Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Password hashing and salting is pending ! #7

Open
Sanket00900 opened this issue Jan 30, 2024 · 3 comments
Open

Password hashing and salting is pending ! #7

Sanket00900 opened this issue Jan 30, 2024 · 3 comments

Comments

@Sanket00900
Copy link

Whenever we are creating new user, the user's password should be hased before saving to the database

@vineet-op
Copy link

Here https://youtu.be/m_8rwKsYmnY?si=M0ZJC8GbDNF2Z6j3

This might Help You

@RevanthMali
Copy link

RevanthMali commented Mar 23, 2024

I hope this might help you it's working, modify the code accordingly ,
##IN db.js
userSchema.methods.createHash = async function(plainTextPassword){
const saltRounds = 10;
const salt = await bcrypt.genSalt(saltRounds);
return await bcrypt.hash(plainTextPassword,salt)
}
userSchema.methods.validatePassword= async function(candidatePassword){
return await bcrypt.compare(candidatePassword,this.password_hash);
}

##IN user.js
var hashedPassword = await user.createHash(req.body.password);
user.password = hashedPassword;
await user.save();

@Znaxh
Copy link

Znaxh commented Jul 23, 2024

// backend/routes/user.js
const express = require('express');
const bcrypt = require('bcrypt')
const router = express.Router();
const zod = require("zod");
const { User, Account } = require("../db");
const jwt = require("jsonwebtoken");
const { JWT_SECRET } = require("../config");
const  { authMiddleware } = require("../middleware");
const saltRound = 10;

const signupBody = zod.object({
    username: zod.string().email(),
	firstName: zod.string(),
	lastName: zod.string(),
	password: zod.string()
})

router.post("/signup", async (req, res) => {
    const { success } = signupBody.safeParse(req.body)
    if (!success) {
        return res.status(411).json({
            message: "Email already taken / Incorrect inputs"
        })
    }

    const existingUser = await User.findOne({
        username: req.body.username
    })

    if (existingUser) {
        return res.status(411).json({
            message: "Email already taken/Incorrect inputs"
        })
    }

    const password = req.body.password;
    bcrypt.hash(password,saltRound,async function(err,hash){
        const user = await User.create({
            username: req.body.username,
            password: hash,
            firstName: req.body.firstName,
            lastName: req.body.lastName,
        })
        
            const userId = user._id;
        
            await Account.create({
                userId,
                balance: 1 + Math.random() * 10000
            })
        
            const token = jwt.sign({
                userId
            }, JWT_SECRET);
        
            res.json({
                message: "User created successfully",
                token: token
            })
    })
})


const signinBody = zod.object({
    username: zod.string().email(),
	passwo33rd: zod.string()
})

router.post("/signin", async (req, res) => {
    const { success } = signinBody.safeParse(req.body)
    if (!success) {
        return res.status(411).json({
            message: "Email already taken / Incorrect inputs"
        })
    }

    const user = await User.findOne({
        username: req.body.username,
    });

    bcrypt.compare(req.body.password,user.password,function(err,result){
        if (result) {
            const token = jwt.sign({
                userId: user._id
            }, JWT_SECRET);
      
            res.json({
                token: token
            })
            return;
        }else{
            console.log(err);
        }
    })
    
    res.status(411).json({
        message: "Error while logging in"
    })
})

const updateBody = zod.object({
	password: zod.string().optional(),
    firstName: zod.string().optional(),
    lastName: zod.string().optional(),
})

router.put("/", authMiddleware, async (req, res) => {
    const { success } = updateBody.safeParse(req.body)
    if (!success) {
        res.status(411).json({
            message: "Error while updating information"
        })
    }
    bcrypt.hash(req.body.password,saltRound,async function(err,result){
        const checkBody = {
            password: result,
            firstName: req.body.firstName,
            lastName: req.body.lastName,
        }
        await User.updateOne(checkBody, {
            id: req.userId
        })
    
        res.json({
            message: "Updated successfully"
        })
    })
})

router.get("/bulk", async (req, res) => {
    const filter = req.query.filter || "";

    const users = await User.find({
        $or: [{
            firstName: {
                "$regex": filter
            }
        }, {
            lastName: {
                "$regex": filter
            }
        }]
    })

    res.json({
        user: users.map(user => ({
            username: user.username,
            firstName: user.firstName,
            lastName: user.lastName,
            _id: user._id
        }))
    })
})

module.exports = router;

this should work ig

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants