firebase 如何让用户在刷新后保持登录状态?

1qczuiv0  于 2023-02-25  发布在  其他
关注(0)|答案(6)|浏览(137)

我有一个内置了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));
    }

这一切都很好,很好用,但是当用户刷新页面时,他们又退出了。有没有什么办法,当控制器加载时,看看用户是否已经登录并自动重定向?谢谢!

q43xntqr

q43xntqr1#

现在的代码处理用户登录的情况,要处理用户已经登录的情况,可以使用onAuthStateChanged方法:

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

通常,您只希望在此函数的else中显示登录按钮。
在较新的(v9及更高版本)模块化SDK中,这将是:

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in.
    // ...
  } else {
    // User is not signed in.
    // ...
  }
});

另请参阅firebase.auth.Auth和获取当前登录用户的文档。

z3yyvxxp

z3yyvxxp2#

就像评论中提到的,接受的答案不再起作用了。目前检查用户是否登录的方法是

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

(from https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged)

enxuqcxy

enxuqcxy3#

我的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();
      }
    });
  }
})
jpfvwuh4

jpfvwuh44#

对于任何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>;
}
pcww981p

pcww981p5#

如果您使用的是Angular 4,则可以使用AngularFire2-官方Firebase集成。
我有一个 Package AngularFire 2的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;
    }
}

完整身份验证服务代码here Full Angular 4,带有Firebase示例here

相关问题