How to use bcrypt - 10 common examples

To help you get started, we’ve selected a few bcrypt 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 dwyl / api / _bak / handlers / register.js View on Github external
bcrypt.genSalt(12, function(err, salt) { //encrypt the password
        // see: https://github.com/nelsonic/bcrypt
        bcrypt.hash(req.payload.password, salt, function(err, hash) {

          person.password = hash;

          ES.CREATE(person, function (res) {

            Hoek.assert(res.created, 'Person NOT Registered!'); // only if DB fails!
            // transfer any anonymous timers & session to the person
            console.log(' - - - - - - - - - - person')
            console.log(person);
            console.log(' - - - - - - - - - - email success')
            email(person, function(err, eres){
              console.log(eres);
              if(req.headers.authorization){
                // console.log("AUTH TOKEN:"+req.headers.authorization);
                return transfer(req, reply);
              }
github Kartikkh / We-Donate / models / Ngo / ngo.js View on Github external
module.exports.createNgo = (newNgo, callback)=>{
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newNgo.password, salt, function(err, hash) {
            // Store hash in your password DB.
            newNgo.password = hash
            // console.log(hash)
            newNgo.save(callback)
        });
    });
};
github niklaskorz / nkchat / server / src / schema / users / resolvers / Mutation.ts View on Github external
async register(
    root: any,
    { input }: { input: RegisterInput },
    ctx: Context,
  ): Promise> {
    let user;
    try {
      user = await UserModel.create({
        name: input.name,
        password: await bcrypt.hash(input.password, 10),
      });
    } catch (ex) {
      if (ex.code === 11000) {
        // WriteError of type KeyError
        throw new Error(`User ${input.name} already exists`);
      }
      throw new Error('User could not be created');
    }

    const session = await SessionModel.create({
      user: user.id,
    });
    ctx.state.session = session;
    ctx.state.viewer = user;

    return session;
github tatsuyaoiw / twitter / lib / model / user.js View on Github external
bcrypt.genSalt(12, function(err, salt) {
    if (err) {
      return fn(err);
    }
    user.salt = salt;
    bcrypt.hash(user.pass, salt, function(err, hash) {
      if (err) {
        return fn(err);
      }
      // Set hash so it'll be saved
      user.pass = hash;
      fn();
    });
  });
};
github veganaut / veganaut-backend / app / models / Person.js View on Github external
Person.hook('beforeSave', function(user) {
        // Only hash the password if it has been modified (or is new)
        if (user.changed('password')) {
            return bcrypt.hash(user.password, BCRYPT_WORK_FACTOR).then(function(hash) {
                // Override the cleartext password with the hashed one
                user.password = hash;
            });
        }
    });
github peterjoseph / Reeve / server / services / passport.js View on Github external
async function LocalStrategyLoadUser(workspaceURL, emailAddress, password) {
	// Load a client using a workspaceURL
	const client = await models().client.findOne({ where: { workspaceURL: workspaceURL, active: true } });

	// Load user based on provided values
	const user = await models().user.findOne({ where: { clientId: client.get("id"), emailAddress: emailAddress, active: true } });

	// Return false if client or user could not be loaded
	if (client === null || user === null) {
		return false;
	}

	// Validate the supplied user password
	const valid = await bcrypt.compare(password, user.get("password"));
	if (valid === false) {
		return false;
	}

	// Generate a unique session id to store in the redis db and compare with the active token
	const sessionId = await uuidv1();

	// Create the JSON Web Token for the User
	const token = await jwt.sign(
		{
			sessionId: sessionId,
			userId: user.get("id"),
			clientId: client.get("id"),
			workspaceURL: client.get("workspaceURL")
		},
		config.authentication.jwtSecret,
github nmaro / ooth / packages / ooth-local / src / index.ts View on Github external
throw new Error(__('verify.token_generated', null, locale));
      }

      const user = await ooth.getUserById(userId);
      if (!user) {
        throw new Error(__('verify.no_user', null, locale));
      }

      const strategyValues: StrategyValues = user[name] as StrategyValues;

      if (!strategyValues || !strategyValues.email) {
        // No email to verify, but let's not leak this information
        throw new Error(__('verify.no_email', null, locale));
      }

      if (!(await compare(token, strategyValues.verificationToken))) {
        throw new Error(__('verify.invalid_token', null, locale));
      }

      if (!strategyValues.verificationTokenExpiresAt) {
        throw new Error(__('verify.no_expiry', null, locale));
      }

      if (new Date() >= strategyValues.verificationTokenExpiresAt) {
        throw new Error(__('verify.expired_token', null, locale));
      }

      await ooth.updateUser(name, user._id, {
        verified: true,
        verificationToken: null,
      });
github utkarsh-pro / chatter / routes / api / login.js View on Github external
.then(user => {
            if (!user) {
                res.status(400).json({ error: 'User not found' });
            }
            // Check password
            bcrypt.compare(password, user.password)
                .then(isMatch => {
                    if (isMatch) {
                        // User matched
                        // Creating payload
                        const payload = {
                            id: user.id,
                            username: user.username
                        }
                        // Sign token
                        jwt.sign(payload, secret, { expiresIn: 3600 * 24 }, (err, token) => {
                            if (err) throw err;
                            res.json({
                                success: true,
                                token: 'Bearer ' + token
                            });
                        });
github mozilla / eyedee.me / lib / wsapi.js View on Github external
db.getAuth(normalizedUser, function(hash) {
      if (hash) {
        bcrypt.compare(req.body.pass, hash, function(err, r) {
          if (r) req.session.user = normalizedUser;
          res.writeHead(!r ? 401 : 200);
          res.end();
        });
      } else {
        // add user
        bcrypt.genSalt(BCRYPT_ROUNDS, function(err, salt) {
          if (err) return cb(err);
          bcrypt.hash(req.body.pass, salt, function(err, hash) {
            if (err) return cb(err);
            db.addUser(normalizedUser, hash, function(err) {
              if (!err) req.session.user = normalizedUser;
              res.writeHead(err ? 401 : 200);
              res.end();
            });
          });
github liamks / Drawbridge.js / lib / drawbridge.js View on Github external
res.redirect('/');
  }
  
  this.dashboard = new Dashboard( this, this.config.signups )
  this.waitlist = false;
  this.authentication = new Auth( this, this.config.authentication );

  if( this.config.signups ){
    this.signups( this.config.signups );
    this.waitlist = this.config.signups.waitlist;
  }

  if(this.config.superUser){
    var salt = bcrypt.genSaltSync(10),
        plainPassword = this.config.superUser.password,
        password = bcrypt.hashSync( this.config.superUser.password, salt );
    this.config.superUser.password = password;
    this.db.createSuperUser( this.config.superUser );
    this.config.superUser.password = plainPassword;
  }


  // critical
  this.dashboard.addAuth( this.authentication );
  

}