DEV Community

Cover image for How we secure our password in express and mongoDB
Sandeep
Sandeep

Posted on

How we secure our password in express and mongoDB

many developers think how we secure our password through malicious user they try to access data and destroy their server.
In express we discuss a library named is "bcrypt" they hashed our data and this hashed data does not decrypt any user this is best feature of this library.
Install in your system

npm i express mongoose bcrypt

userSchema.js

const {Schema,model}=mongoose
const userSchema=new Schema({
username:String,
password:String
)}
const User=model('user',userSchema)
module.exports=User

Enter fullscreen mode Exit fullscreen mode

send data through this api end point

index.js

router.post('/api/register',acync (req,res)=>{
    const {username,password}=req.body
                    const oldUser=await User.findOne({username})
    if(oldUser) return res.status(400).send("User already registered")
    const salt=await bcrypt.getSalt(10)
    const hashPassword=await bcrypt.hash(password,salt);
                    const user=new User({username,password:hashPassword})
                    const result=await user.save()
    res.status(200).send(result);
             });
Enter fullscreen mode Exit fullscreen mode

above example is register it and saved their data

Image description


router.post('/api/login',acync (req,res)=>{
    const {username,password}=req.body
    const user=await User.findOne({username})
    (!user) return res.status(404).send("User Not Found")
    const hashPassword=await bcrypt.compare(password,user.password);
                    if(user && hashPassword)
    return res.send({username,password:hashPassword});
    else
    return res.status(400).send("password is wrong")
             });


Enter fullscreen mode Exit fullscreen mode

above code is login user with athenticated.

Discussion (0)