53

I am looking to fetch Auth User(s) UID from Firebase via NodeJS or Javascript API. I have attached screenshot for it so that you will have idea what I am looking for.

enter image description here

Hope, you guys help me out with this.

Modus Tollens
  • 5,083
  • 3
  • 38
  • 46
Piyush Bansal
  • 1,635
  • 4
  • 16
  • 39

6 Answers6

80

Auth data is asynchronous in Firebase 3. So you need to wait for the event and then you have access to the current logged in user's UID. You won't be able to get the others. It will get called when the app opens too.

You can also render your app only once receiving the event if you prefer, to avoid extra logic in there to determine if the event has fired yet.

You could also trigger route changes from here based on the presence of user, this combined with a check before loading a route is a solid way to ensure only the right people are viewing publicOnly or privateOnly pages.

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User logged in already or has just logged in.
    console.log(user.uid);
  } else {
    // User not logged in or has just logged out.
  }
});

Within your app you can either save this user object, or get the current user at any time with firebase.auth().currentUser.

https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged

Dominic
  • 62,658
  • 20
  • 139
  • 163
28

if a user is logged in then the console.log will print out:

if (firebase.auth().currentUser !== null) 
        console.log("user id: " + firebase.auth().currentUser.uid);
JamesD
  • 591
  • 5
  • 10
  • 2
    I was having an issue where this is not available immediately on page load. The callback method (onAuthStateChanged) worked for me though. – Fractaly Mar 08 '19 at 03:15
8

on server side you can use firebase admin sdk to get all user information :

const admin = require('firebase-admin')
var serviceAccount = require("./serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://yourprojecturl.firebaseio.com",
});

admin.auth().listUsers().then(data=>{
    console.log(data.users)
})
Dipanjan Panja
  • 396
  • 4
  • 12
4

This is an old question but I believe the accepted answer provides a correct answer to a different question; and although the answer from Dipanjan Panja seems to answer the original question, the original poster clarified later in a reply with a different question:

Basically, I need to generate token from UID by Firebase.auth().createCustomToken(UID) to sign in user on firebase with the following function firebase.auth().signInWithCustomToken(token).

Because the original question was clarified that the intent is to use createCustomToken and signInWithCustomToken, I believe this is a question about using the Firebase Admin SDK or Firebase Functions (both server-side) to provide custom authentication, probably based on a username and password combination, rather than using an email address and password.

I also think there's some confusion over "uid" here, where in the code example below, it does NOT refer to the user's Firebase uid, but rather the uid indicated in the doc for createCustomToken, which shows:

admin
  .auth()
  .createCustomToken(uid)
  .then((customToken) => {
    ...

In this case, the uid parameter on the createCustomToken call is not the Firebase uid field (which would not yet be known), thus providing a series of frustrating replies to the coder asking this question.

Instead, the uid here refers to any arbitrary basis for logging in for which this custom auth will support. (For example, it could also be an email address, social security number, employee number, anything...)

If you look above that short code block from the documentation page, you'll see that in this case uid was defined as:

const uid = 'some-uid';

Again, this could represent anything that the custom auth wanted it to be, but in this case, let's assume it's username/userid to be paired with a password. So it could have a value of 'admin' or 'appurist' or '123456' or something else.

Answer: So in this case, this particular uid (misnamed) is probably coming from user input, on a login form, which is why it is available at (before) login time. If you know who is trying to log in, some Admin SDK code code then search all users for a matching field (stored on new user registration).

It seems all of this is to get around the fact that Firebase does not support a signInWithUsernameAndPassword (arbitrary userid/username) or even a signInWithUidAndPassword (Firebase UID). So we need Admin SDK workarounds, or Firebase Functions, and the serverless aspect of Firebase is seriously weakened.

For a 6-minute video on the topic of custom auth tokens, I strongly recommend Jen Person's YouTube video for Firebase here: Minting Custom Tokens with the Admin SDK for Node.js - Firecasts

Appurist - Paul W
  • 1,291
  • 14
  • 22
3

As of now in Firebase console, there is no direct API to get a list of users, Auth User(s) UID.
But inside your Firebase database, you can maintain the User UID at user level. As below,

"users": {
  "user-1": {
    "uid": "abcd..",
    ....
  },
  "user-2": {
    "uid": "abcd..",
    ....
  },
  "user-3": {
    "uid": "abcd..",
    ....
  }
}

Then you can make a query and retrieve it whenever you need uid's.
Hope this simple solution could help you!

Karthi R
  • 1,338
  • 10
  • 25
  • 1
    Basically, I need to generate token from UID by `Firebase.auth().createCustomToken(UID)` to sign in user on firebase with the following function `firebase.auth().signInWithCustomToken(token)`. Is there any other way to Sign In User on firebase ? – Piyush Bansal Jul 14 '16 at 15:48
  • Firebase makes authentication easy. It has built-in functionality for email & password, and third-party providers such as Facebook, Twitter, GitHub, and Google. And with Firebase `custom Authentication API`, you can integrate with your existing login server too. – Karthi R Jul 15 '16 at 06:04
  • For more info go through these articles, hope this would help you, [Link-1](https://www.firebase.com/docs/android/guide/user-auth.html) and [Link-2](https://firebase.google.com/docs/auth/) – Karthi R Jul 15 '16 at 06:06
1

From Firebase docs, use Firebase.getAuth():

var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
var authData = ref.getAuth();

if (authData) {
  console.log("Authenticated user with uid:", authData.uid);
}

Source:

Selfish
  • 6,023
  • 4
  • 44
  • 63
  • 1
    If I try it, `authdata.uid` belongs to which user? the problem is that I need UID to signin user on firebase and without authentication, how can I get the correct UID. – Piyush Bansal Jul 14 '16 at 15:50
  • I believe this belongs to the currently authenticated user, this can be easily confirmed against the DB.. – Selfish Jul 14 '16 at 16:06