Using Firebase v9, NPM, ReactJS
Hi everybody,
how can I display some text in order, that user is signed in?
e.g:
if(loggedIn){
<p>you are logged in</p>
} else if(notLoggedIn){
<p>you arent logged in</p>
}
Already have done Firebase auth with email and password.
You need to Set an authentication state observer and get user data
https://firebase.google.com/docs/auth/web/start#set_an_authentication_state_observer_and_get_user_data
follow this link it will get you where do you need
its somethings like that
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
// show message user is logged in
const uid = user.uid;
// ...
} else {
// User is signed out
// show message user is not logged in
}
});
Related
I am doing a project in react based no Firebase OTP authentication.
I get the OTP part right but the trouble comes in the OTP verification part, because it's done in another page. But when i run the verification code on the other page i get an error as Cannot read properties of undefined (reading 'confirm').
OTP_SEND.JS
onsignInSubmit =(event)=>{
event.preventDefault();
this.setupRecaptcha()
var phoneNumber = "+91"+this.state.mobile
console.log(phoneNumber)
var appVerifier = window.recaptchaVerifier;
authentication
.auth()
.signInWithPhoneNumber(phoneNumber,appVerifier)
.then(function(confirmationResult){
window.confirmationResult = confirmationResult;
console.log("otp sent")
}).catch(function(error){
console.log("OTP not send")
})
}
OTP-VERIFICATION.JS
otpSubmit=(e)=>{
e.preventDefault();
const code = this.state.otp;
console.log( code);
window.confirmationResult.confirm(code).then((result)=>{
const user = result.user;
console.log(JSON.stringify(user))
alert("user verified")
}).catch((error)=>{
console.log(error)
})
}
Install the react-dom-router package.
Create a new React application and add the react-dom-router package to it.
Create a new page in your application and add a form to it. This form should include fields for the user's phone number and a button to send the OTP.
Use the Firebase Authentication API to generate an OTP and send it to the user's phone number.
Create a new page in your application and add a form to it. This form should include fields for the user's OTP and a button to verify the OTP.
Use the Firebase Authentication API to verify the OTP entered by the user.
If the OTP is verified, redirect the user to the page you want them to see.
I want to use one login form for admin and a user in my project for react js and firebase,only the admin to be able to login and be redirected to the admin panel and the user to the user profile with,
Admin panel and user login in firebase and reactjs. Anybody knows how to do this?
There are some hints and keywords:
1> For firebase auth user, you can set custom claims to set role to user, ex. admin or user. Please refer to the link below
https://firebase.google.com/docs/auth/admin/custom-claims
Firebase - how to set custom claim from the console
2> When log in, you have to listen to auth state changed to get user role thanks to the getIdTokenResult function
onAuthStateChanged(auth, async (user) => {
if (user) {
user.getIdTokenResult(true).then((result) => {
// Confirm the user is an Admin.
if (!!result.claims.admin) {
// Show admin UI.
showAdminUI();
} else {
// Show regular user UI.
showRegularUI();
}
})
}
});
or
Check for firebase's auth user's role when or after logging in
https://firebase.google.com/docs/auth/admin/custom-claims#access_custom_claims_on_the_client
currently building react & back4app project. when a user signs in and navigates to a new page they are automatically signed out and have to log back in again. I am using the currentUser method and wondering do i need to call this on every page to keep the user signed in.
// Function that will return current user and also update current username
const getCurrentUser = async function () {
const currentUser = await Parse.User.current();
// Update state variable holding current user
setCurrentUser(currentUser);
return currentUser;
};
Someone new visits my web app and decides to sign up. When they sign up they are taken to the dashboard. Upon visiting the dashboard for the first time Id like to welcome them with a toast message or a modal.
I am using passport local and passport google oauth2.0. which always sends back a req.user object with properties.
I am not sure how to set up a useEffect to trigger this message when they visit the dashboard. Do I do something like
const useEffect(() => {
// show toast or modal
},[// based on cookie time? or some req.user prop?])
You can simply use LocalStorage or cookies to know if user is logged in or not then in your useEffect you can do something like this.
useEffect(()=>{
//don't store any user info in local storage only flag
const isLogin=localStorage.getItem("flag")//you can also use cookies
if (isLogin==true)
{
showModal(true);
}
},[showModal])
//in your return
return(
showModal==true?<Modal/>:<></>
)
I am trying to code a simple React app that requires a user to sign in with Google before sample data can be accessed in the app. I would like a welcome message to display upon login that says "Welcome, [name]!" Currently, this function is working, but it's lagging behind by one sign-in.
The beginning state of my app
This is how the app appears at the beginning.
The app after one login
This is how the app appears after one login. Note that instead of getting the name from the user's Google account, it displays the default value of "default".
The app after two or more logins to the same account
After logging out and logging back in again, however, the app functions normally, showing the welcome message with the user's name. I've tried logging in with a different account, and the lag persists, i.e. "default" displays when logging in with Naomi, "Naomi" displays when logging in with Ally, "Ally" displays after logging out and logging back into Ally.
I've tried logging the variable with the user's name (userName) to the console right before information is passed, and it appears to be firing AFTER the log-in is completed, but I'm not sure why.
The code I hope is relevant is below.
import React from 'react';
import Login from './Login';
var userName = "default";
class LoginButton extends React.Component {
// some other code here
onSignIn = googleUser => {
this.toggleLoggedIn();
let user = googleUser.getBasicProfile();
let id_token = googleUser.getAuthResponse().id_token;
userName = user.getName(); //I try to grab the name from the user's account and assign it to userName
console.log('google user obj', user);
{/*console.log('google_id_token', id_token);*/}
console.log('Name:', userName); //This properly logs the correct userName to the console
};
// some other code here
render() {
console.log(this.state.isLoggedIn);
console.log(userName); //this incorrectly logs the userName lagged by one
// noinspection CheckTagEmptyBody
return (
<div>
<Login isLoggedIn={this.state.isLoggedIn} name={userName}/> //this passes the incorrect userName
<div id="my-signin2"></div>
<br />
{this.state.isLoggedIn && (
<button style={{ width: 200, height: 40, textAlign: 'center' }} onClick={this.logout}>
Logout
</button>
)}
</div>
);
}
}
Any help would be much appreciated.
My problem was the placement of this.toggleLoggedIn();
Moving it to the end of the onSignIn function block solved my problem.
onSignIn = googleUser => {
console.log("Sign in successful");
let user = googleUser.getBasicProfile();
userName = user.getName();
this.toggleLoggedIn();
};