I am trying to add users with email and password function in Firebase but the information is not added once the sign up button is clicked. I have inserted the block of code I've written to perform this action. I'm not sure what I'm missing.The user information does not appear in the console and there is no error message. All other data that is entered works, the authentication part is the only thing that is not working correctly.
// signing new users up
const signupForm = document.querySelector('.signup');
signupForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = signupForm.email.value;
const password = signupForm.password.value;
createUserWithEmailAndPassword(auth, email, password)
.then((cred) => {
// console.log('user created:', cred.user);
signupForm.reset();
})
.catch((err) => {
// console.log(err.message);
});
// logging in and out
const logoutButton = document.querySelector('.logout');
logoutButton.addEventListener('click', () => {
signOut(auth)
.then(() => {
alert('user signed out');
})
.catch((err) => {
console.log(err.message);
});
});
const loginForm = document.querySelector('.login');
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = loginForm.email.value;
const password = loginForm.password.value;
signInWithEmailAndPassword(auth, email, password)
.then((cred) => {
console.log('user logged in:', cred.user);
loginForm.reset();
})
.catch((err) => {
console.log(err.message);
});```
Related
When the user clicks on the "sign-in" button and if user.challangeName === 'NEW_PASSWORD_REQUIRED'is true, I redirect the user to a page (form screen) where he can provide the input for required attributes and a new password. Even tho the user object is getting populated upon clicking on the sign-in button, using Auth.currentsession on the form screen will print "No user found"
Can someone let me know why I'm seeing no user? What am I doing wrong here?
Here's my login function (triggered when clicked on sign-in button) where I direct the user to the change password screen (form screen) if user.challangeName === 'NEW_PASSWORD_REQUIRED' is true.
const login = async (email, password) => {
try {
const user = await Auth.signIn(email, password);
if (user.challengeName === 'NEW_PASSWORD_REQUIRED') {
navigate('/change-password');
return;
}
if (user) {
setToken(user.signInUserSession.idToken.jwtToken);
const userDetails = await getAccountDetails();
dispatch({
type: LOGIN,
payload: {
user: {
attributes: user.attributes,
username: user.username
},
client: userDetails
}
});
}
} catch (error) {
await logout();
throw error;
}
};
Here's my onSubmit function on the change password screen where eventually I want to use Auth.completeNewPassword to update the user's password in Cognito
const onSubmitClick = (e) => {
e.preventDefault();
if (validateFields());
Auth.currentSession()
.then((user) => console.log(user))
.catch((err) => console.log(err));
};
Here's the documentation provided by AWS https://docs.amplify.aws/lib/auth/manageusers/q/platform/js/#forgot-password, and the code provided by AWS to update password
Auth.signIn(username, password)
.then(user => {
if (user.challengeName === 'NEW_PASSWORD_REQUIRED') {
const { requiredAttributes } = user.challengeParam; // the array of required attributes, e.g ['email', 'phone_number']
Auth.completeNewPassword(
user, // the Cognito User Object
newPassword, // the new password
// OPTIONAL, the required attributes
{
email: 'xxxx#example.com',
phone_number: '1234567890'
}
).then(user => {
// at this time the user is logged in if no MFA required
console.log(user);
}).catch(e => {
console.log(e);
});
} else {
// other situations
}
}).catch(e => {
console.log(e);
});
New updated answer to reflect your updated post, change the onSubmitClick to the following:
const onSubmitClick = (e) => {
e.preventDefault();
if (validateFields());
Auth.currentAuthenticatedUser()
.then(user => {
console.log(user))
})
.then((data) => console.log(data))
.catch((err) => console.log(err));
};
You are looking at the documentation which shows how to use the user after Auth.signIn() (which was my previous answer), compared to what you use: Auth.currentAuthenticatedUser(). The proper documentation example you have to look at is this one: https://www.docs.amplify.aws/lib/auth/manageusers/q/platform/js
I cannot update user name where user is sign in to website it doesnt addit to user account, on displaName it shows null.The user account is created succefully but without user name as i said
const onSubmit = async ({ name, email, password }) => {
setIsLoading(true);
try {
await signup(email, password);
await updateProfile(currentUser, {
displayName: name,
});
setInterval(() => {
<Redirect to="/" />;
}, 5000);
} catch (error) {
setIsLoading(false);
console.log(error);
}
};
You can use .then().
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(() => {
// do whatever in here
setUserInfo()
sendEmailVerification()
setDisplayName()
alert('Account created!')
})
.catch(error => {
console.log(error)
alert(error.message)
})
Inside the setDisplayName(), you can set the displayName. In my case, I am using the firstName and lastName, which I am getting through my form.
const setDisplayName = () => {
firebase
.auth()
.currentUser
.updateProfile({
displayName: firstName + ' ' + lastName
})
.then(() => {
console.log('display name set')
})
.catch(error => {
console.log(error)
alert(error.message)
})
}
I have a problem with firebase, I want when a user creates a user for the first time, add him to updateProfile, personal details.
This is the code I'm trying to do but the code is not running, it does not work for me.
The part with the currentUser does not work, I do not understand why, I also do not get an error.
signupUser = async () => {
const newUser = {
email: 'test#mail.com',
password: '123456'
};
await signup(newUser);
}
call to signup in nodejs
export const signup = (newUser) => (dispatch) => {
axios
.post('/signup', newUser)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
};
signup - nodejs
//basically call to this function to signup
exports.signup = (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password
};
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then((data) => {
const currentUser = firebase.auth().currentUser;
const name = `${"adding some private information"}`;
currentUser.updateProfile({
displayName: name,
})
.then(() => {
console.log("sign in successfully")
});
return data.user.getIdToken();
})
.then((token) => {
return db.doc(`/users/${newUser.handle}`).set("test");
})
.then(() => {
return res.status(201).json({ token });
})
.catch((err) => {
console.error(err);
});
};
The issue looks to be that you aren't return the promise from currentUser.updateProfile, ensuring it successfully completes. Try the following by returning the Promise from that method:
exports.signup = (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
};
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then((data) => {
const currentUser = firebase.auth().currentUser;
const name = `${"adding some private information"}`;
return currentUser
.updateProfile({
displayName: name,
})
.then(() => {
console.log("sign in successfully");
return data.user.getIdToken();
});
})
.then((token) => {
return db.doc(`/users/${newUser.handle}`).set("test");
})
.then(() => {
return res.status(201).json({ token });
})
.catch((err) => {
// probably send an error back?
// return res.status(500).json({ message: 'error' });
console.error(err);
});
};
I have a function "signInWithPhoneNumber" in SignUp screen after call it navigates me to a Confirmation Screen and I pass some params after navigate to confirm a verification code I was received,
So in this screen "Confirmation", I have a button "Re-send Verification Code" so my question is
when I press to "re-send" I want to call a "signInWithPhoneNumber" function in SignUp screen to get a new code
So what you think? that's possible?
Or rewrite a signInWithPhoneNumber in a confirmation screen and call it after pressed re-send button?
SignUp Screen - Function
signUp = async () => {
const {phoneNumber} = this.state;
this.setState({message: 'Sending code ...'});
const phoneWithAreaCode = phoneNumber.replace(/^0+/, '+972');
console.log(phoneWithAreaCode);
auth()
.signInWithPhoneNumber(phoneWithAreaCode, true)
.then(confirmResult => {
console.log('confirmResult', confirmResult);
this.setState({confirmResult, message: 'Code has been sent!'});
// this.createUserDatabase();
})
.then(() => {
this.props.navigation.navigate('Confirmation', {
message: this.state.message,
confirmResult: this.state.confirmResult,
createUser: uid => this.createUserDatabase(uid),
});
});
};
Confirmation screen - function
confirmCode = codeInput => {
const confirmResult = this.props.navigation.state.params.confirmResult
if (confirmResult && codeInput.length) {
confirmResult
.confirm(codeInput)
.then(user => {
clearInterval(this.interval);
const {params} = this.props.navigation.state;
//Check if any users exist
database()
.ref(`users`)
.limitToFirst(1)
.once('value', snapshot => {
if (snapshot.exists()) {
console.log('exists!');
return true;
} else {
params.createUser(user.uid);
console.log('No user found Hah');
}
});
this.setState({
timer: 0,
message: 'Code Confirmed!',
isValid: true,
});
})
.catch(error => {
let errorCode = error.code;
let errorMessage = error.message;
console.log(errorCode);
switch (errorCode) {
case 'auth/invalid-verification-code':
this.setState({message: 'Code is invalid', codeInput: ''});
this.refs.codeInputRef2.clear();
break;
default:
alert(`Please, Check your Messages!`);
break;
}
console.log(errorMessage);
});
} else {
console.log('Not here');
}
};
You can send signInWithPhoneNumber to Confirmation screen, while navigating to it from SignUp screen, like so
this.props.navigation.navigate('Confirmation', {
message: this.state.message,
confirmResult: this.state.confirmResult,
createUser: uid => this.createUserDatabase(uid),
signInWithPhoneNumber: signInWithPhoneNumber // your actual function here
});
});
And then this function will be available in Confirmation screen as a prop, and you can call it when necessary
I have done authentication trigger, it's working fine. If someone delete their account I need to send to notification "this user deleted his account (email)" like that. Here is my code
const functions = require('firebase-functions')
//initialize the app
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
const ref = admin.database().ref()
//create user account function
exports.createUserAccount = functions.auth.user().onCreate(event => {
const uid = event.data.uid
const email = event.data.email
const newUserRef = ref.child(`/UserNotify/${uid}`)
return newUserRef.set({
email: email
})
})
//delete user account function
exports.cleanupUserData = functions.auth.user().onDelete(event => {
const uid = event.data.uid
const userRef = ref.child(`/UserNotify/${uid}`)
return userRef.update({isDeleted: true})
})
function sendNotification() {
console.log("Successfully sent");
var payload = {
notification: {
title: "User get deleted",
body: "sample#gmail.com"
}
};
admin.messaging().sendToDeveice(payload)
.then(function (response) {
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
})
}
You may have a typing error
admin.messaging().sendToDevice() and not sendToDeveice
check: https://firebase.google.com/docs/cloud-messaging/admin/send-messages