Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'bcryptjs' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
const { name, email, password } = event.data;
if (!validator.isEmail(email)) {
return { error: 'Not a valid email' };
}
// check if user exists already
const userExists: boolean = await getUser(api, email)
.then(r => r.User !== null);
if (userExists) {
return { error: 'Email already in use' };
}
// create password hash
const salt = bcrypt.genSaltSync(SALT_ROUNDS);
const hash = await bcrypt.hash(password, salt);
// create new user
const userId = await createGraphcoolUser(api, name, email, hash);
// generate node token for new User node
const token = await graphcool.generateNodeToken(userId, 'User');
return { data: { id: userId, token } };
} catch (e) {
console.log(e);
return { error: 'An unexpected error occured during signup.' };
}
};
handler.put(async (req, res) => {
// password reset
if (!req.body.password) return res.status(400).end();
const { value: tokenDoc } = await req.db
.collection('tokens')
.findOneAndDelete({ _id: req.query.token, type: 'passwordReset' });
if (!tokenDoc) {
return res.status(200).json({
status: 'error',
message: 'This link may have been expired.',
});
}
const password = await bcrypt.hash(req.body.password, 10);
await req.db
.collection('users')
.updateOne({ _id: tokenDoc.userId }, { $set: { password } });
return res.json({ message: 'Your password has been updated.' });
});
bcrypt.genSalt(10, function (error, salt) {
bcrypt.hash(password, salt, function (error, hash) {
if (error) return res.status(400).json({ success: false, description: error });
req.body.password_hash = hash; // 'password_hash' transfers and saves to DB
delete req.body.password || req.body.newPassword;
next();
});
});
}
}, (err, user) => {
if (err)
throw err;
if(!user){
res.json({
status: false,
message: 'Authentication failed, user not found.'
});
}else{
bcrypt.compare(password, user.password).then((result) => {
if (!result){
res.json({
status: false,
message: 'Authentication failed, wrong password.'
});
}else{
const payload = {
username
};
const token = jwt.sign(payload, req.app.get('api_secret_key'), {
expiresIn: 720 // 12 saat
});
res.json({
status: true,
token
// pick the first found
var user = items[0];
ldapClient.bind(user.dn, password, function (error) {
if (error) return callback('Invalid credentials');
callback(null, { username: username });
});
});
});
});
} else {
var users = safe.JSON.parse(safe.fs.readFileSync(LOCAL_AUTH_FILE));
if (!users || !users[username]) return callback('Invalid credentials');
bcrypt.compare(password, users[username].passwordHash, function (error, valid) {
if (error || !valid) return callback('Invalid credentials');
callback(null, { username: username });
});
}
}
set(val) {
// 加密
const salt = bcrypt.genSaltSync(10);
// 生成加密密码
const psw = bcrypt.hashSync(val, salt);
this.setDataValue("password", psw);
},
allowNull: false,
errors = {...errors, [field]: 'Passwords do not match'}
}
});
if (Object.keys(errors).length > 0) {
res.json({ errors });
} else {
const newUser = new User({
name: name,
username: username,
email: email,
password: password
});
// Generate the Salt
bcrypt.genSalt(10, (err, salt) => {
if(err) return err;
// Create the hashed password
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) return err;
newUser.password = hash;
// Save the User
newUser.save(function(err){
if(err) return err
res.json({ success: 'success' });
});
});
});
}
});
return Validation.userExists(username).then(user => {
if (!bcrypt.compareSync(oldPassword, user.password)) {
throw new Error("Incorrect password");
}
const newPasswordHash = bcrypt.hashSync(newPassword, 10);
const updateOperation = {$set: {password: newPasswordHash}};
return mean.db.collection("users")
.updateOne({username: username}, updateOperation)
.then(write_res => {
if (write_res.modifiedCount !== 1) {
throw new Error("Couldn't save new password");
}
// report
return bus.update_atom("User", user.atom_id, updateOperation);
})
static async verifyEmailPassword(email, plainPassword) {
// 查询用户是否存在
const user = await User.findOne({
where: {
email
}
})
if (!user) {
throw new global.errs.AuthFailed('账号不存在')
}
// 验证密码是否正确
const correct = bcrypt.compareSync(plainPassword, user.password);
if (!correct) {
throw new global.errs.AuthFailed('密码不正确')
}
return user
}
return Validation.userExists(username).then(user => {
// TODO: promisify
if (!bcrypt.compareSync(password, user.password)) {
throw new Error("Incorrect password");
}
const token = jwt.sign(username, "ultra-secret-key");
return JSON.stringify({
token: token,
user: user
});
});
}