Firebase Google登录(网络)流程

CK *_*vir 3 javascript web firebase firebase-authentication

引用此链接

大家好。这是我的代码,我有两个问题

首先,我想知道我的登录流程是否正确?

我的逻辑是当用户进入我的索引页面时

我将首先检查用户登录状态

如果用户未登录,则要求用户登录。

    function google_login_in(){
        var provider = new firebase.auth.GoogleAuthProvider(); 
        provider.addScope('https://www.googleapis.com/auth/plus.login');
        firebase.auth().signInWithPopup(provider).then(function(result) {
            var token = result.credential.accessToken;
            var user = result.user;
        }).catch(function(error) {
            var errorCode     = error.code;
            var errorMessage  = error.message;
            var email         = error.email;
            var credential    = error.credential;
        });         
    }

    function print_user(user) {
        user.providerData.forEach(function (profile) {
            console.log("Sign-in provider: "+profile.providerId);
            console.log("  Provider-specific UID: "+profile.uid);
            console.log("  Name: "+profile.displayName);
            console.log("  Email: "+profile.email);
            console.log("  Photo URL: "+profile.photoURL);
        });
    }

    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            print_user(user);
        } else {
            google_login_in();
        }
    });
Run Code Online (Sandbox Code Playgroud)

其次是如何使用“ signInWithRedirect”?

链接显示“要通过重定向到登录页面登录,请致电signInWithRedirect

因此,如果用户已经登录,并且我想重定向到“ B.html”页面

如何使用此功能?

firebase.auth().signInWithRedirect("B.html");
Run Code Online (Sandbox Code Playgroud)

Mic*_*igh 5

您的流程通常还可以,尽管您可能不想google_login_in()onAuthStateChanged以下两个方面触发:

  1. 侦听器可能null在初始化期间触发。它旨在作为登录状态的积极指标,并且只有用户的存在(而不是不存在)才是可靠的。
  2. 浏览器将忽略打开并非源自用户操作的弹出窗口的请求。例如,您应该将登录附加到按钮的click事件上,或使用signInWithRedirect

这使我进入signInWithRedirect()-这并不意味着您的应用程序将重定向,而不是Firebase Auth过程将通过重定向而不是在弹出窗口中进行。可以在没有用户交互的情况下触发此操作,但是它将触发整个页面的重新加载,使用户离开当前页面,然后将其带回。

如果要在验证用户身份后重定向到其他URL,则应等待直到onAuthStateChanged表明用户已登录,然后使用例如window.location = '/B.html'