Enforce Firebase Authentication on Page - javascript

I am using Firebase Authentication with Firebase UI to protect pages by requiring a user to be logged in.
In the documentation I don't see what script we need to use on the top of each page in order to determine if user is logged in. If they are not logged in I want to redirect them to the logon page.
In simple PHP, I can do the following:
require_once("./include/membersite_config.php");
if(!$fgmembersite->CheckLogin())
{
$fgmembersite->RedirectToURL("login.php");
exit;
}
I don't see what is needed to be included in the Firebase JS authentication (and/or using Firebase UI).

In JavaScript you can detect whether the user is signed in with:
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
See the Firebase documentation on determining what user is signed in.

Related

React-Firebase Authentication

I am having a react application with firebase as authentication. My authentication code is below
await firebase.auth().onAuthStateChanged((user) => {
if (user) {
props.setUser(user); //setting the user if login/register happens
history.push(`/admin/dashboard`);
console.log("user",user)
} else {
props.setUser(null); //blocks the user to get into the app if he/she is not logged in
history.push("/");
}
});
So, when user logs in..he will be navigated to /admin/dashboard. suppose when am in /admin/home and when i refresh the page, it goes again to admin/dashboard which shouldn't happen. so I tried
history.push(${props.location.pathname}); it works correctly after the refresh, it stays on the same page when the application is logged in. but when I restart the server again when I try to log in, it says no redirect url is specified. Got stuck on this for a long time.. Any help is welcome.Thanks
What your code does is check if the user is logged in and only let the user access the data if so.
You should do that in the fireabse rules (= serverside) as this is way more secure.
You didn't provide the kind of FirebaseDB you are using. So assuming you use the Realtime Database here are some according rules:
{
“rules”: {
“.read”: “auth != null”,
“.write”: “auth != null”
}
}
You should maybe check the rules before deploying your app, because now every authenticated user can change/add/delete data, but you get the point. This does exactly what you want so you won't even need to perform a check in your ReactJS App. Firebase will automatically deny unauthenticated users the access to the database.
Btw: You should try to implement security relevant things in the Firebase Rules. Ideally you want your rules to be written in a way that you don't need to perform any validation inside your ReactJS app. Firebase rules can get quite complex. I experienced that myself when writing a chat app with chatrooms and everything. But it is definitly worth the effort if your app is more secure after.

Firebase Authentication - Logged In User Is Null

I have managed to setup a custom login system using Firebase. The user enters email/password and is redirected to the main page(which is private). I am having issue with onAuthStateChanged after logging in. When I check the auth state after logging into the main page, i get invalid user (null). The firebase dashboard shows I have logged in successfully but onAuthStateChanged is the opposite.
I am trying to check if a user is logged in to my html pages, if not I want to redirect them to the login page. I like how the authentication works in firebase but I need to protect my html pages not my divs (which is what the vast majority of firebase auth tutorials show).
If anyone has an easier way to password protect a web directory that looks nicer than HTaccess, please advise (I am not crazy about using wordpress for password protection, but its an option). Otherwise, I guess I will have to do this in PHP. Thanks in advance!
(function () {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
console.log(user);
console.log('A user is logged in.');
} else {
// No user is signed in.
console.log('Invalid user. Redirecting to root.');
window.location.replace('../index.html');
}
});
})();
If you navigate to a new page, Firebase will have to initialize again. As part of that it will try to restore the user's authentication state, but this requires a call to the server which takes time.
For that reason the onAuthStateChanged listener will initially fire with null as the current user (and auth.currentUser is set to null). Then once the user is signed in, the listener fires again with the user object for that user.
If you want to detect this initial state, you can either store some token value in the browser's local storage that you can check for yourself on the new page, or you could set a time-out for when you expect the user to be re-signed in and only then navigate away to the index.html page.

Only let pre-verified users log into Firebase

Right now, I only want users who have already registered and been verified with our software to login, and I have saved the list of emails of users (stripped of special characters) inside Firebase. Currently, when the user logs in, I use the following function to check if their email is in this list:
function isEmailValid(userEmail, trueCallback, falseCallback) {
var emailHash = userEmail.replace(/[^a-zA-Z0-9]/g, "");
firebase
.database()
.ref("validEmails/" + emailHash)
.on("value", snapshot => {
if (snapshot.val()) {
trueCallback(snapshot.val());
} else {
falseCallback();
}
});
}
Although this method works, it is quite unwieldy, as the user is still able to log in initially before the function callback is called, and their email is still shown in the "Authentication" tab in Firebase.
Is there a better way to only allowed pre-verified users to log into Firebase?
I'm pretty sure this has been covered before: there currently is no way to prevent users from signing in with Firebase Authentication. But if you want to prevent them from accessing backend resources, you can check whether their email address is verified either in the server-side security rules (for Realtime Database, Storage, or Firestore), or in your own server-side code.
At I/O a demo was given of upcoming functionality in Cloud Function that would allow you to prevent signing in users without a verified email address. But I don't know when this functionality will available in a public API.
Also see:
Firebase Prevent Creating Account Before Email Verification
How to prevent user authentication in Firebase/Vue.js BEFORE email is verified
How do I lock down Firebase Database to any user from a specific (email) domain?

PWA blank page Facebook

I have a PWA app where one of the options you have to sign-in is Facebook, everything goes well and if you're in the browser the login works really well. The problem happens when you add the website to your mobile and it opens in PWA and you click log-in from Facebook it opens a blank page and it doesn't redirect to the app, if you close the page, go back to the app and click again facebook the user is logged in, but does anyone has any idea how to get rid of the white/blank page?
I have tried 'redirect_uri' and 'display: touch,' but none of this seems to be working anymore.
A blank page after login is a common problem when using Facebook as a sign-in method, especially when we’re in development mode.
It happens because you already logged in and authorized the app, so when it tries to log-in again, it goes blank.
The most straightforward way to fix this is first to check if the user has already logged in and authorized your app before calling the .login() function.
Luckily, Facebook provides a function to do it, where they handle (almost) everything for you.
The getLoginStatus() function
The getLoginStatus() functions determines 1) if a user is signed into Facebook and 2) if the user has already authorized your app.
There are three possible states for a user:
The user is logged into Facebook and has authorized your app, in this case, the function will return: connected.
The user is logged into Facebook but has not authenticated your application, in this case, the function will return: not_authorized.
The user is either not logged into Facebook or explicitly logged out of your application, in this case, we don’t know which one is it, that’s why it returns: unknown.
For example:
When we call getLoginStatus() we’ll get an object similar to this:
{
authResponse: {
userID: '12345678912345',
accessToken: 'kgkh3h4gkh3g4k2h4gk23h4gk2h34gk234gk2h34AndSoOn',
session_Key: true,
expiresIn: '5183738',
sig: '...'
},
status: 'connected'
}
There you can see there’s an authResponse object and a status object. We’ll focus on the status object first, checking for each of the three possible responses.
this.facebookProvider.getLoginStatus(response => {
if (response.status === 'connected') {
// User Authenticated and your App is authorized
} else if (response.status === 'not_authorized') {
// User authenticated but your app isn't authorized yet.
} else {
// the user isn't logged in to Facebook.
}
});
Try this and try to logout first from Facebook before you make call from PWA.

javascript firebase.auth().signInWifEmailAndPassword not be able to get login in firebase

I am working with javascript Firebase in my app.
I'm able to use createUserWithEmailAndPassword successfully in the app. Also, the new user's registration shows inside the Firebase Console.
My question is, how can I check if a user exists or is logged into the browser?
This code will watch to see if there is a logged in user. It is based on the official docs from Firebase. Let me know if you need to know about the flow and authentication tokens etc.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log('There is a user')
} else {
console.log('Nobody is home: Need to login or sign up!');
}
});

Categories

Resources