How to use bcryptjs - 10 common examples

To help you get started, we’ve selected a few bcryptjs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github plinionaves / angular-graphcool-chat / graphcool / src / email-password / signup.ts View on Github external
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.' };
  }
};
github hoangvvo / nextjs-mongodb-app / pages / api / user / password / reset / [token].js View on Github external
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.' });
});
github zmts / lovefy-api-nodejs / api / middleware / auth.js View on Github external
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();
                });
            });
        }
github meseven / node-egitimi-movie-api / routes / index.js View on Github external
}, (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
github nebulade / surfer / src / auth.js View on Github external
// 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 });
        });
    }
}
github liangfengbo / nodejs-koa-blog / app / models / admin.js View on Github external
set(val) {
      // 加密
      const salt = bcrypt.genSaltSync(10);
      // 生成加密密码
      const psw = bcrypt.hashSync(val, salt);
      this.setDataValue("password", psw);
    },
    allowNull: false,
github hemakshis / Basic-MERN-Stack-App / routes / usersRoute.js View on Github external
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' });
                });
            });
        });
    }
});
github spderosso / deja-vu / catalog / access / standardAuthentication / src / app.ts View on Github external
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);
          })
github liangfengbo / nodejs-koa-blog / app / dao / user.js View on Github external
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
    }
github spderosso / deja-vu / catalog / access / standardAuthentication / src / app.ts View on Github external
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
        });
      });
    }

bcryptjs

Optimized bcrypt in plain JavaScript with zero dependencies. Compatible to 'bcrypt'.

MIT
Latest version published 7 years ago

Package Health Score

70 / 100
Full package analysis