How do I return a list of users if I use the Firebase simple username & password authentication

后端 未结 7 2096
猫巷女王i
猫巷女王i 2020-11-22 05:06

Not sure if I am doing something wrong but using this api https://www.firebase.com/docs/security/simple-login-email-password.html I can successfully create a user - accordin

7条回答
  •  臣服心动
    2020-11-22 05:40

    It's possible to use cloud function to fetch users list (view docs at firebase). Note, in the following example custom claims feature is used to check if user has enough privileges.

    // USERS: return full users list for admin
    // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    import * as admin from 'firebase-admin'
    import * as functions from 'firebase-functions'
    
    export const listUsers = functions.https.onCall((data, context) => {
      // check if user is admin (true "admin" custom claim), return error if not
      const isAdmin = context.auth.token.admin === true
      if (!isAdmin) {
        return { error: `Unauthorized.` }
      }
    
      return admin
        .auth()
        .listUsers()
        .then((listUsersResult) => {
          // go through users array, and deconstruct user objects down to required fields
          const result = listUsersResult.users.map((user) => {
            const { uid, email, photoURL, displayName, disabled } = user
            return { uid, email, photoURL, displayName, disabled }
          })
    
          return { result }
        })
        .catch((error) => {
          return { error: 'Error listing users' }
        })
    })
    

提交回复
热议问题