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

后端 未结 7 2076
猫巷女王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:16

    You can use Google Identity Toolkit API to get a list of all registered users in your Firebase project, this API is used by the Firebase CLI which can be accessed by running firebase auth:export results-file

    Make sure Identity Toolkit API is enabled

    firebase-users-list.js

    const serviceAccount = require('path/to/firebase-sdk-json-service-account');
    
    const googleapis = require('googleapis');
    const identitytoolkit = googleapis.identitytoolkit('v3');
    
    const authClient = new googleapis.auth.JWT(
        serviceAccount.client_email,
        null,
        serviceAccount.private_key,
        ['https://www.googleapis.com/auth/firebase'],
        null
    );
    
    authClient.authorize((err) => {
        if (err) {
            return console.error(err);
        }
    
        let nextPageToken = undefined;
        let users = [];
        const getAccounts = () => identitytoolkit.relyingparty.downloadAccount({
            auth: authClient,
            resource: {
                targetProjectId: serviceAccount.project_id,
                maxResults: 200,
                nextPageToken: nextPageToken
            }
        }, (e, results) => {
            if (e) {
                return console.error(err);
            }
    
            users = users.concat(results.users);
            if (results.nextPageToken) {
                nextPageToken = results.nextPageToken;
                return getAccounts();
            } else {
                console.log(users);
            }
        });
        getAccounts();
    });
    
    0 讨论(0)
  • 2020-11-22 05:16

    You can do it using admin.auth().listUsers

    Here is the doc for this: https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth.html#listusers

    And an usage example: https://firebase.google.com/docs/auth/admin/manage-users#list_all_users

    function listAllUsers(nextPageToken) {
      // List batch of users, 1000 at a time.
      admin.auth().listUsers(1000, nextPageToken)
        .then(function(listUsersResult) {
          listUsersResult.users.forEach(function(userRecord) {
            console.log('user', userRecord.toJSON());
          });
          if (listUsersResult.pageToken) {
            // List next batch of users.
            listAllUsers(listUsersResult.pageToken);
          }
        })
        .catch(function(error) {
          console.log('Error listing users:', error);
        });
    }
    // Start listing users from the beginning, 1000 at a time.
    listAllUsers();
    
    0 讨论(0)
  • 2020-11-22 05:22

    i will answer it simply as much as possible just add the registered user to your data base by using the following code

    you can also use shared prefernces to save the data locally but it won't be able for other user.

    once you save the list of user in the database simply retrieve it from there using adapters

    FirebaseDatabase.getInstance().getReference().child("my_user")
                            .child(task.getResult().getUser().getUid())
                            .child("username").setValue(autoCompleteTextView1.getText().toString());
    
    0 讨论(0)
  • 2020-11-22 05:27

    When using email / password authentication in Firebase Authentication (previously known as Firebase SimpleLogin), your user's email and password combination is securely stored separately from the data actually stored in your Firebase.

    This barrier between the data in your Firebase and your users' email / password hash combinations is by design: we want to make it easier for you to (1) develop your application, (2) prevent any accidental user credential leaks, and (3) still give you total flexibility with how to store your user data in Firebase.

    That means that we only store the email address / password hash combination and nothing else, so it is up to you to decide how to store actual user data in your Firebase. As you suggested, you should be taking the user id and storing that data in your Firebase in a location such as /users/$id, and using the Firebase Security Rules Language to determine read / write access to that data. Your user's unique id and email are already in the auth variable you'll use when writing rules.

    0 讨论(0)
  • 2020-11-22 05:29

    Users list in python:

    from firebase_admin import credentials, db, auth
    cred = credentials.Certificate('\path\to\serviceAccountKey.json')
    default_app = firebase_admin.initialize_app(cred, {
        "databaseURL": "https://data_base_url.firebaseio.com"
    })
    users = auth.list_users()
    
    0 讨论(0)
  • 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' }
        })
    })
    
    0 讨论(0)
提交回复
热议问题