Firestore如何使用FirebaseUI登录时将用户文档添加到集合中

时间:2019-01-11 00:21:08

标签: firebase vue.js google-cloud-firestore firebaseui

当新用户登录时,我正在尝试将新文档uid加载到Firestore集合users中。

我正在使用FirebaseUI + VueJS,并尝试使用signInSuccessWithAuthResult回调填充数据。 (如果有更好的方法,请告知)。

更新:我重构了代码(如下),至少现在Firebase引发了错误:

Function CollectionReference.doc() requires its first argument to be 
of type non-empty string, but it was: undefined  Dismiss

以下是可能无法成功的尝试之一。您对代码示例的帮助将不胜感激。

firebase-config.js:

import firebase   from 'firebase';
import firebaseui from 'firebaseui'

import { usersCollection } from '@/services/registerFirebase'

export const FBuiConfig = {
    signInSuccessUrl: '/dashboard',
    signInFlow: 'popup',

    callbacks: {
        signInSuccessWithAuthResult: function(authResult, redirectUrl) {
            const userUid       = authResult.uid;
            const email         = authResult.email;
            const displayName   = authResult.displayName;
            const photoURL      = authResult.photoURL;
            const lastLoginAt   = authResult.lastLoginAt;
            const createdAt     = authResult.createdAt;
            setUser(userUid, email, displayName, photoURL, lastLoginAt, createdAt);
            return false;
        },

        uiShown: function() {
            document.getElementById('app-drawer').style.display = 'none';
            document.getElementById( 'app-toolbar').style.display = 'none';
        },
    },

    signInOptions: [
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        {
            provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
            requireDisplayName: true,
            forceSameDevice: true,
        },

        firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID,
    ],

    tosUrl: '/tos',
    privacyPolicyUrl: function() {
        window.location.assign('/pp');
    }
};

function setUser(userUid, email, displayName, photoURL, lastLoginAt, createdAt) {
    const user = {
        useruid         : userUid,
        useremail       : email,
        displayname : displayName,
        photourl        : photoURL,
        lastlogin       : lastLoginAt,
        created         : createdAt,
        calendarEvents: []
    }
    usersCollection.doc(userUid).set(user);
}

1 个答案:

答案 0 :(得分:0)

authResult不是用户,但拥有用户。

const user = authResult.user;

然后您可能要确保登录确实有效:

if (user) {
          const userUid       = user.uid;
          const email         = user.email;
          const displayName   = user.displayName;
          const photoURL      = user.photoURL;
          const lastLoginAt   = user.lastLoginAt;
          const createdAt     = user.createdAt;
}

return user != null;

文档中有一个很好的例子,请遵循此link