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.

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay