Firebase Auth+Functions | create user with displayName

女生的网名这么多〃 提交于 2019-12-10 15:10:09

问题


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?

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.

How I create a user with 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)
                })
            })
        }
    )

My cloud function:

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

回答1:


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

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

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

Take a look at the sample code provided by 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
});

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.

Note: Firebase will refresh the token and return a new one for you if it's expired.

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

I hope this helps you.



来源:https://stackoverflow.com/questions/48741932/firebase-authfunctions-create-user-with-displayname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!