Firebase Auth+Functions | create user with displayName

后端 未结 1 512
执念已碎
执念已碎 2021-01-18 22:16

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 disp

相关标签:
1条回答
  • 2021-01-18 22:43

    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.

    0 讨论(0)
提交回复
热议问题