How to get user's id from auth0 in React - javascript

I recently implemented user authentication in my react web app using Auth0. And I need to retrieve some information from user object. I did this so far:
cost { user, isAuthenticated } = useAuth0();
<p>{user.name}</p>
But I also want to get user's id, so I can reference them later in my backend. So I did this:
const { user, isAuthenticated } = useAuth0();
<p>{user.user_id}</p>
And when I go to the website I get undefined instead of the user's id.
Is it happening because I use dev-keys for my social connections, or maybe it has to be done differently?

Not sure if you are still searching for this problem, however I had a similar problem and found this as a solution:
const { user, isAuthenticated } = useAuth0();
<p>{user.sub}</p>
source: https://community.auth0.com/t/how-to-get-user-id-of-a-user-after-login-in-react-hook-useauth0/53309

It should be the "sub" key. Discord id is 18 characters long. The results prefix it with oauth2|discord|. Which you can truncate out with a function.
const { user, isAuthenticated } = useAuth0();
console.log(user.sub);
The results should be something like:
oauth2|discord|111111111111111111

Related

Access route params in a single way react native

I am currently facing a problem with the authentication flow and the navigation file. Basicly I want to have the authentication logic inside my navigation file, so I can conditionaly say if I want to show the login or not.
Like this:
const { id: contextId } = useId()
const { token } = useToken()
const _id = contextId : getIdParam(contextId)
const globalParams = { initialParams: { _id } }
And then I use the _id to conditionally show or not the login. The problem with this implementation is, that I am using two ways to access the id param in the url:
ContextAPI (I set the id after login so it is available in that session)
getIdParam function, to access the id param via location.path, whenI try to reload a screen without passing in login.
Is there any way I can access params in the navigation file, I tried to use useRoute hook, but I am not allowed to use it outside of a screen.
Any help? Thanks

how to save user form input data to firestore in reactnative

i've been trying to submit user input to my firebase database but it doesn't work for me. i'm a beginner in react-native and firebase. i have 3 input fields and want to save the data entered by user into my database after clicking on submit.
Let's say you have those inputs ready, let's say you have them stored in i don't know states maybe. Then if we talk about firestore you would do something like this :
const onSubmit = () => {
firestore()
.collection('your collection')
.doc(auth().currentUser.uid)
.set({
name : state.name,
email : state.email
// and so on
})
.then(() => {
// do something like logging 'user registered'
})
}
Note that the comments you received earlier are rights. This is just an example of what you can do, guessing this is what you were asking. But your question need to be more precise in the future so you can get better support
Also check the firebase or react-native-firebase documentations depending on which one you are using because the way of doing things might be a bit different. The one i showed you is with the react-native-firebase library
Let's say you have some data in the state from the text input:
const [dataState,setDataState] = useState("Some data from text Input")
Now let's say you want to upload it to firebasee. First you need to have the firebase app initialized. Often you do this in a separate file. Here's how:
import {initializeApp} from 'firebase/app'
import {firestore} from 'firebase/firestore'
const firebaseConfig = {
..your keys
}
initializeApp(firebaseConfig)
const db = firestore()
export db;
Now that you have your app initialized, go to your main file/screen (like app.js):
import {db} from './yourFirebaseFile'
import {collection,addDoc} from 'firebase/firestore'
Now let's say you have the data in your state from the text input. Let's create a function to send the data to firebase (you can all this function on press of a button)
const sendToFirestore = async() => {
await addDoc( collection(db, "Your_Collections_Name_in_firebase"), {
dataFromInput : dataState
} )}
There you go! You have the data saved (:

How do I add more fields in firebase-auth?

After a long research on firebase-auth with email and password, I found that we can't give more than two fields (email and password).
In my assignment, they supposed to give three input fields (full name, email and password).
I have completed my assignment only with two input fileds (email and password) but they also want to store full-name in firebase.
My assignment is given bellow -
So, Is it possible to also store "full name" in firebase, If so then how ?
I could describe this question in another way, but I just tell you the truth.
Please Help Me !
Firebase Auth object has a displayName property which you use to store user's name. However, if you are using Client SDK then you would have to create the user first and then update the name. This can be done in a single step if you use Admin SDK with Cloud functions or a server.
import { useAuth } from "firebase/auth"
const auth = getAuth();
const createNewUser = async () => {
const { user } = await createUserWithEmailAndPassword(auth, email, password)
await updateProfile(user, { displayName: "Jane Q. User" })
console.log('New user', user.uid)
}
If the full name consists of a first name and a last name, then you can add a - or any symbol between them e.g. first-last in displayName. Then you can read the name as shown below:
const { displayName } = auth.currentUser
const [firstName, lastName] = displayName.split("-")
If you need to access the data from a server environment or any user management page, then it'll be best to store details of users in a database answered by #TarikHuber.
You have basicaly two options for doing that:
as mentioned in the comments you could use the database to store additional data for each user uid
use customClaims to store such additional data there
I would recommend the first one for more data if you need to store a lot of data and if you have less you could use the customClaims. They are limited in size so be carefull how much you save inside.

How can I make Dialogflow agent greet user if they have used the action before?

I'm using Actions On Google / Dialogflow, and I'm trying to make a function that will greet a user by their name if they've used the action before, and if not, will ask for their name. I have tried to map this to the "Welcome intent" through fulfillment, but whenever I try to run the action on the simulator, I get this error:
Error 206: Webhook Error
Which Initially would make sense if this was mapped to another intent, but I'm wondering if I'm getting this error because you can't have a fulfillment with the welcome intent?
Here's the code I'm using in the inline editor which may be the problem:
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request,response) => {
const agent = new WebhookClient({ request, response });
function welcome(conv) {
if (conv.user.last.seen) {
conv.ask(`Welcome back ${name}!`);
} else {
conv.ask('Welcome to The app! My name is Atlas, could I get your name?');
}}
let intentMap = new Map();
intentMap.set('Welcome Intent', welcome);
agent.handleRequest(intentMap);
How come this isn't working? Do I need to implement user login? Do I need to use a function that would write to a firestore databbase?
Thanks for the help or suggestions!
Let's clear a few things up to start:
You can have fulfillment with your welcome intent.
You do not need user login. Although using Google Sign In for Assistant can certainly be used, it doesn't fundamentally change your problem here.
You do not need to use a function that writes to the firestore database. Again, you could use it, but this doesn't change your problems.
The specific reason this isn't working is because the conv parameter in this case contains a Dialogflow WebhookClient rather than an actions-on-google Conversation object.
To get the Conversation object with the parameter you have, you can call conv.getConv(), which will give you an object that has a user parameter. So this may look something like
function welcome(conv) {
let aog = conv.getConv();
if (aog.user.last.seen) {
conv.ask(`Welcome back ${name}!`);
} else {
conv.ask('Welcome to The app! My name is Atlas, could I get your name?');
}}
There are, however, still some issues with this. Most notably, it isn't clear where name will come from. I assume you will get it out of the user store object, but you don't seem to have done this.
For anyone who comes across this question in the future and just wants a straight forward answer without having to search through ambiguous answers / documentation, here is what to do step by step:
note: I ended up using the Google Sign in method, but even if this isn't your goal, i'll post the link to the alternative method.
1) Import the actions on google module. What people / tutorials don't to show is you have to import the library like this (for user login):
const {
dialogflow,
Permission,
SignIn
} = require('actions-on-google')
instead of
const dialogflow = require('actions-on-google')
2) Use this code:
const app = dialogflow({
clientId: '<YOUR CLIENT ID from Actions on Google>',
});
app.intent('Start Signin', conv => {
conv.ask(new SignIn('To get your account details'));
});
app.intent('Get Signin', (conv, params, signin) => {
if (signin.status === 'OK') {
const payload = conv.user.profile.payload;
conv.ask(`Welcome back ${payload.name}. What do you want to do next?`);
} else {
conv.ask(`I won't be able to save your data, but what do you want to do next?`);
}
});
This function will ask the user for a login, and next time you invoke the intent, it will say "Welcome back name", because google automatically saves it.
Here's the link to the alternative method:

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