簡體   English   中英

如果用戶存在,則僅使用 Google 身份驗證提供程序進行身份驗證

[英]Only authenticate with Google Auth Provider if user exists

我正在使用 Firebase 使用GoogleAuthProvider對我們應用中的用戶進行身份驗證。 但是,如果新用戶還不是經過身份驗證的用戶,我不希望他們登錄。

如果用戶存在,則將其登錄並console.log('user ' + user.email + ' does exist!'); .

但是,如果用戶不存在 然后不允許身份驗證和console.log('user ' + user.email + ' does not exist!')

var googleProvider = new firebase.auth.GoogleAuthProvider();
export const doSignInWithGoogle = () => auth.signInWithPopup(googleProvider);

googleLogin = () => {
    auth
      .doSignInWithGoogle()
      .then(result => {
        var user = result.user;
        const userRef = db.collection('users').doc(user.uid);
        userRef.get().then(docSnapshot => {
          if (docSnapshot.exists) {
            userRef.onSnapshot(() => {
              console.log('user ' + user.email + ' does exist!');
            });
          } else {
            console.log('user ' + user.email + ' does not exist!');
          }
        });
      })
      .catch(error => {
        this.setState(updateByPropertyName('error', error));
      });
  };

我認為在 Firestore 中引用用戶記錄是一種簡單的方法。 但是,也許 Firebase Auth 已經有辦法做到這一點。 我找不到文檔或任何示例。

在上面的代碼中,沒有記錄任何內容,並且用戶被創建或登錄。

如何阻止新用戶注冊,同時仍允許當前用戶登錄?

如果你真的想使用signInWithPopup方法,你有這個選項,但這不是最好的方法。 當您使用 google 登錄時, signInWithPopup方法會返回一個承諾。 您可以訪問isNewUser財產additionalUserInfo從生成的對象。 然后刪除您剛剛創建的用戶。

firebase.auth().signInWithPopup(provider).then(
     function (result) {
          var token = result.credential.accessToken;
          var user = result.user;

          //this is what you need
          var isNewUser = result.additionalUserInfo.isNewUser;
          if (isNewUser) {
               //delete the created user
               result.user.delete();
          } else {
               // your sign in flow
               console.log('user ' + user.email + ' does exist!');
          }
     }).catch(function (error) {
     // Handle Errors here.

});

這是簡單的方法,但創建后刪除不是最佳做法。 還有一個選擇,

您可以為此使用signInAndRetrieveDataWithCredential方法。 根據文檔

如果使用來自firebase.auth.EmailAuthProvider.credential的憑據登錄並且沒有與給定電子郵件對應的用戶,則auth/user-not-found將被拋出。

function googleSignInWithCredentials(id_token) {
     // Build Firebase credential with the Google ID token.
     var credential = firebase.auth.GoogleAuthProvider.credential(id_token);

     // Sign in with credential from the Google user.

     firebase.auth().signInAndRetrieveDataWithCredential(credential)
          .then(function (userCredential) {
               //sign in
               console.log(userCredential.additionalUserInfo.username);
          }).catch(function (error) {
               // Handle Errors here.
               var errorCode = error.code;
               if (errorCode === 'auth/user-not-found') {
                    //handle this
               } else {
                    console.error(error);
               }
          });
}

是來自 firebase github repo 的示例。

使用Firebase安全規則,只能檢查密鑰是否存在 - 因此在用戶表中搜索不是一個選項:

"emails": {
    "example1@gmail.com": true,
    "example2@gmail.com": true
}

然后可以檢查安全規則,如果auth.token.email作為密鑰存在:

{
    "rules": {
        ".read": "root.child('emails').child(auth.token.email).exists(),
        ".write": false,
    }
}

在客戶端,這應該拋出"The read failed: Permission denied error"錯誤,然后進行相應處理。 連接到 Firebase 注冊是不可能的 - 但雖然他們無法登錄,但這樣做也有同樣的作用(除了必須不時清理用戶數據庫); 例如。 使用雲功能刪除用戶,這些用戶沒有將他們的電子郵件作為emails “表”中的鍵。

Firestore安全規則中,可以檢查:

  • request.auth.token.email & request.auth.token.email_verified

例如,一個名為emails的集合和一個名為content的集合:

match /databases/{database}/documents {

    function userMatchesId(userId) {
        return request.auth != null && request.auth.uid == userId
    }
    function readAllowed(email) {
        return if get(/databases/$(database)/documents/emails/$(request.auth.token.email)).data != null
    }

    match /users/{userId} {
        allow get: if userMatchesId(userId)
    }
    match /content {
        allow get: if readAllowed(request.auth.token.email)
    }
}

您在登錄后從isNewUser收到的對象具有additionalUserInfo ,其中您具有屬性isNewUser

您可以在此處找到參考: https : //firebase.google.com/docs/reference/js/firebase.auth.html#.AdditionalUserInfo

暫無
暫無

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

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