Nodejs-Assignment-8

 Create following routes in User API



 1. Get user by username (Password should not be included)

 2. Get all users (Passwords should not be included)

 3. Login user



Website links:

https://jwt.io/

https://www.npmjs.com/


Sample code for User login:

----------------------------------

userApp.post('/user-login',expressAsyncHandler(async(request,response)=>{

//get userCollectionObj
const userCollectionObj = request.app.get("userCollectionObj");

//get user credentials from req
const userCredObj=request.body;

//verify username
let userOfDB=await userCollectionObj.findOne({username:userCredObj.username})

//if username is invalid
if(userOfDB===null){
response.status(200).send({message:"Invalid username"})
}
//if username is valid
else{
//verify password
let isEqual=await bcryptjs.compare(userCredObj.password,userOfDB.password)
//if passwords not matched
if(isEqual===false){
response.status(200).send({message:"Invalid password"})
}
//if passwords matched
else{
//create a JWT token
let jwtToken=jwt.sign({username:userOfDB.username},'abcdef',{expiresIn:20})
//send token in response
response.status(200).send({message:"Valid user",token:jwtToken})
}
}
}))

Comments

Popular posts from this blog