Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firebase auth - get current provider javascript

I'm trying to find out what provider my user is using, and I have no idea how! the language that I use is vanilla javascript.
There's a very similar question:
Firebase Auth - get provider ID
but this only works in swift 3...

like image 539
Joanthan Ahrenkiel-Frellsen Avatar asked Nov 19 '17 17:11

Joanthan Ahrenkiel-Frellsen


3 Answers

As the linked answer and Hareesh said, you will need to loop over the providerData array since a user can be signed in with multiple providers. So:

user.providerData.forEach(function(providerData) {
    console.log("Signed in with "+providerData.providerId);
});

For a working example see: https://jsbin.com/vuzafuq/edit?html,js,output (check the JavaScript console for the actual providers)

like image 179
Frank van Puffelen Avatar answered Oct 11 '22 00:10

Frank van Puffelen


I have tried multiple providers.
If you want to get all providers user have logged in, you can use user.providerData.
But the order of providerData is not based on the desc order by user log in time which the Swift SDK claimed. This doesn't apply to Javascript SDK.

If you want to get current provider, you can decode the idToken which contain current logged in provider sign_in_provider.
The format would be something like this

{
  .....
  "email": ....,
  "email_verified": true,
  "firebase": {
    "identities": {
      "google.com": [
        ....
      ],
      "email": [
        ....
      ]
    },
    "sign_in_provider": "password"
  }
}

You could tried to decode by https://jwt.io/ or using npm package jsonwebtoken to decode.
Test on the firebase 7.15.0 and hope this works for you.

like image 20
鄭元傑 Avatar answered Oct 10 '22 22:10

鄭元傑


Firebase provides the currently signed-in provider information inside the user object like below (I have used the AngularFire Framework Library for the below example).

For the web platform, please refer to the following code:

import { AngularFireAuth } from '@angular/fire/auth';
import 'firebase/auth';

export class AuthenticationService {
   constructor(private auth: AngularFireAuth) { }

   getCurrentUser(){
      this.auth.onAuthStateChanged((user) => {
         if (user) {
            // User is signed in.
            user.getIdTokenResult()
                .then((idTokenResult) => {
                  let currentProvider = idTokenResult.signInProvider;
                  // The result will look like  'google.com', 'facebook.com', ...
                 });
         } else {
            // No user is signed in.
         }
      });
    }
}

For more details, check out the official doc here.

like image 39
arunraj6 Avatar answered Oct 10 '22 22:10

arunraj6