javascript - Firebase 身份验证+功能 |使用 displayName 创建用户

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

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

最佳答案

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

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

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

使用更新的 token 创建 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到你的服务器。

看看sample code由 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
});

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

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

如果你真的要初始化用户的displayName onCreate event期间那么你可以试试下面的东西。
exports.createUser = functions.auth.user().onCreate(event => {
  let user = event.data;
  const displayName = user.displayName || 'Anonymous';
  ...Update operation code goes below
});

我希望这可以帮助你。

关于javascript - Firebase 身份验证+功能 |使用 displayName 创建用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741932/

相关文章:

javascript - AngularJS 指令模板类不呈现

java - 删除多个父节点上的特定子节点

android - 如何使用 Dagger2 提供 GoogleSignInOptions?

javascript - Firebase onAuthStateChange 登录时触发两次

javascript - 功能分配不起作用

javascript - 使用 R 读取动态 HTML 元素

android - Firebase isEmailVerified 无法正常工作 kotlin android

firebase - onAuthStateChanged 现在在 react native 中返回 null

javascript - 调试在 Adob​​e Air 中运行的 Javascript

firebase - 如何解决 : Error: Failed to list Firebase projects. 请参阅 firebase-debug.log 了解更多信息