DEV Community

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

Posted on

3 1

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.

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay