如何坚持Firebase登录?

问题描述 投票:0回答:3

我正在使用Ionic Framework和Firebase做一个应用程序。我进行了自定义登录以在Firebase中获取数据,但每次重新启动应用程序时我都需要再次登录。如何坚持登录?用户应该第一次登录,而不需要再次登录。

这是我的服务:

(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;
        };
    }
})();
firebase ionic-framework firebase-authentication
3个回答
1
投票

如果您必须至少将密码存储为哈希,则不应将用户名和密码保留到存储中。

Firebase具有以下用于再次登录的内容:firebase.auth()。onAuthStateChanged(user => {

});


1
投票

为了重新尝试不要自己持久登录,firebase会为你做这件事。我从打字稿FYI引用这个。

在官方文档()中:

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

本地在磁盘上的位置。

然后在您的代码中,您需要做的就是订阅onAuthStateChanged observable。

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

不要自己坚持纯文本密码!!!! Firebase使用uid,会话API密钥等来保留用户。

只需按照Firebase文档操作即可。保留纯文本密码将导致错误的安全审核。


-1
投票

我已经想出了如何做到这一点。也许它不是最正确的anwser,但它对我有用。我使用localSotrage存储用户名和密码。我也可以存储tolken,但我想创建一个“记住密码”屏幕。当我第一次登录时,我会在我的服务中执行此操作。

我存储用户数据时的service.js;

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语句:

if(localStorage.getItem("uEmail")!==undefined && localStorage.getItem("uPassword")!==undefined) {
  LoginService.CustomLogin(localStorage.getItem("uEmail"),localStorage.getItem("uPassword"))
 }
© www.soinside.com 2019 - 2024. All rights reserved.