Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist a Firebase login?

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;
        };
    }
})();
like image 515
Lucas Gaspar Avatar asked Nov 27 '22 20:11

Lucas Gaspar


2 Answers

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.

like image 161
Christo Goosen Avatar answered Dec 05 '22 21:12

Christo Goosen


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);
like image 35
VRSEN Avatar answered Dec 05 '22 19:12

VRSEN