Node.js pratics
I am not sure if I am using .then() and .catch() functions on the right way you can find my code below of a login function. Could you tell me if this code is ok or if it's a bad pratic? I didn't find code like mines on the web that's why I ask and I am worry.... If it's a bad pratic, how to right this code on the right way ? Thank you by advance :)
const login = (request, response) => {
// user login informations
const user = {
email: request.body.email,
password: request.body.password
}
// check if there is erros in datas
const { valid, errors } = validateLoginDatas(user)
if (!valid) {
return response.status(400).json(errors)
}
// firebase authentification
firebase.auth().signInWithEmailAndPassword(user.email, user.password)
.then(() => {
// we create an access token and save it in db, it will be util to refresh the access token when it will expire
const refreshToken = crypto.randomBytes(128).toString('base64')
getUserIdByEmail(user.email)
.then((idUser) => {
// update of the refreshToken
upsertUserRefreshToken(idUser, refreshToken)
getUserRoleWithId(idUser)
.then((role) => {
// new accessToken with id_user and user's role inside
const accessToken = jwt.sign(
{
idUser: idUser,
role: role
},
jwtConfig.secretKey,
{
algorithm: jwtConfig.algorithm,
expiresIn: jwtConfig.expiresIn
}
)
return response.json({ accessToken })
})
.catch((error) => {
return response.status(403).json({ error: error.message })
})
})
.catch((error) => {
return response.status(403).json({ error: error.message })
})
})
.catch((error) => {
if (error.code === 'auth/wrong-password') {
return response.status(403).json({ general: 'Wrong credentials, please try again' })
}
return response.status(500).json({ error: error.code })
})
}