簡體   English   中英

刷新后如何讓用戶登錄 Firebase 應用程序?

[英]How do I keep a user logged into a firebase app after refresh?

我有一個內置 firebase 和 angular 的應用程序,我希望能夠在刷新頁面后讓用戶保持登錄狀態。 現在我有一個登錄屏幕,其中包含兩個綁定到控制器的基本輸入字段

    this.email = "";
    this.pass = "";
    this.emessage = "";

    this.loginUser = function() {
        ref.authWithPassword({
            email: this.email,
            password: this.pass
        }, function(error, authData) {
            if (error) {
                console.log("Login Failed!", error);
                this.emessage = error.message;
                $scope.$apply();
            } else {
                dataStorage.uid = authData.uid;
                $location.path('/projects');
                $scope.$apply(); 
            }
        }.bind(this));
    }

這一切都很好,而且很有效,但是當用戶刷新頁面時,他們會被注銷。 有沒有辦法在控制器加載時查看用戶是否已經登錄並自動重定向? 謝謝!

您現在擁有的代碼處理用戶登錄的情況。 要處理用戶已經登錄的情況,您可以監控身份驗證狀態。 來自有關監控身份驗證狀態Firebase 文檔

// Create a callback which logs the current auth state
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
  if (authData) {
    console.log("User " + authData.uid + " is logged in with " + authData.provider);
  } else {
    console.log("User is logged out");
  }
});

通常,您只想在此函數的else中顯示登錄按鈕。

正如評論中提到的,接受的答案不再有效。 當前檢查用戶是否登錄的方法是

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  }
});

(來自https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged

我面臨的挑戰是我的 Web 應用程序具有具有受保護功能的公共頁面。 使用以下代碼,用戶始終先通過 Firebase SDK 加載(如果已登錄)。 但如果頁面需要身份驗證,也會被重定向到登錄頁面。 這適用於頁面重新加載。

Router.beforeEach((to, from, next) => {

  // If route required authentication
  if (to.matched.some(record => record.meta.requiresAuth)) {

    // Load user
    firebase.auth().onAuthStateChanged(user => {

      // If user obj does not exist --> redirect to login page
      if (!user) {
        next({ name: 'login' });
      } else {
        store.commit("user/SET_USER", user);
        user.getIdToken().then(token => {
          store.commit("user/SET_TOKEN", token)
        });

        next();
      }
    });
  } else {

    // Path does not required auth - Still we check the user
    firebase.auth().onAuthStateChanged(user => {

      // If user exist (is logged in) --> store in state.
      if (user) {  
        store.commit("user/SET_USER", user);
        user.getIdToken().then(token => {
          store.commit("user/SET_TOKEN", token)
        });
        next();

      } else {
        next();
      }
    });
  }
})

對於任何 ReactJS 用戶,這是我根據此線程中提供的答案創建的一個簡單 Hook,如果當前用戶未登錄,它會將用戶重定向到登錄路由。

import { useEffect } from 'react';
import * as firebase from 'firebase';
import { useHistory } from 'react-router-dom';

export default function useProtectedRoute() {
  const history = useHistory();

  useEffect(() => {
    firebase.auth().onAuthStateChanged(function(user) {
      if (!user) {
        console.error(
          'Access to protected route denied, redirecting to login...'
        );
        history.push('/auth/login');
      }
    });
  }, [history]);
}

你只需要導入這個鈎子並在任何你不想渲染的組件中運行,除非用戶登錄。

例子:

import React from 'react';
import useProtectedRoute from 'hooks/useProtectedRoute';

export default function UserDetailsComponent() {
  useProtectedRoute();
  return <div>This is only visible when user is logged in</div>;
}

如果您使用的是 Angular 4,則可以使用AngularFire2 - 官方 Firebase 集成。

我有一個包裝 AngularFire2 的 AuthService。 我只是在 Service 的構造函數中檢索 AuthSession 並在需要時使用。 例子:

@Injectable()
export class AuthenticationService {

    private authState: any;

    constructor(public afAuth: AngularFireAuth) {
        this.afAuth.authState.subscribe((auth) => {
          this.authState = auth
        });
    }

    get user(): any {
        return this.authenticated ? this.authState : null;
    }
}

此處為完整身份驗證服務代碼 Full Angular 4 with Firebase 示例在此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM