When a user logs in, or registers an account, an auth token is stored on the local storage. Now I want to use this token to get the logged in user information to display on my app for example the username and phone number.
I can get the user information using the token on my Postman. But now how do I display it on the reactjs app?
Here is the Api
public function me(Request $request){
return $request->user();
}
For example if you want to display the user on the first render of the page:
const [user, setUser] = useState()
useEffect(() => {
const fetchUser = async (url) => {
const response = await fetch(url)
const resData = await response.json()
setUser(resData.user)
}
fetchUser(YOUR_URL)
},[])
And then use the JSX syntax inside the React component to display the user.
Related
How do I get access to the refreshed token in Firebase Auth?
I'm building a React app, and on the signin button click run Login function. This function gives me a Google API token which I use to access google drive api.
The problem is that is token expires after an hour. This post mentions:
"If you need to know when the SDK refreshes the token in order to get a new one immediately, you should instead use onIdTokenChanged to set up a callback that will be invoked every time the user's token changes."
As such I've gone ahead and set this function up. However, how do I access this new updated token so that I can pass it along to the rest of the app?
Login Function
const login = async () => {
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
}
onIdTokenChanged
onIdTokenChanged(auth, (currentUser) => {
console.log(currentUser);
setUser(currentUser);
});
i am implementing user authentication with the help of firebase in my React project. So, I am confused over something.
I am verifying the user from firebase and then getting a token on frontend which is sent to backend via headers and verfied there once.
I read the docs and came to know that firebase token gets expired after 1 hr by default so we have to use "getIdToken" like
firebase.auth().onAuthStateChanged(async user => {
if (user) {
console.log(user, 'user123 inside firebaseAuth')
const token = await user.getIdToken()
Cookies.set('my_token', token, { domain: domain })
}
})
but how do i manage this function , do i have to call it everytime the component updates or everytime before hitting api or first time the component renders ?
The thing is i do not want this token to get expire until the user logs out himself / herself even if he is in a different component and sitting ideal for too long.
You can get the Firebase ID Token every time you are making an API call to your server:
async function callAPI() {
const user = firebase.auth().currentUser
if (user) {
const token = await user.getIdToken()
const res = await fetch("url", {
headers: {authorization: `Bearer ${token}`}
})
} else {
console.log("No user is logged in")
}
}
You could get the ID token once when the component mounts but then you'll have to deal with onIdTokenChanged to keep it updated in your state. Using the method above you'll get a valid token always.
We are developing Microsoft Sharepoint "Widgets" using javascript(React) and aadTokenProviderFactory to acquire tokens.
import { WebPartContext } from "#microsoft/sp-webpart-base";
const getMSToken = async (context: WebPartContext) => {
const provider = await context.aadTokenProviderFactory.getTokenProvider();
const token = await provider.getToken('https://graph.microsoft.com');
return token;
}
This token is valid and everything works fine. But when switching users I receive a token from the old user.
How to solve this issue and acquire tokens for the user that is currently signed in?
Issue solved.
getToken method has 2nd parameter called useCachedToken: boolean.
const token = await provider.getToken('https://graph.microsoft.com', false);
I'm trying to create a web application to manage the users of my Discord server. In my database, I have stored only the users' ids.
I tried to use the discord.js API, but from what I've understood it requires a discord bot to do that. That's not what I want. I would like to retrieve the user's information from my frontend, even by calling a backend function, but without having a discord bot which is always online. In other words, I need something simpler.
I would like to request users' information by using only the id. Which is the best way to do that in JavaScript?
You can use the Discord API.
First, create a Discord application here. Once you've done that, click 'Bot' on the sidebar and create a bot for that application. There, you'll see a section called 'Token' under the bot username. Copy this and store it somewhere secure. It is important to never share your token. If you do, you should regenerate it to prevent abuse.
You can then use the Get User endpoint (/users/{user.id}/) to retrieve the user for an ID. This should be done by the backend as it involves authenticating with the bot token.
Using the API directly
Here is a minimal example of how you would fetch a user by their ID using the Discord API using Node.js:
const fetch = require('node-fetch')
// You might want to store this in an environment variable or something
const token = 'YOUR_TOKEN'
const fetchUser = async id => {
const response = await fetch(`https://discord.com/api/v9/users/${id}`, {
headers: {
Authorization: `Bot ${token}`
}
})
if (!response.ok) throw new Error(`Error status code: ${response.status}`)
return JSON.parse(await response.json())
}
The response would be something like this:
{
"id": "123456789012345678",
"username": "some username",
"avatar": null,
"discriminator": "1234",
"public_flags": 0,
"banner": null,
"banner_color": null,
"accent_color": null
}
Using a library
Alternatively, you may be able to use a Discord library to do this instead. The following examples also handle rate limits.
#discordjs/rest + discord-api-types
const {REST} = require('#discordjs/rest')
const {Routes} = require('discord-api-types/v9')
const token = 'YOUR_TOKEN'
const rest = new REST().setToken(token)
const fetchUser = async id => rest.get(Routes.user(id))
The result would be the same JSON as described above.
For TypeScript users:
import type {RESTGetAPIUserResult, Snowflake} from 'discord-api-types/v9'
const fetchUser = async (id: Snowflake): Promise<RESTGetAPIUserResult> =>
rest.get(Routes.user(id)) as Promise<RESTGetAPIUserResult>
discord.js
When I first posted this answer, #discordjs/rest didn't exist yet.
const {Client} = require('discord.js')
const token = 'YOUR_TOKEN'
const client = new Client({intents: []})
client.token = token
const fetchUser = async id => client.users.fetch(id)
The result of fetchUser would be a discord.js User object.
Something you can do is
let user = message.guild.cache.get('id');
(modified by #cherryblossom)
I am facing a problem with setting custom claims for Firebase Authentication service's token. I am using Cloud function to set the custom claims for Hasura. The cloud function executes upon new user create event to set the custom claims. Here's my code running in cloud function
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.processSignup = functions.auth.user().onCreate(user => {
// create custom claims for hasura
const hasuraClaims = {
"x-hasura-default-role": "user",
"x-hasura-allowed-roles": ["user"],
"x-hasura-user-id": user.uid
}
// attach claims to user auth object
return admin.auth().setCustomUserClaims(user.uid, hasuraClaims)
.then(_ => {
functions.logger.info('SUCCESS: Custom claims attached');
})
.catch(err => {
console.log('ERROR: ', err);
})
})
In my frontend web page, I am running the following code to get the idToken
// subscribe to user state change
firebase.auth().onAuthStateChanged(async user => {
console.log('Firebase auth state changed');
if (user) {
// User is signed in.
window.User = user;
let idToken = await user.getIdTokenResult();
console.log('idToken: ', idToken);
}
})
I don't know what I'm doing wrong, but the token doesn't contain the custom claims that I've set in my Cloud function processSignup(). I know that the function executed without error because I can check my function logs and find the info entry SUCCESS: Custom claims attached.
Can anyone please help me solve this problem?
Updating claims does not trigger an onAuthStateChanged (the auth state of being logged in or not has not changed, but the users' claims have) and tokens are minted and then used for ~1h.
You are calling getIdTokenResult but not forcing a refresh, try:
let idToken = await user.getIdTokenResult(true);
which will force a new token to be fetched from the server and will (hopefully) include your custom claims.