本文介绍了Firebase Auth +功能|使用displayName创建用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to create a user with displayName. It actually works if I update the user profile after creation. BUT I also use a cloud function auth.onCreate where I need the displayName. But event.data doesn't give me the displayName. I guess it's because when the cloud function is triggered, the profile isn't updated. Any idea how I can get access to the displayName in my cloud function?

之所以尝试这样做是因为我想确保displayNames是唯一的.因此,当人们注册时,他们必须离开用户名.如果它已经存在于我的数据库中,则必须再选择一个.

The reason why I try to do this is because I wanna make sure that displayNames are unique. So when people register they have to leave a username. If it already exists in my database they have to take another one.

我如何使用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
  })
});

推荐答案

几周前,我遇到了完全相同的问题.我相信在onCreate事件(文档中的代码无效)期间无法使用displayName.到目前为止,这是我的工作方式.

I had the exact same issue a few weeks ago. I believe there's no way to use displayName during onCreate event (the code in the documentation does not work). Here's how I've done so far.

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

Create a function to handle updating user's access token from a client side.

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触发.

Make an HTTP trigger with the updated token.

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更新到您的服务器.

Create a cloud function which handles updating user's displayName to your server.

看看 Firebase提供的示例代码.

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
});

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

It's 100% up to you and there might be a better way to handle updating user's displayName. Be aware that a user changes their display name and profile photo quite often. Every time a user updates their default profile, you should update the token and store in local storage as well.

注意:Firebase将刷新令牌并在令牌过期时为您返回一个新令牌.

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

If you really want to initialize user's displayName during onCreate event then you could try something like below.

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

希望对您有帮助.

这篇关于Firebase Auth +功能|使用displayName创建用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 09:22