【问题标题】:Firebase Auth+Functions | create user with displayNameFirebase 身份验证+功能 |使用 displayName 创建用户
【发布时间】:2018-07-22 08:31:01
【问题描述】:

我试图用 displayName 创建一个用户。如果我在创建后更新用户配置文件,它实际上可以工作。但我也在需要显示名称的地方使用云函数 auth.onCreate。但是 event.data 没有给我显示名称。我猜是因为触发云功能时,配置文件没有更新。知道如何在我的云函数中访问 displayName 吗?

我尝试这样做的原因是因为我想确保 displayNames 是唯一的。因此,当人们注册时,他们必须留下用户名。如果它已经存在于我的数据库中,他们必须再取一个。

我如何使用 Javascript 创建用户:

firebase.auth().createUserWithEmailAndPassword(this.email, this.password).then(
        (user) => {
            user.updateProfile({
                displayName: username
            }).then(() => {
                user.sendEmailVerification().then(
                    () => {
                        firebase.auth().signOut()
                        this.complete = true
                    }).catch(function(err) {
                    console.log(err.message)
                })
            })
        }
    )

我的云功能:

exports.createUser = functions.auth.user().onCreate(event => {
  let user = event.data;
  var userObject = {
    displayName: user.displayName, // undefined
    wins: 0
  }

  admin.database().ref('/users/' + user.uid).set(userObject).then(() => {
    return true
  })
});

【问题讨论】:

    标签: javascript firebase firebase-authentication google-cloud-functions


    【解决方案1】:

    几周前我遇到了完全相同的问题。我相信在onCreate 事件期间没有办法使用displayName(文档中的代码不起作用)。到目前为止,这是我所做的。

    创建一个函数来处理从客户端更新用户的访问令牌。

    updateUserProfile(name: string, photoURL: string) {
        const data = {
          displayName: name,
          photoURL: photoURL
        };
    
        return this.afAuth.auth.currentUser.updateProfile(data)
          .then(() => {
            console.log('Successfully updated default user profile');
    
            // IMPORTANT: Force refresh regardless of token expiration
            return this.afAuth.auth.currentUser.getIdToken(true);
          })
          .then(newToken => {
            console.log('Token refreshed!', newToken);
            return newToken;
          })
          .catch((err) => console.log(err));
     }
    

    使用更新的令牌创建 HTTP 触发器。

    const data = {
      displayName: this.displayName,
      photoURL: this.photoURL,
    };
    
    this.userService.updateUserProfile(this.displayName, this.photoURL).then(accessToken => {
      // Better: Store token in local storage
      const url = 'https://cloud function endpoint';
      this.http.post(url, JSON.stringify(data), {
        headers: {'Authorization': accessToken, 'Content-Type': 'application/json; charset=utf-8'}
      }).subscribe((res) => {
        // Went well
      }, (err) => {
        // Went wrong
      });
    });
    

    创建一个云函数来处理将用户的displayName 更新到您的服务器。

    看看 Firebase 提供的sample code。

    const app = express();
    
    app.use(cors({ origin: true }));
    
    app.use((req, res, next) => {
      if (!req.headers.authorization) return res.status(403).json({ message: 'Missing Authorization Header' });
      ... handle JWT
    });
    
    app.post('/', (req, res) => {
      const batch = admin.firestore().batch();
      const data = req.body;
      const userState = {
        displayName: data.displayName,
        photoURL: data.photoURL,
      };
      ... commit batch update
    });
    

    这 100% 取决于您,并且可能有更好的方法来处理更新用户的 displayName。 请注意,用户经常更改其显示名称和个人资料照片。每次用户更新他们的默认配置文件时,您都应该更新令牌并将其存储在本地存储中。

    注意:如果令牌过期,Firebase 将刷新令牌并为您返回一个新令牌。

    如果您真的想在onCreate event 期间初始化用户的displayName,那么您可以尝试以下操作。

    exports.createUser = functions.auth.user().onCreate(event => {
      let user = event.data;
      const displayName = user.displayName || 'Anonymous';
      ...Update operation code goes below
    });
    

    希望对你有帮助。

    【讨论】:

    • 您可以通过将所有逻辑移至 Cloud Function 来简化此解决方案,并从那里使用 firebase-admin API 更新用户 displayName 或任何其他身份验证数据 admin.auth().updateUser(uid, data) 并执行任何数据库更新.类似this answer
    • 嘿杰夫。 user.displayName 属性的值在创建帐户时传递给 Cloud Functions,因为它存在。由于对于电子邮件+密码帐户,displayName 是在第二个 API 调用中设置的,因此该值在 Cloud Functions 触发器中不可用。您的辅助调用方法确实是一个很好的解决方法。
    猜你喜欢
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2018-03-10
    • 2019-03-28
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多