Skip to content

Instantly share code, notes, and snippets.

@Andaeiii
Last active April 1, 2022 15:40
Show Gist options
  • Save Andaeiii/9197b32f3870158c170c9add305c73c0 to your computer and use it in GitHub Desktop.
Save Andaeiii/9197b32f3870158c170c9add305c73c0 to your computer and use it in GitHub Desktop.
using bcrypt to encrypt password in nodejs/express applications using moongoose...
//npm install bcrypt --save
import bcrypt from 'bcryptjs';
import UserModel from '../models/users.js';
export default config = {
PORT: 5200,
DB_USER: '.......',
DB_PASS: '.......',
DB_NAME: '.......',
SALT_ROUNDS: 10
};
var salt = bcrypt.genSaltSync(config.SALT_ROUNDS);
export const createUser = async (req, res) => {
const user = req.body;
const hashed = bcrypt.hashSync(user.password, salt); //hash password here....
const userObj = { ...user, password: hashed };
......
};
//controller function to validate and check password.. using bcrypt.
export const loginUser = async (req, res) => {
const user = req.body;
try {
const userObj = await UserModel.findOne({ email: user.email }).exec();
if (!mongoose.Types.ObjectId.isValid(userObj._id)) return res.status(404).send('user does not exist'); //check for valid ids...
const result = bcrypt.compareSync(user.password, userObj.password) == true ? TRUE : FALSE;
.....
} catch (error) {
res.status(409).json({ message: error.message })
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment