FirebaseError: Firebase: Error (auth/user-token-expired) [duplicate] - javascript

This question already has an answer here:
firebase: admin.auth().updateUser() causes auth/user-token-expired
(1 answer)
Closed 8 months ago.
I have created a new form after creating a user with phone number authentication(in firebase), But an error keeps on coming after submitting FirebaseError: Firebase: Error (auth/user-token-expired)
The Error is Comming in this code
//This Component is used to store the Name ,Phone Number Of new User Which have Registered in SignUp With Number
import "./Auth.scss";
import React, { useState } from "react";
import { updateProfile, updateEmail } from "firebase/auth";
import { auth } from "../../firebase/config";
import { useNavigate, useLocation } from "react-router";
import usePhoneSignUp from "../../hooks/usePhoneSignUp";
import { update } from "lodash";
const SaveUserDetails = () => {
//code to extract userType after navigating from SignUpWithNumber page
const { state } = useLocation();
const userType = state.userType;
console.log(userType);
// .......
const {
signUp,
error: signupError,
isPending: signupIsPending,
} = usePhoneSignUp();
const [name, setname] = useState();
const [email, setemail] = useState();
const navigate = useNavigate();
const handleChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
switch (name) {
case "displayname":
setname(value);
break;
case "email":
setemail(value);
break;
default:
break;
}
};
const updateEmailUser = () => {
updateEmail(auth.currentUser, email)
.then(() => {
// Email updated!
// ...
console.log("email Updated");
})
.catch((error) => {
// An error occurred
console.log("email Updated");
// ...
console.log(error);
});
};
const updateUserProfile = () => {
updateProfile(auth.currentUser, {
displayName: name,
})
.then(() => {
console.log("profile Updated" + name + " " + email);
})
.catch((error) => {
console.log(error + "In update profile");
});
updateEmailUser();
};
const handleSubmit = () => {
// updateEmailUser();
updateUserProfile();
signUp(name, userType, email);
let path =
userType === "salonOwner" ? "/addBuisnessDetails" : "/salonsNearby";
if (signupError) {
console.log(signupError.message);
}
return navigate(path, { replace: true });
};
//query function for saloon
return (
<>
<div className="form-wrapper ">
<div id="register-form">
<p className="login-title register-title">Complete Your Profile</p>
<div className="login-hr" />
<form onSubmit={handleSubmit}>
<div className="form-group login-sj">
<label htmlFor="exampleInputName1">Name:</label>
<input
type="text"
className="form-control"
id="exampleInputName1"
aria-describedby="emailHelp"
placeholder="Your Name"
name="displayname"
onChange={handleChange}
/>
</div>
<div className="form-group login-sj">
<label htmlFor="exampleInputEmail2">Email address</label>
<input
type="email"
className="form-control"
id="exampleInputEmail2"
aria-describedby="emailHelp"
placeholder="Enter email"
name="email"
onChange={handleChange}
/>
</div>
{/* <div className="form-group login-sj">
<label htmlFor="exampleInputPassword1"></label>
<input
type="password"
className="form-control"
id="exampleInputPassword2"
placeholder="Password"
value={userPassword}
onChange={(e) => setUserPassword(e.target.value)}
/>
</div> */}
{signupIsPending ? (
<>
<button
type="submit"
className="btn-auth-sj btn btn-primary"
disabled
>
Save Details
</button>
</>
) : (
<>
<button type="submit" className="btn-auth-sj btn btn-primary">
Save Details
</button>
</>
)}
</form>
</div>
</div>
</>
);
};
export default SaveUserDetails;
The part where error is Comming
.catch((error) => {
console.log(error + "In update profile");
});
Due to this my displayName Is not getting saved and after submitting user is getting logged out automatically.
I also asked this question previously and implemented it as answered Is their any function signupwithphonenumber in firebase just like signupwithemailandpassword? (for web) I want to make user register with his creds
Thanks In advance

Okay So the problem got resolved gust by wrapping updateProfile function(one provided by firebase) into
auth.currentUser.reload().then(() => { /* update profile function here */ })
Or In my case :-
const updateUserProfile = () => {
auth.currentUser.reload().then(() => {
updateProfile(auth.currentUser, {
displayName: name,
})
.then(() => {
console.log("profile Updated" + name + " " + email);
})
.catch((error) => {
console.log(error + "In update profile");
});
updateEmailUser();
});
};

Related

Uncaught TypeError: react__WEBPACK_IMPORTED_MODULE_0__.useContext(...) is null when calling set function

I'm trying to set up a user login system using the userContext and localSotrage of the browser.
I have a first file that includes my provider and my context:
Auth.jsx
import { hasAuthenticated } from '../services/AuthAPI';
export const AuthContext = createContext()
const AuthProvider = ({children}) => {
const [auth, setAuth] = useState(hasAuthenticated());
const value = useMemo(() => ({auth, setAuth}, [auth, setAuth]));
return (
<AuthContext.Provider value={value}>{children}</AuthContext.Provider>
)
}
export default AuthProvider
export const AuthState = () => {
return useContext(AuthContext)
}
I also have a page that allows to manage elements of the LocalStorage and to know if a user is already connected (it for now hardcoded):
AuthAPI.jsx
export function hasAuthenticated() {
const token = getItem('sessionToken');
const result = token ? tokenIsValid(token) : false;
if (false === result) {
removeItem('sessionToken');
}
return result;
}
export function login(credentials) {
addItem('sessionToken', 'tokenSample');
return true;
};
export function logout() {
removeItem('sessionToken');
}
function tokenIsValid(token) {
// const { exp: expiration } = jwtDecode(token);
// if (expiration * 1000 > new Date().getTime()) {
// return true;
// }
return true;
}
And finally I have my connection page which must update the auth variable using the context:
Login.jsx
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../contexts/Auth';
import { login } from '../services/AuthAPI';
const Login = () => {
const navigate = useNavigate();
const {auth, setAuth} = useContext(AuthContext);
const [user, setUser] = useState({
username: "",
password: ""
})
const handleChange = ({ currentTarget }) => {
const { name, value } = currentTarget;
setUser({ ...user, [name]: value })
}
async function handleSubmit(event) {
event.preventDefault();
try {
const response = await login(user);
setAuth(response);
navigate('news', { replace: true });
console.log('oui');
} catch (e) {
console.error(e);
}
}
useEffect(() => {
if (auth) {
navigate('news', { replace: true });
}
}, [navigate, auth]);
return (
<div className="container border rounder mt-5 p-3 bg-light">
<form className="form-profile" onSubmit={setAuth(true)} >
<fieldset>
<legend>Se connecter</legend>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="text"
name="username"
className="form-control"
id="email"
placeholder="mail#mail.fr"
onChange={handleChange}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
className="form-control"
id="password"
placeholder="Password"
onChange={handleChange}
/>
</div>
<button type="submit" className="btn btn-outline-primary">
Se connecter
</button>
</fieldset>
</form>
</div>
);
};
export default Login;
But React returns this error:
Uncaught TypeError: react__WEBPACK_IMPORTED_MODULE_0__.useContext(...) is null site:stackoverflow.com at line setAuth(response); from Login.jsx
Do you have any idea ?

While implementing react-intl-tel-input in my react JS it give me errors

Hello I have started learning ReactJS and from last 1 week i stuck with a problem. I am using React with Firebase Phone Authentication. I want to use react-intl-tel-input for taking Phone input. I have installed the npm package and write the code as told in documentation. after running the code it takes the input correctly but after clicking on verify it say this number is not register but this number work perfectly with tag but not with this
please have a look on my code
import React from 'react'
import firebase from './firebase'
import 'firebase/auth';
import "./App.css";
import { getDatabase, ref, child, get } from "firebase/database";
import IntlTelInput from 'react-intl-tel-input';
import 'react-intl-tel-input/dist/main.css';
class Login extends React.Component {
state = {};
handlePhoneChange = (status, phoneNumber, country) => {
console.log({ phoneNumber });
this.setState({ phoneNumber });
};
handleChange = (e) => {
console.log (e)
const { name, value } = e.target
this.setState({
[name]: value
})
console.log (value)
this.setState({ phoneNumber: value }, () => {
console.log(this.state.phoneNumber);
});
}
configureCaptcha = () =>{
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
'size': 'invisible',
'callback': (response) => {
// reCAPTCHA solved, allow signInWithPhoneNumber.
this.onSignInSubmit();
console.log("Recaptca varified")
},
// defaultCountry: "IN"
}
);
}
onSignInSubmit = (e) => {
e.preventDefault()
this.configureCaptcha()
const phoneNumber = this.state.mobile
console.log(phoneNumber)
const appVerifier = window.recaptchaVerifier;
const dbRef = ref(getDatabase());
get(child(dbRef, `Users/${phoneNumber}`)).then((snapshot) => {
if (snapshot.exists()) {
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then((confirmationResult) => {
window.confirmationResult = confirmationResult;
alert('An OTP has been sent to your registered mobile number')
localStorage.setItem("Phone_No", phoneNumber)
console.log(localStorage.getItem('Phone_No'));
}).catch((error) => {
console.error(error);
alert("Oops! Some error occured. Please try again.")
});
}
else {
alert('Sorry, this mobile number is not registered with us. Please use your registered mobile number.');
}
})
}
onSubmitOTP = (e) => {
e.preventDefault()
const code = this.state.otp
console.log(code)
window.confirmationResult.confirm(code).then((result) => {
// User signed in successfully.
const Users = result.user;
console.log(JSON.stringify(Users))
this.props.history.push("/home");
}).catch((error) => {
alert("You have entered wrong code")
});
}
render() {
return (
<>
<main>
<div className="img">
<img src="./55k-logo.png" alt="Company Logo" style={{ height: "80px", width: "200px" }} />
<br />
</div>
<fieldset>
<div className="Main-header">
<h1>Sign-In</h1>
<p>Limtless Water. From Unlimited Air.</p>
<form onSubmit={this.onSignInSubmit}>
<div id="sign-in-button"></div>
<label>Mobile Number</label> <br />
<IntlTelInput
containerClassName="intl-tel-input"
inputClassName="form-control"
name="mobile"
placeholder="Enter Your Number"
input
type="tel"
value={this.state.phoneNumber}
onPhoneNumberChange={this.handlePhoneChange}
/>
{/* <input type="tel" id="phone" name="mobile" placeholder="Enter Your Number" required onChange={this.handleChange} /> */}
<div className="buttons">
<button type="submit">Verify</button>
</div>
</form>
<div>
<form onSubmit={this.onSubmitOTP}>
<label >Code</label> <br />
<input type="text" name="otp" placeholder="Enter six digit code" required onChange={this.handleChange} />
<div className="buttons" >
<button type="submit">Continue</button>
</div>
</form>
</div>
</div>
</fieldset>
</main>
</>
)
}
}
export default Login;
after running the code i got this message but my number is registered
But my code work perfectly with this
<input type="tel" id="phone" name="mobile" placeholder="Enter Your Number" required onChange={this.handleChange} /> but i don't want to take input with normal input tag because here user have to type country code manually

How to integrate react-intl-tel-input-v2

While using react-intl-tel-input-v2 I was getting this error:-× TypeError: Cannot read properties of null (reading 'e') I have install the react-intl-tel-input-v2 from npm Try many things but nothing work if anyone know the solution please help Even if you know any other npm package which help me please suggest
I was getting the error in this part:-
handleChange = (e) => { const { name, value } = e.target this.setState({ [name]: value
This is my code
import React from 'react'
import firebase from './firebase'
import 'firebase/auth';
import "./App.css";
import { getDatabase, ref, child, get } from "firebase/database";
// import PhoneInput from 'react-phone-number-input'
// import $ from 'jquery';
// import intlTelInputUtils from 'jquery';
import ReactIntlTelInput from 'react-intl-tel-input-v2';
import 'intl-tel-input/build/css/intlTelInput.css';
class Login extends React.Component {
handleChange = (e) => {
const { name, value } = e.target
this.setState({
[name]: value
})
this.setState({ phoneNumber: value }, () => {
console.log(this.state.phoneNumber);
});
}
configureCaptcha = () =>{
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
'size': 'invisible',
'callback': (response) => {
// reCAPTCHA solved, allow signInWithPhoneNumber.
this.onSignInSubmit();
console.log("Recaptca varified")
},
defaultCountry: "IN"
}
);
}
onSignInSubmit = (e) => {
e.preventDefault()
this.configureCaptcha()
const phoneNumber = this.state.mobile
console.log(phoneNumber)
const appVerifier = window.recaptchaVerifier;
const dbRef = ref(getDatabase());
get(child(dbRef, `Users/${phoneNumber}`)).then((snapshot) => {
if (snapshot.exists()) {
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then((confirmationResult) => {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
alert('An OTP has been sent to your registered mobile number')
localStorage.setItem("Phone_No", phoneNumber)
console.log(localStorage.getItem('Phone_No'));
}).catch((error) => {
console.error(error);
alert("Oops! Some error occured. Please try again.")
});
}
else {
alert('Sorry, this mobile number is not registered with us. Please use your registered mobile number.');
}
})
}
onSubmitOTP = (e) => {
e.preventDefault()
const code = this.state.otp
console.log(code)
window.confirmationResult.confirm(code).then((result) => {
// User signed in successfully.
const Users = result.user;
console.log(JSON.stringify(Users))
this.props.history.push("/home");
}).catch((error) => {
alert("You have entered wrong code")
});
}
render() {
return (
<div className="Main-header">
<img src="./55k-logo.png" alt="Company Logo" style={{ height: "80px", width: "200px" }} />
<br />
<div>
<h2>Login Form</h2>
<p>Limtless Water. From Unlimited Air.</p>
<form onSubmit={this.onSignInSubmit}>
<div id="sign-in-button"></div>
{/* <PhoneInput */}
<label>Mobile Number</label> <br />
{/* for="phoneNumber" */}
<ReactIntlTelInput
type="tel" id="phone" name="mobile" placeholder="Enter Your Number" required onChange={this.handleChange}
value={this.state.value}
// onChange={this.handleChange}
/>
{/* <input type="tel" id="phone" name="mobile" placeholder="Enter Your Number" required onChange={this.handleChange} /> */}
<div className="buttons">
<button type="submit">Submit</button>
</div>
</form>
</div>
<div>
<form onSubmit={this.onSubmitOTP}>
<label >Code</label> <br />
{/* for="code" */}
<input type="number" name="otp" placeholder="Enter The 6 Digit OTP" required onChange={this.handleChange} />
<div className="buttons" >
<button type="submit">Submit</button>
</div>
</form>
</div>
</div>
)
}
}
export default Login;

How does Firebase phone number authentication work?

Firebase Phone number authentication not working. Upon submitting the form for entering the phone number, this is what the error shows: Google Sign in works but not the registration using Phone number.
Uncaught TypeError:
firebase_utils__WEBPACK_IMPORTED_MODULE_2_.auth.RecaptchaVerifier is not a function
import React, { useState, useEffect } from "react";
import { Button, TextField } from "#material-ui/core";
import { signInWithGoogle, firestore, auth } from "./../firebase/utils";
const Register = (props) => {
const [currentUser, setCurrentUser] = useState("");
const [displayName, setDisplayName] = useState("");
const [phoneNumber, setPhoneNumber] = useState("");
const [otp, setOtp] = useState("");
const getCurrentUser = () => {
auth.onAuthStateChanged((user) => {
if (user) {
const uid = user["uid"];
const name = user.displayName;
console.log("uid: ", uid);
console.log(name);
setCurrentUser(uid);
setDisplayName(name);
} else {
console.log("uid: ", "no uid");
}
});
};
useEffect(() => {
getCurrentUser();
}, []);
const configureCaptcha = () => {
window.recaptchaVerifier = auth.RecaptchaVerifier("sign-in-button", {
size: "invisible",
callback: (response) => {
// reCAPTCHA solved, allow signInWithPhoneNumber.
onSignInSubmit();
console.log("Verified");
},
defaultCountry: "PH",
});
};
const onSignInSubmit = (e) => {
e.preventDefault();
configureCaptcha();
const phoneNumber = phoneNumber;
console.log(phoneNumber);
const appVerifier = window.recaptchaVerifier;
auth
.signInWithPhoneNumber(phoneNumber, appVerifier)
.then((confirmationResult) => {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
console.log("OTP has been sent");
// ...
})
.catch((error) => {
// Error; SMS not sent
// ...
console.log(error);
});
};
return (
<div>
<h1>Google SIGN IN</h1>
<Button variant="contained" onClick={signInWithGoogle}>
Google Sign In
</Button>
{auth.currentUser ? (
<div>
{" "}
<br />
UID: {currentUser}
<br />
Name: {displayName}
</div>
) : (
<div>
<h1>NOT LOGGED IN </h1>
<form onSubmit={onSignInSubmit}>
<div id="sign-in-button"></div>
<TextField
type="number"
name="mobile"
placeholder="mobile"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
/>
<Button type="submit">Submit</Button>
</form>
<h2>Enter OTP</h2>
<form>
<TextField
type="number"
name="OTP"
placeholder="Enter OTP"
value={otp}
onChange={(e) => setOtp(e.target.value)}
/>
<Button type="submit">Submit</Button>
</form>
</div>
)}
</div>
);
};
export default Register;
I doubt your code looks like this and that's incorrect:
const auth = firebase.auth()
window.recaptchaVerifier = auth.RecaptchaVerifier()
Try this instead
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(...)
// ^^^^ not auth()

How to successfully register users within redux using firebase auth

I keep getting the error undefined when registering a user.
I'm not sure if react is obtaining the states information correctly. Maybe it could be the onChange value, or maybe im missing something else.
I referenced this
How to implement Firebase authentication with React Redux?
but still unsure, what the error can be.
It shows that the user has been sign up on the backend like this.
Demo
https://stackblitz.com/edit/react-h9ekc4
Actions
export const onEmailSignUpChangeAction = value => ({
type: EMAIL_SIGN_UP_CHANGE,
email: value
})
export const onPasswordSignUpChangeAction = value => ({
type: PASSWORD_SIGN_UP_CHANGE,
password: value
})
export const onEmptySignUpEmailClick = () => ({
type: 'EMPTY_SIGN_UP_EMAIL'
})
export const onEmptySignUpPasswordClick = () => ({
type: 'EMPTY_SIGN_UP_PASSWORD'
})
export const signUp = () => (dispatch, getState) => {
const {signUpAuth} = getState();
if (signUpAuth.emailSignUp === '') {
dispatch(onEmptySignUpEmailClick())
}
if (signUpAuth.passwordSignUp === '') {
dispatch(onEmptySignUpPasswordClick())
}
else {
firebaseAuth.createUserWithEmailAndPassword(signUpAuth.emailSignUp, signUpAuth.passwordSignUp)
.then(() => console.log('signUpok'))
.catch( function (error) {
let errorCode = error.code;
let errorMessage = error.message;
alert(errorMessage)
});
}
}
SignUp.js
import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import { signUp, onEmailSignUpChangeAction, onPasswordSignUpChangeAction } from '../actions/';
class SignUp extends Component {
state = {
email: "",
password: ""
}
// onChange = (e) =>{
// this.setState({
// [e.target.name] : e.target.value
// })
// }
handleSubmit = (e) => {
e.preventDefault();
const register = this.props.signUp();
console.log(register);
(register === true) && this.props.history.push('/');
console.log(this.state)
}
render() {
return (
<div className="container">
<div className="row">
<div className="col-md-6">
<h1>Sign Up</h1>
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email address</label>
<input
type="email"
className="form-control"
id="email"
onChange={this.props.onEmailSignUpChangeAction}
aria-describedby="emailHelp"
value={this.props.emailSignUp}
placeholder="Enter email" />
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div className="form-group">
<label htmlFor="exampleInputPassword1">Password</label>
<input
type="password"
className="form-control"
id="password"
value={this.props.passwordSignUp}
onChange={this.props.onPasswordSignUpChangeAction}
placeholder="Password" />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => ({
user: state.auth.user,
emailSignUp: state.signUpAuth.emailSignUp,
passwordSignUp: state.signUpAuth.passwordSignUp
})
const mapDispatchToProps = (dispatch) => ({
signUp: () => dispatch(signUp()),
onEmailSignUpChangeAction: (event) => dispatch(onEmailSignUpChangeAction(event.target.value)),
onPasswordSignUpChangeAction: (event) => dispatch(onPasswordSignUpChangeAction(event.target.value)),
});
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(SignUp));
Reducers.js
const initialState = {
emailSignUp: '',
passwordSignUp: '',
errorTextEmailSignUp: '',
errorTextPasswordSignUp: ''
}
export default (state = initialState, action) => {
switch (action.type) {
case EMAIL_SIGN_UP_CHANGE:
return {
...state,
emailSignUp: action.email
}
case PASSWORD_SIGN_UP_CHANGE:
return {
...state,
passwordSignUp: action.password
}
case EMPTY_SIGN_UP_EMAIL:
return {
...state,
errorTextEmailSignUp: 'This field is required'
}
case EMPTY_SIGN_UP_PASSWORD:
return {
...state,
errorTextPasswordSignUp: 'This field is required'
}
default:
return state
}
}
If you want to pass this.props.emailSignUp and this.props.passwordSignUp into your signUp function you could try:
export const signUp = (email, password) => { return (dispatch) => {
if (email === '') {
dispatch({ type: EMPTY_SIGN_UP_EMAIL })
}
else if (password === '') {
dispatch({ type: EMPTY_SIGN_UP_PASSWORD })
}
else {
firebaseAuth.createUserWithEmailAndPassword(email, password)
.then(() => console.log('signUpok'))
.catch( function (error) {
let errorCode = error.code;
let errorMessage = error.message;
alert(errorMessage)
});
}
}
}
Then call your function this.props.signUp(this.props.emailSignUp, this.props.passwordSignUp)
You are assigning signUp method's return to subscribed variable but that method does return nothing.
Since its execution is asynchronous, you may need to dispatch an action that will cause a reducer to store the created user in the state when creation has succeeded, then make use of a selector for retrieving that user for instance.

Categories

Resources