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)
})
}
Related
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);
});```
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);
});
};
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Hi everyone I have such a problem,
After a user signs up for my site, for the first time, I want to log in with the user one more time.
I want that after he registers, connect again.
I tried to do it asynchronously, but it does not always work, sometimes I try to log in before the user is registers, I do not know why it does not work.
I want there to be a login only after registration, to force it.
handleSubmit = async () => {
const newUserData = {
email: 'test#mail.com',
password: '123456',
confirmPassword: '123456',
handle: 'test'
};
await signupUser(newUserData);
await signinChat(newUserData);
}
export const signupUser = (newUserData) => (dispatch) => {
axios
.post('/signup', newUserData)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
};
//basically call to this function to signup
exports.signup = (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
handle: req.body.handle,
};
db.doc(`/users/${newUser.handle}`)
.get()
.then((doc) => {
if (doc.exists) {
return res.status(400).json({ handle: "this handle is already taken" });
} else {
return firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password);
}
})
.then((data) => {
userId = data.user.uid;
return data.user.getIdToken();
})
.then((idToken) => {
token = idToken;
const userCredentials = {
handle: newUser.handle,
email: newUser.email,
};
const userPreferences = {
handle: newUser.handle
};
return db.doc(`/users/${newUser.handle}`).set(userCredentials);
})
.then(() => {
return res.status(201).json({ token });
})
.catch((err) => {
console.error(err);
if (err.code === "auth/email-already-in-use") {
return res.status(400).json({ email: "Email is already is use" });
} else {
return res
.status(500)
.json({ general: "Something went wrong, please try again" });
}
});
};
export const signinChat = (user) => {
return async (dispatch) => {
const db = firebase.firestore();
firebase.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then(data => {
console.log(data);
const currentUser = firebase.auth().currentUser;
const name = `${user.handle}`;
currentUser.updateProfile({
displayName: name,
})
.then(() => {
db.collection('users')
.doc(data.user.displayName)
.update({
isOnline: true,
})
.then(() => {
const loggedInUser = {
handle: user.handle,
uid: data.user.uid,
email: user.email
}
localStorage.setItem('user', JSON.stringify(loggedInUser));
console.log('User logged in successfully...!');
})
.catch(error => {
console.log(error);
});
});
})
.catch(error => {
console.log(error);
})
}
}
When I try to connect a second time, sometimes it does not work, for example:
image to show the error:
Is there any reason why I'm being signed out before my firebase actions are done finishing?
What Should Happen:
I first make a post request to my server to update values in my db.
Then I update the users firebase email if its changed.
Then I update the email if its changed as well.
Then finally I want to sign the user out.
What Happens:
I instantly gets signed out and then get errors in my console because the other actions couldn't be completed.
I have tried to trail the .then() after my axios post as well but I still had the same issue of being instantly signed out.
export const updateUserData = (userData) => {
return (dispatch, getState, {getFirebase}) => {
const state = getState();
const firebase = getFirebase()
let user = firebase.auth().currentUser;
let cred = firebase.auth.EmailAuthProvider.credential(user.email, userData.oldPassword);
user.reauthenticateWithCredential(cred).then(() => {
axios.post('/updateUserData', {
uid: state.firebase.auth.uid,
email: userData.email,
firstName: userData.firstName,
lastName: userData.lastName,
devices: userData.devices,
}, {
headers: {
"Authorization": `${state.firebase.auth.stsTokenManager.accessToken}`,
'Content-Type': 'application/json',
},
withCredentials: true
}).catch(err => {
console.log("Failed Email Change: " + err)
});
}).then(() => {
if (state.firebase.auth.email !== userData.email) {
firebase.auth().currentUser.updateEmail(userData.email).then(() => {
console.log("Email Changed")
}).catch(err => {
console.log("Failed Email Change: " + err)
});
}
}).then(() => {
if (userData.newPassword.length !== 0) {
firebase.auth().currentUser.updatePassword(userData.newPassword).then(() => {
console.log("Successful Password Change")
}).catch(err => {
console.log("Failed Password Change: " + err)
});
}
}).then(() => {
firebase.auth().signOut().then(null)
})
}
}
You aren't returning values from your promise chains. If you want an async action to take place after another one when using Promises, you need to return them:
// don't do this
doThing().then(() => {
doSomethingElse().then(() => { /* ... */ });
}).then(() => {
// this will happen before doSomethingElse is finished
finallyDoThing();
});
// instead do this
doThing().then(() => {
return doSomethingElse();
}).then(() => {
return finallyDoThing();
});
I am trying to add custom user claims after user sign up, to define user role, using setCustomUserClaims:
/api/users/addUser.js
export default async (req, res) => {
const { displayName, email, password, role } = req.body;
if (!displayName || !password || !email || !role) {
return res.status(400).send({ message: 'Missing fields' });
}
try {
const { uid } = await admin.auth().createUser({
displayName,
email,
password,
});
await admin.auth().setCustomUserClaims(uid, role);
res.status(201).send(uid);
} catch (error) {
handleError(res, error);
}
};
This code checks for any change in the authentication state and sets user to the currently logged in user:
/utils/use-auth.js
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
setUser(user);
} else {
setUser(false);
// Router.push('/login');
}
});
in my /pages/user/home,jsx:
import { useAuth } from '../../utils/use-auth';
function home() {
const { user } = useAuth();
return (
<div>
<pre>{JSON.stringify(user, null, 4)}</pre>
<AdminLayout componentProps={{ selected: '1' }} Component={HomeContent} />
</div>
);
}
The displayed object doesn't have any custom claims.
when I check the firebase console, I find that the user is actually added.
Try using
admin.auth().setCustomUserClaims(uid, claims).then(() => {
// Do your stuff here
});
And verify the claims like
admin.auth().verifyIdToken(idToken).then((claims) => {
// check claims
if (claims) {
// do your stuff here
}
});
for more info check https://firebase.google.com/docs/auth/admin/custom-claims#node.js