Cannot connect to Firebase authentication (nothing happen) - javascript

I build some authentication app including input username, password on firebase. But nothing happen after i press on Log in button on my application. It only shows "Authentication Failed".
class LoginForm extends Component {
state = {
email: '',password: '',error: '',loading: false
};
onButtonPress() {
const { email, password } = this.state;
this.setState({ error: '', loading: true });
firebase.auth().signInWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(this.onLoginFail.bind(this));
});
}
onLoginFail() {
this.setState({ error: 'Authentication Failed.', loading: false });
}
onLoginSuccess() {
this.setState({
email: '',password: '',error: '',loading: false});
}
render
....
value={this.state.email}
onChangeText={email => this.setState({ email })}
/>
</CardSection>
<CardSection>
<Input
...
onChangeText={password => this.setState({ password })}
/>

Try to catch the error and console.log it.
onButtonPress() {
const { email, password } = this.state;
this.setState({ error: '', loading: true });
firebase.auth().signInWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch((error) => { <===
console.log(error); <===
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(this.onLoginFail.bind(this));
});
}

Related

async/await + try/catch not working as spected when using a .then() function

I'm working on a project using react, and i need to redirect to a logged in page if register is successful, so I added a state called redirect, empty when you access the register form that I need to set so the page can redirect, since I use a handler, this is the relevant component code:
class Registro extends Component {
constructor() {
super();
this.state = {
email: "",
password: "",
passwordConfirm: "",
userName: "",
redirect: "",
};
}
handleRedirect = () => {
this.setState({ redirect: "/aplicacion" });
console.log(this.state);
}
render() {
if (this.state.redirect) {
return <Navigate to={this.state.redirect} />
}
return (
<button id="submit" className="btn btn-outline-accesible col-3 m-2 mt-3"
onClick={() => {
registerWithEmailAndPassword(this.state.userName, this.state.email, this.state.password).then(
handleRedirect()
)}}>Acceder</button>
And the register with email and password is this function:
const registerWithEmailAndPassword = async (name, email, password) => {
try {
console.log(name, email, password)
const res = await createUserWithEmailAndPassword(auth, email, password);
const user = res.user;
await setDoc(doc(db, "users", email), {
email: email,
nombre: name,
pass: password
});
alert("Registro completado con éxito")
} catch (err) {
console.error(err);
alert(err.message);
}
};
The expected outcome is that if the register is successful, the page reloads and you can go on your merry way, but if there's an error, the page won't load and the error will be alerted to the user. What is happening is that in the case there's an error, the page redirects you and then shows you an alert with the error data.
Thanks for reading and pondering this with me.
What is the idea beneath mixing approach?
This should work
class Registro extends Component {
render() {
if (this.state.redirect) {
return <Navigate to={this.state.redirect} />;
}
return (
<button
id="submit"
className="btn btn-outline-accesible col-3 m-2 mt-3"
onClick={this.handleClick}
>
Acceder
</button>
);
}
handleClick = async () => {
try {
await registerWithEmailAndPassword(
this.state.userName,
this.state.email,
this.state.password
);
handleRedirect();
} catch (err) {
console.error(err);
alert(err.message);
}
};
}
const registerWithEmailAndPassword = async (name, email, password) => {
console.log(name, email, password);
const res = await createUserWithEmailAndPassword(auth, email, password);
const user = res.user;
await setDoc(doc(db, "users", email), {
email: email,
nombre: name,
pass: password,
});
alert("Registro completado con éxito");
};
UPDATE:
Please note that registerWithEmailAndPassword also updated to support correct error handling according to the request
Your registerWithEmailAndPassword function is async, so it returns a Promise. In this function, you call another async function, and you wait for its response. You are catching the exceptions thrown by setDoc. So your registerWithEmailAndPassword always resolves. What you can do is :
Return something if the function succeeds
Return a rejected Promise in case of error
const registerWithEmailAndPassword = async (name, email, password) => {
try {
console.log(name, email, password)
const res = await createUserWithEmailAndPassword(auth, email, password);
const user = res.user;
await setDoc(doc(db, "users", email), {
email: email,
nombre: name,
pass: password
});
alert("Registro completado con éxito")
return true
} catch (err) {
console.error(err);
alert(err.message);
return Promise.reject(false);
}
};

What is the proper syntax for axios post call to django rest-auth token in React JS?

Currently, my code is communicating with my django-rest-auth api. It is getting the token, however, it is not authenicating the request. My backend shows 200 (username and password is correct). While my front end, reactjs is declaring wrong username or password (i created in else statement) and a 400 bad request error.
axios
.post(
'http://127.0.0.1:8000/rest-auth/login/',
{
username: this.state.username,
password: this.state.password
},
// { withCredentials: true }
{ isAuthenticated: true }
)
.then(response => {
const token = response.data.key;
if (localStorage.getItem(token)) {
console.log(token);
this.props.handleSucessfulAuth();
} else {
this.setState({
errorMessage: 'Wrong username or password'
});
this.props.handleUnsuccessfulAuth();
// console.log(token);
}
})
.catch(error => {
this.setState({
errorMessage: 'Authorization error occured',
error
})
this.props.handleUnsuccessfulAuth();
});
}
Now I have changed the top portion to the following:
handleSubmit(event) {
event.preventDefault();
axios.defaults.headers.common["Authorization"] = `Token ${this.props.token}`;
axios
.post(
'http://127.0.0.1:8000/rest-auth/login/',
{
username: this.state.username,
password: this.state.password
},
// { withCredentials: true }
{ isAuthenticated: true }
)
.then(response => {
const token = response.data.key;
if (localStorage.setItem(token, 'token')) {
console.log(token);
this.props.handleSucessfulAuth();
} else {
this.setState({
errorMessage: 'Wrong username or password'
});
this.props.handleUnsuccessfulAuth();
// console.log(token);
}
})

Unhandled Rejection (TypeError): __WEBPACK_IMPORTED_MODULE_2__config_fbConfig__.a.database is not a function

What im doing wrong here and why im getting this error, retrieving extra info that i saved with createUserWithEmailAndPassword
SignUP form details
const {email, password } = this.state;
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((data) => {
const { user } = data;
if(user){
firebase.database().ref('Users/Trainers/' + user.uid).set({
email: this.state.email,
firstName: this.state.firstName,
lastName: this.state.lastName,
role: this.state.role,
datecreated: Date.now()
});
this.props.history.push('/trainerSignin');
}
}).catch((error) => {
this.setState({ error: error });
});```
Profile Page Details
firebase.auth().onAuthStateChanged(user => {
if(user){
const db = firebase.database().ref('Users/Trainers/' + user.uid).once('value', snap => {
console.log(user.email);
console.log(user.firstName);
})
}
})
Here is my DB

To get the same id in firebase auth and realtime database

I have done the firebase auth and to save the same data in the firebase database. As shown in the image below, I want the same id which is created while login to get display on the database. I should get the same id if the login is successful.
constructor(props) {
super(props);
this.state = { email: '', password: '', error:
'',user:'',confirmpassword:'' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
static navigationOptions = {
title: 'Login',
};
state = { loggedIn: null };
handleChange(e) {
this.setState({
email: e.nativeEvent.text,
password: e.nativeEvent.textpassword,
user: e.nativeEvent.textuser,
confirmpassword: e.nativeEvent.textconfirmpassword,
});
}
handleSubmit(email,password,user) {
db.ref('sevenup-a1db1/').push({
email:this.state.email,
password:this.state.password,
user:''
}).then((data)=>{
console.log('data ' , data)
Alert.alert(
'Item saved successfully'
);
}).catch((error)=>{
console.log('error ' , error)
})
this.setState({ email, password,user });
}
The above code is for saving the data in the firebase database.
componentDidMount() {
let config = {
apiKey: "AIzaSyDPVoCjlIlLj1xrgros7hPjF8kkqsD4bSM",
authDomain: "sevenup-a1db1.firebaseapp.com",
databaseURL: "https://sevenup-a1db1.firebaseio.com",
projectId:"sevenup-a1db1",
storageBucket: "sevenup-a1db1.appspot.com",
messagingSenderId: "144328588028",
appId: "1:144328588028:web:2e5addaf8b3e83ad"
};
firebase.initializeApp(config);
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({ loggedIn: true })
} else {
this.setState({ loggedIn: false })
}
})
}
onButtonPress() {
this.setState({ error: '', loading: true })
const { email, password } = this.state;
firebase.auth().signInWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch((error) => {
let errorCode = error.code
let errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
this.onLoginFailure.bind(this)('Weak password!')
} else {
this.onLoginFailure.bind(this)(errorMessage)
}
});
});
}
The above code is for saving the data in firebase auth
I want that after successful login data should be saved in the database successfully. The same id should be displayed in the firebase database which is displayed in firebase auth.

Firebase user displayName is null

I'm running this code in my react app:
componentDidMount() {
modelInstance.addObserver(this);
modelInstance.getSignInStatus().then((user)=>{
this.setState({
userName: user !== false ? user.displayName : "Sign in",
logged_in: user !== false ? true : false
});
});
}
And here is modelInstance.getSignInStatus():
this.getSignInStatus = function () {
return new Promise((resolve, reject)=>{
firebase.auth().onAuthStateChanged(function(user){
if (user){
resolve(user);
}
else {
resolve(false);
}
});
});
}
What happens is that this.state.userName is set to null, meaning that user.displayName is null. Why is this?
state = {
username: "",
email: "",
passwordOne: "",
passwordTwo: "",
error: null
};
onSubmit = event => {
const {username, email, passwordOne} = this.state;
const {history} = this.props;
auth
.createUserWithEmailAndPassword(email, password);
.then(authUser => {
db.doCreateUser(authUser.uid, username, email).then(() => {
//you should clear your state fields here, for username / email etc
console.log(authUser);
//redirect user
history.push(routes.HOME);
});
})
.catch(error => {
this.setState({error});
});
event.preventDefault();
};
const auth = firebase.auth();
const db = firebase.database();
in order to acess doCreateUser
const doCreateUser = (id, username, email) =>
db.ref(`users/${id}`).set({
uid:id,
username,
email,
});
I would use setState for checking the auth status like so:
firebase.auth().onAuthStateChanged(function(user){
if (user){
this.setState({user});
}
}
Then you want the state of the displayName of the current user
componentDidMount() {
modelInstance.addObserver(this);
modelInstance.getSignInStatus().then((user)=>{
this.setState({
userName: this.state.user ? this.state.user.displayName : "Sign in",
logged_in: this.state.user ? true : false
});
});
}
Obviously there has to be a name in the displayName property, If not you would have to update it. Let me know how this turns out.

Categories