How to persist a Firebase login?

11,342

Solution 1

I've figured out how to do this. Maybe it's not the most correct anwser for it, but it worked for me. I used localSotrage to store the username and password. I could store the tolken as well, but I want to create a "remember password" screen. When I do my first login I do this in my service.

service.js when I store the user data;

localStorage.setItem("uPassword",password);
localStorage.setItem("uEmail",email);
And I add the following if statement in my controller. If i already did the login, I use the e-mail and password to login again. If I dont, I wait to user press the button and call de function in my service.

controller.js if statement:

if(localStorage.getItem("uEmail")!==undefined && localStorage.getItem("uPassword")!==undefined) {
  LoginService.CustomLogin(localStorage.getItem("uEmail"),localStorage.getItem("uPassword"))
 }

Solution 2

To re-iterate the point of don't persist the login yourself, firebase does this for you. I am referencing this from typescript FYI.

In the official docs() :

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)

Where local is on disk.

Then later in your code all you need to do is subscribe to the onAuthStateChanged observable.

this.firebase.auth.onAuthStateChanged(user => {
  if (user){

Do not persist the plain text password yourself!!!! Firebase persists a user with uid, session API keys etc.

Just follow the Firebase docs. Persisting plain text password will result in a bad security audit.

Solution 3

You shouldn't persist username and password to storage, if you have to then at least store the password as a hash.

Firebase has the following for signing in again: firebase.auth().onAuthStateChanged(user => {

});

Solution 4

Newer version:

Initialize the app like this to keep the user logged in even after the browser is closed and reopened on the same device.

import { initializeApp } from 'firebase/app';
import { getAuth, browserLocalPersistence, setPersistence } from 'firebase/auth'

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
(async () => {
    await setPersistence(auth, browserLocalPersistence);
})();

To get the user object you can use React Firebase Hooks:

import { useAuthState } from 'react-firebase-hooks/auth';

const [user, loading, error] = useAuthState(auth);
Share:
11,342
Lucas Gaspar
Author by

Lucas Gaspar

Updated on July 02, 2022

Comments

  • Lucas Gaspar
    Lucas Gaspar about 2 years

    I'm doing an app with Ionic Framework and Firebase. I made a custom login to get data inside Firebase, but every single time the app is restarted I need to login again. How can I persist the login? The user should login the first time, and not need to do it again.

    Here is my service:

    (function() {
    	'use strict';
    
        angular
            .module('mytodo.login')
            .factory('LoginService', LoginService);
    
        LoginService.$inject = ['$state', '$ionicLoading', '$firebaseAuth', '$firebaseObject','$rootScope', '$timeout', 'fb', '$q'];
    
        function LoginService($state, $ionicLoading, $firebaseAuth, $firebaseObject, $rootScope, $timeout, fb, $q){
            
    
            var service = {
                CustomLogin: CustomLogin,
                GetCurrentUser: GetCurrentUser,
                RegisterUser: RegisterUser,
            };
            return service;
    
            function CustomLogin(email, password) {
                if(email ==null | password == null){
                    console.log('Preencha todos os campos!');
                    return;
                }
    
                $ionicLoading.show({
                    showBackdrop: false,
                     template: '<p>Carregando...</p><ion-spinner icon="android" style="stroke: #1d9c9e;fill:#1d9c9e;"></ion-spinner>'
                });
    
                $firebaseAuth().$signInWithEmailAndPassword(email, password).then(function(authData) {
                    $rootScope.currentUser = GetCurrentUser(authData.uid);
    
                    $timeout(function() {
                        $ionicLoading.hide();
                        $state.go('tab.todo', {});
                    }, 1000);
    
                }).catch(function(error) {
                    showToast();
                   
                    $ionicLoading.hide();
                    
                    console.log(error);
                });
            }
    
             function showToast(){ 
                ionicToast.show('Usuário ou senha inválido', 'middle', false, 1500);
            }
    
    
            function GetCurrentUser(userId) {
                var query = fb.child('/users/' + userId);
                var currentUser = $firebaseObject(query)
                return currentUser;
            }
    
            function SaveUser(authData) {
    
                console.log(authData.uid);
                var deffered = $q.defer();
                
                var uid = authData.uid;
                var user = {
                    displayName: authData.displayName,
                    name: authData.displayName,
                    photoURL: authData.photoURL,
                    email: authData.email,
                    emailVerified: authData.emailVerified,
                    providerId: authData.providerData[0].providerId
                };
    
                var ref = fb.child('/users/' + uid);
                ref.once("value")
                    .then(function(snapshot) {
                        if (snapshot.exists()) {
                            console.log('User already exists');
                        } else {
                            ref.set(user);
                        }
    
                        deffered.resolve(snapshot);
                    });
    
                return deffered.promise;
            };
    
            function RegisterUser(user) {
                var deffered = $q.defer();
                $ionicLoading.show();
                $firebaseAuth().$createUserWithEmailAndPassword(user.email, user.password).then(function(authData) {
                    var newUser = {
                        name: user.name,
                        email: user.email,
                        providerId: authData.providerData[0].providerId
                    };
    
                    var userId = authData.uid;
                    var ref = fb.child('/users/' + userId);
                    ref.once("value")
                        .then(function(snapshot) {
                            if (snapshot.exists()) {
                                //console.log('User already exists');
                            } else {
                                ref.set(newUser).then(function(user){
                                    $rootScope.currentUser = GetCurrentUser(userId);
                                })
                            }
    
                            deffered.resolve(snapshot);
                            CustomLogin(user.email, user.password);
                        });
                }).catch(function(error) {
                    $ionicLoading.hide();
                    var errorCode = error.code;
                    console.log(errorCode);
    
                    if(errorCode === 'auth/weak-password')
                        ionicToast.show('Erro, a senha precisa ter no mínimo 6 digitos.', 'middle', false, 3000);
                    
                    if(errorCode === 'auth/email-already-in-use')
                        ionicToast.show('Erro, o email: ' + user.email + ' já existe em nossa base de dados.', 'middle', false, 3000);
                })
    
                return deffered.promise;
            };
        }
    })();