Firebase passing Authentication between web pages - javascript

i don't know how to share the authentication between my web. For example, i want to pass authentication to home page after user logged in in login.html.
What is the problem:
After user logged in in login.html, the authentication is created.
//login.html
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
}
However, i need to change location.href to home.html after user logged in.
//login.html
if (user) {
// User is signed in.
location.href = "home.html";
}
So, what is the solution that keep the authentication when changing web page?
//home.html
if (user) {
//
}else {
// No user is signed in.
}
web/login.html <--> web/home.html

Firebase keeps track of the authentication state between pages by storing the session id in local storage.
The best way to ensure a smooth flow for you users is to monitor the authentication state. From that documentation:
The recommended way to get the current user is by setting an observer on the Auth object:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
By using an observer, you ensure that the Auth object isn't in an intermediate state—such as initialization—when you get the current user.

Related

Keep logged in between reloads - Firebase (Sign in with Google)

How do you keep a user logged in with Sign in with Google between reloads?
Here is my login function (Firebase):
const loginWithGoogle = async () => {
try {
const provider = new firebase.auth.GoogleAuthProvider();
const res = await firebase.auth().signInWithPopup(provider);
$user = res.user;
$isLoggedIn = true;
}
catch (error) {
console.log(error);
}
}
Although $isLoggedIn and the $user object save to LocalStorage (I'm using SvelteJS), the user does not actually stay logged in after reloading.
After reloading, admin users are no longer able to write to the database and I get the error firestore: PERMISSION_DENIED: Missing or insufficient permissions.
(Here are my firestore rules)
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read;
allow write: if (request.auth != null && (request.auth.uid == "someAdminID" || request.auth.uid == "otherAdminID"));
}
}
How would I stay logged in after reloading? Or is there some way to automatically log in again if the user had not previously logged out?
On most browser environments Firebase automatically persists the user credentials in local storage, and restores them when the app/page reloads. This requires it to make a call to the server however, a.o. to check if the account was disabled, and thus it isn't completed right away when the page loads.
To react to when the authentication state is restored (or otherwise changes), you'll want to use an auth state listener as shown in the first code snippet in the documentation on getting the currently signed in user:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
// ...
// 👈 This is where you can also query the database as the user for the first time
} else {
// User is signed out
// ...
}
});

How to store firebase authentication session

I have a web application made in vue with firebase authentication. The problem here is that I need to login every time I reload the page.
Firebase Authentication by default stores the user's credentials in local storage of the browser, and restores it from there when the page reloads. This requires a call to the server though, which means that if you access Firebase.auth().currentUser immediately as the page loads, it might not be set yet.
To prevent having this problem, use an auth state listener as shown in the first snippet of the documentation on getting the current user.
For v8 and earlier of the SDK that'd be:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
For v9:
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});

storing user uid instead of refresh token to keep user signed in?

I am using Firebase authentication in my project and my question is, what is the problem of storing just user uid instead of refresh token that expires in short time so i can keep user logged in.
I am using signInWithEmailAndPassword ,method to sign in users and get user object from firebase.auth().onAuthStateChanged
firebase.auth().onAuthStateChange(authUser=> setUser(authUser))
Now i can use authUser.user.uid and store it in localStorage.
My question is not related to firebase or any other library, but i am asking about a general behavior, what is the problem in storing something that don't expire??
My question is, how bad is doing this??
You may want to use Authentication State Persistence like the example below:
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(function() {
// Existing and future Auth states are now persisted in the current
// session only. Closing the window would clear any existing state even
// if a user forgets to sign out.
// ...
// New sign-in will be persisted with session persistence.
return firebase.auth().signInWithEmailAndPassword(email, password);
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});
Learn more about it here

Is it possible to use session cookies in Firebase to stay logged in without firebase-admin package?

I'm using firebase in my next.js app to login. My login works but logs out every time a user changes paths inside the site. Once logged in, the user is redirected to the front page with path=/ if a user changes paths to path=/question/page firebase immediately logs them out but their session cookie has not expired. I would like to use the session cookie to keep a user logged in until it expires no mater where they navigate on the site. I am not about to use the package firebase-admin because it keeps crashing my next.js site. I can only use the regular firebase package which includes firebase.auth() along with js-cookie package. Here is the code I am using to set my cookie:
componentDidMount() {
let user = firebase_auth.currentUser;
console.log("User: ", user);
if (user) {
this.setState({user_logged_in: true});
return firebase_auth.currentUser.getIdToken(true).then(function (token) {
Cookies.set('__session', token, {expires: 7});
})
}
else {
this.setState({user_logged_in: false})
}
}
How would I be able to use the session cookie being called in the code above so that my users aren't being logged out every time they navigate to a new path?
Thanks for your help in advance!
Firebase Authentication SDKs automatically persist the user state between page/app reloads, and try to restore that state upon the restart.
The most likely cause of your problems, is that Firebase is still checking whether the authentication state is valid when you access firebase.auth().currentUser.
In that case, the solution is to use an auth state listener:
componentDidMount() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
this.setState({user_logged_in: true});
firebase_auth.currentUser.getIdToken(true).then(function (token) {
Cookies.set('__session', token, {expires: 7});
})
} else {
this.setState({user_logged_in: false})
}
});
}

Firebase for web: telling whether user is logged in or not

I have a web app built on Firebase's web library. I want to restrict some pages to only users who are logged in.
This code triggers when firebase detects the user is logged in, which is good.
firebase.auth().onAuthStateChanged(function (user) {
console.log('User is logged in');
});
But I can't get anything to reliably check whether the user is not logged in without leaving the page before the above code has a chance to check...
var check_firebaseReady == false;
function local_initApp() {
if (check_firebaseReady == false) {
if (typeof firebase !== 'undefined') {
check_firebaseReady = true;
console.log(firebase.auth().currentUser); //not reliable becuase it may return an empty user before it has a chance to get an existing user
}
setTimeout(function () {
local_initApp();
}, 300);
}
}
local_initApp();
I think for single page apps, you have to use the onAuthStateChanged listener and enforce access via security rules on specific data. If you want to block access to a complete page, you are better off using a cookie system. Firebase Auth provides that option: https://firebase.google.com/docs/auth/admin/manage-cookies
With cookies, you would check and verify the cookie server side, otherwise, not serve the page and show some error or redirect to login page instead.

Categories

Resources