firebase auth - get current provider javascript - 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...

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)

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.

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.

2022 Answer (Firebase v8)
I was looking for a simple little JS snippit and couldn't find one. Maybe this will help you:
// Gets the user's sign-in method
let signInMethod =
firebase.auth().currentUser?.providerData[0]?.providerId;

Related

How to implement cookie authentication with Sveltekit & Supabase?

I'm fairly new to both SvelteKit & Supabase and have done a bit of experimentation on my own, but I would like to know what is the best way to implement user authentication with both of these technologies.
I currently have the following in my __layout.svelte file so that every page on my web application will have access to the session but I'm not sure how to implement persistent user authentication with a cookie.
If anyone can guide me and future users that would be awesome!
<script>
import supabase from "$lib/api";
import { page, session } from '$app/stores';
import { browser } from '$app/env';
if(browser){
$session = supabase.auth.session();
supabase.auth.onAuthStateChange((event, sesh) => {
$session = sesh;
});
}
</script>
It is definitely not clear how to do this. I tried to make it easy and put it into a user readable store:
export const user = readable<any>(null, (set) => {
set(supabase.auth.user());
const unsubscribe = supabase.auth.onAuthStateChange((_, session) => {
session ? set(session.user) : set(null);
});
return () => {
unsubscribe.data.unsubscribe();
}
});
Now you can just use $user anywhere to get the session, or see if there is a session.
J
The supabase project has released an example repo and a QuickStart Guide which helps by abstracting away some of the boilerplate. There's quite some modifications one needs to add so I won't re-paste all the information here as it wouldn't make sense without looking at the full solution. It's all based on a helper library https://supabase.com/docs/guides/auth/auth-helpers/sveltekit

How do I set displayName in Firebase when using Apple authentication?

I am trying to use Apple OAuth on the web with the Firebase Javascript SDK, and when I do, the returned user object is fine, except for displayName, which is null.
let provider = new firebase.auth.OAuthProvider("apple.com");
provider.addScope("email");
provider.addScope("name");
let userCred = await firebase.auth().signInWithPopup(provider);
However when I look at the userCred I get:
displayName: null
I tried the scope fullName to no luck.
Is there any way to get the display name? I use it so that my users can see their name on the site, to personalize the experience.
You get this right on the response to appleAuth signin response
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME]
});
appleAuthRequestResponse will hold the name details.
Please note that, if you had already used your account for testing, you will have to login to your appleid and remove the apple sign in for your app, to test this.[ Also delete this user from firebase auth ]

Redirect to checkout in ReactJS

I am trying to implement the Stripe function "redirect to checkout" in ReactJS.
I have been looking around and there is no package that seems to help to do it.
const stripe =
Stripe('key');
stripe.redirectToCheckout({
items: [
// Replace with the ID of your SKU
{sku: 'sku_123', quantity: 1}
],
successUrl: 'https://your-website.com/success',
cancelUrl: 'https://your-website.com/canceled',
}).then(({error}) => {
// If `redirectToCheckout` fails due to a browser or
network
// error, display the localized error message to your
customer
// using `error.message`.
});
This is where I got this source code: https://stripe.com/docs/stripe-js/reference#stripe-redirect-to-checkout
StripeJS only seems to support the standard checkout that does not receive the product SKU as the parameter
After I read the new stripe-js docs https://stripe.com/docs/stripe-js/react
I found this might be useful for you
Instead using stripe, install #stripe/stripe-js
then the job can be done by
import { loadStripe } from "#stripe/stripe-js";
...
const stripePromise = loadStripe(
"pk_.........."
);
const stripe = await stripePromise;
stripe.redirectToCheckout({
...
})
I found out how ti make it work.
Basically as per the documentation, there is the need to import the Stripe script in public/index.html
stripe.redirectToCheckout(...)
can be simply put into the onClick of a button.
The thing that is really not clear in the docs, and that can mislead newbies like me, lies in setting the public key:
const stripe = Stripe('key');
doesn't work, because the script is not found at compile time.
This can be solved by using:
const stripe = window.Stripe('key');
This worked for me.

firebase json db security rule using fb authentication

I am using ionic 3 angular for my mobile app and fb native cordova plugin is used to login.
The firebase db security documentation uses the syntax like
{
"rules":{
"users":{
"$user_id":{
".write":"$user_id === auth.id"
}
}
}
}
the fb authentication looks like below in my app
doLogin(){
if (this.platform.is('cordova')) {
return this.fb.login(['email', 'public_profile']).then(res => {
const facebookCredential = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
firebase.auth().signInWithCredential(facebookCredential);
this.navCtrl.setRoot(TabsPage);
})
}
}
my question is the auth firebase variable is taken care with above code or i need to something extra for auth to get required uid etc. ?
The auth firebase variable is token care of in theory: assuming you have the Facebook sign-in method enabled already. However, the database rules you are showing are not necessarily related.
These rules (the same as above):
"rules": {
"users":{
"$variable":{ ".write": "$variable=== auth.uid" }
Dictate that users can only write to a child node with the same uid. I changed $user_id to $variable to highlight that the $ simply denotes a variable that represents the child node's name.
(I should probably mention that it should be auth.uid not auth.id)
This is used to save user specific data. So, when they signup you could have a function that says
firebase.database().ref('users').child(firebase.auth().currentUser.uid).update(<your custom data here>);
*please note how the child of users is the "firebase.auth().currentUser.uid" which can optionally be retrieved from the firebase.auth().signInWithCredential() promise.
Sorry if the explanation was more that necessary. In short. the uid is always present with firebase.auth().currentUser.uid after login and that uid is what the database rules are referring to in auth.uid and last, the auth/uid/etc is pretty much 100% taken care of with firebase.

Is there any way to get Firebase Auth User UID?

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.
Hope, you guys help me out with this.
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
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);
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)
})
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
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!
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:
Firebase.getAuth()

Categories

Resources