Exemple #1
0
    User.findOne({ username: req.body.username }).then(user => {
      if (user) {
        errors.username = '******';
        return res.status(400).json({ errors });
        // checks if user is student, and prevents request if it is.
      } else {
        const newUser = new User({
          username: req.body.username,
          password: req.body.password,
          accountType: 2,
          owner: req.user.id
        });

        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser
              .save()
              .then(user => res.json(user))
              .catch(err => console.log(err));
          });
        });
      }
    });
Exemple #2
0
      .then((user) => {
        console.log('user: '******'User has been created 🍜'
                  });
                });
            });
          });
        } else {
          // email is in user
          next(new Error('Email is in use'));
        }
      });
Exemple #3
0
schema.pre('save', function(done) {
	var user = this;

	// Hash email for later
	if (user.email) {
		user.emailHash = md5(user.email);
	}

	if (user.isModified('githubAccessToken') || !user.githubStateToken) {
		bcrypt.genSalt(SALT_WORK_FACTOR, function(error, salt) {
			if (error) {
				return done(error);
			}

			// hash the password using our new salt
			bcrypt.hash(Math.random() + '', salt, function(error, hash) {
				if (error) {
					return done(error);
				}

				user.githubStateToken = hash;
				done();
			});
		});
	} else {
		done();
	}
});
Exemple #4
0
 .then(function(found) {
   if (found) {
     console.log('Sorry, that username is already in the database!');
   } else {
     bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
       if (err) {
         console.log('Could not create salt', err);
         res.status(404).send(err);
       } else {
         bcrypt.hash(password, salt, function(err, hashedPassword){
           if (err) {
             console.log('Could not hash password', err);
             res.status(404).send(err);
           } else {
             Users.create({
               username: username,
               password: hashedPassword,
               phoneNumber: phoneNumber
             })
             .then(function(user) {
               res.status(201).send({id : user.attributes.id, success: true});
             })
             .catch(function(err) {
               console.error('Error signing up new user', err);
               res.status(404).send(err);
             });
           }
         });
       }
     });
   }
 });
Exemple #5
0
const passHash = (userPassword, callback) => {
    bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(userPassword, salt, (err, hash) => {
            callback(err, hash);
        });
    });
};
Exemple #6
0
  .pre('save', function(next) {
    const user = this;

    // Don't do stuff if nothing changed
    if (!user.isModified('password')) {
      logger.log('info', 'password not modified');
      return next();
    }

    // Hash the password
    bcrypt.genSalt(10, function(err, salt) {
      if (err) {
        logger.log('error', err);
        return next(err);
      }

      bcrypt.hash(user.password, salt, function(err, hash) {
        if (err) {
          logger.log('error', err);
          return next(err);
        }

        // Replace the user's password with the hash
        user.password = hash;

        next();
      });
    });
  })
 User.findOne({ email: req.body.email }).then(user => {
   if (user) {
     return res.status(400).json({ email: "already exists" });
   } else {
     const avatar = gravatar.url(req.body.email, {
       s: "200", //size
       r: "pg", //rating
       d: "mm" //default
     });
     const newUser = new User({
       name: req.body.name,
       email: req.body.email,
       avatar: avatar,
       password: req.body.password
     });
     bcrypt.genSalt(10, (err, salt) => {
       bcrypt.hash(newUser.password, salt, (err, hash) => {
         if (err) throw err;
         newUser.password = hash;
         newUser
           .save()
           .then(user => res.json(user))
           .catch(err => console.log(err));
       });
     });
   }
 });
Exemple #8
0
function userSignup (req, res){
	bcrypt.genSalt(11, function(error, salt){
        bcrypt.hash(req.body.password, salt, function(hashError, hash){
            var newUser = new User({
                first_name : req.body.first_name,
                last_name : req.body.last_name,
                email : req.body.email,
                username: req.body.username,
                password: hash,
            });
            newUser.save(function(saveErr, user){
                if ( saveErr ) { res.send({ err:saveErr }) }
                else {
                    req.login(user, function(loginErr){
                        if ( loginErr ) { res.send({ err:loginErr }) }
                        else { res.send({success: 'success'}) }
                    })

                    // req.user is always the logged in user
                }
            })

        })
    })
}
 doSignup: function(req, res) {
   if(req.body.password != req.body.confirm_password) {
     FlashService.error(req, "Password and confirm don't match");
     res.redirect("/auth/signup");
   } else {
     bcrypt.genSalt(10, function(err, salt) {
       bcrypt.hash(req.body.password, salt, function(err, hash) {
         delete req.body.password;
         delete req.body.confirm_password;
         req.body.passwordHash = hash;
         req.body.authToken = uuid.v4();
         User.create(req.body, function (err, created) {
           if (err) {
             FlashService.error(req, JSON.stringify(err));
             res.redirect("/auth/signup");
           } else {
             req.session.authenticated = true;
             req.session.user = created;
             res.redirect("/");
           }
         });
       });
     });
   }
 },
app.post('/create-an-account', function(req, res){
    console.log(req.body)
    bcrypt.genSalt(11, function(error, salt){
            console.log('salt')

        bcrypt.hash(req.body.password, salt, function(hashError, hash){
            console.log('hash')

            var newUser = new User({
                name: req.body.name,
                email: req.body.email,
                password: hash,
            });
            console.log('made a user')
            newUser.save(function(saveErr, user){
                console.log('saaved a user')
                if ( saveErr ) { res.send({ err:saveErr }) }
                else {
                    req.login(user, function(loginErr){
                        if ( loginErr ) { res.send({ err:loginErr }) }
                        else { res.send({success: 'success'}) }
                    })
                }
            })

        })
    })
})
Exemple #11
0
 function (req, res) {
     // Get the validation result whenever you want; see the Validation Result API for all options!
     const errors = validationResult(req);
     if (!errors.isEmpty()) {
         res.render('register', {
             errors: errors.mapped()
         });
     } else {
         let user = new User();
         user.name = req.body.name;
         user.email = req.body.email;
         user.username = req.body.username;
         user.password = req.body.password;
         bcrypt.genSalt(10, function (err, salt) {
             bcrypt.hash(user.password, salt, function (err, hash) {
                 if (err) {
                     console.log(err);
                 }
                 user.password = hash;
                 user.save(function (err) {
                     if (err) {
                         console.log(err);
                         return;
                     } else {
                         req.flash('success', 'You are now registered and can log in');
                         res.redirect('/users/login');
                     }
                 });
             });
         });
     }
 }
  upsert: function(req, res) {
    // console.log('controllers/userController.js', req.body)
    if (req.params.id) {
      User.update({ _id: req.params.id }, req.body, function(err, updated) {
        if (err) {
          return res.send(err)
        }
      })
    } else {
      bcrypt.genSalt(11, function(error, salt) {
        bcrypt.hash(req.body.password, salt, function(hashError, hash) {
          req.body.password = hash
          var newUser = new User(req.body);
          newUser.save(function(saveErr, user) {
            if (saveErr) { res.send({ err: saveErr }) } else {
              req.login(user, function(loginErr) {
                if (loginErr) { res.send({ err: loginErr }) } else { res.send({ success: 'success', user: user }) }
              })
            }
          })

        })
      })
    }
  },
Exemple #13
0
    User.findOne({ email: email }).then(user => {
      if (user) {
        errors.push({ msg: 'Email already exists' });
        res.render('register', {
          errors,
          name,
          email,
          password,
          password2
        });
      } else {
        const newUser = new User({
          name,
          email,
          password
        });

        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser
              .save()
              .then(user => {
                req.flash(
                  'success_msg',
                  'You are now registered and can log in'
                );
                res.redirect('/users/login');
              })
              .catch(err => console.log(err));
          });
        });
      }
    });
Exemple #14
0
 return new Promise((resolve, reject) => {
   /**
    * CASE: add model, hash password
    * CASE: update model, hash password
    *
    * Important:
    *   - Password hashing happens when we import a database
    *   - we do some pre-validation checks, because onValidate is called AFTER onSaving
    */
   if (self.isNew() || self.hasChanged('password')) {
     self.set('password', String(self.get('password')));
     bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
       // hash the password along with our new salt
       if (err) {
         reject(err);
       }
       bcrypt.hash(self.get('password'), salt, (err2, hash) => {
         if (err2) {
           reject(err2);
         }
         // override the cleartext password with the hashed one
         self.set('password', hash);
         resolve(hash);
       });
     });
   }
 });
	connection.query(queryString, function(err, users) {
			if (err) throw err;

			if (users.length > 0){
				// console.log(users)
				res.write('<h3>We already have an email or username for this account. Try a different e-mail </h3>');
			}else{

				bcrypt.genSalt(10, function(err, salt) {
						bcrypt.hash(req.body.password, salt, function(err, hash) {
              user.create(['username', 'email', 'password_hash', 'photo'], [req.body.username, req.body.email, hash, req.body.photo], function(data){
                req.session.logged_in = true;
                req.session.user_id = user.id;
                req.session.user_email = user.email;
                console.log('usercreated');

                res.redirect('/');
                res.write('<h3>User created! Sign in below to start playing </h3>');
            	});

						});
				});

			}
	});
 db.once('open', function() {
   console.log("Db is open");
   var obj = {
     username: req.body.username,
     password: req.body.password,
   }
   if(obj){
       bcrypt.genSalt(saltRounds, function(err, salt) {
         bcrypt.hash(obj.password, salt, function(err, hash) {
             if(err){
               console.error(err);
             } else {
                 var Signup = db.model('Creditials',AuthenticateSchema);
                 obj.password = hash;
                 new Signup(obj).save(function (err,result) {
                   if (err) {
                     console.error(err);
                     res.sendStatus(HttpStatus.INTERNAL_SERVER_ERROR);
                     mongoose.disconnect();
                   } else if(result) {
                     console.log(result);
                     res.sendStatus(HttpStatus.CREATED);
                     mongoose.disconnect();
                   }
                 });
             }
         });
       });
     }
 });
Exemple #17
0
UserSchema.pre('save', function(next) { // don't use an arrow function here, we need the scope!
    var user = this; // this is why we can't use an arrow function  here, again we need the scope

    // only hash the password if it has been modified (for updating users)
    if( !user.isModified('password') ) {
        return next();
    }
    // generate a salt value to encrypt our password
    bcrypt.genSalt(SALTY_BITS, (saltErr, salt) => { // used to guarentee uniqueness
        if(saltErr) {
            return next(saltErr);
        }
        console.info('SALT generated!'.yellow, salt);

        // now let's hash this bad boy!
        bcrypt.hash(user.password, salt, (hashErr, hashedPassword) => {
            if( hashErr ) {
                return next(hashErr);
            }
            // over-ride the plain text password with the hashed one
            user.password = hashedPassword;
            next();
        });
    });
});
Exemple #18
0
        generatePassword: function(password, next) {
          var SALT_WORK_FACTOR = this.options.SALT_WORK_FACTOR;

          return bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
            return bcrypt.hash(password, salt, next);
          });
        },
Exemple #19
0
router.post('/submit_password_change', function(req, res){
    var query = {email: req.body.email, reset_hash: req.body.hash};
    var hash_val = sha1(Math.floor(Date.now() + Math.random() * 1000));
    
    //Make sure password is typed twice
    if (req.body.password == req.body.password2 && req.body.password != "")
    {
    //Encrypt password
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(req.body.password, salt, function(err, hash) {
            //Update password
            User.update(query, {password: hash, reset_hash: hash_val}, function(err, writeObj){
            if (err) throw err; 
            if (writeObj.nModified) //sucess
            {
                req.flash('success_msg', 'Password changed!');
                res.redirect('/password_reset');
            }
            else //fail
            {
                req.flash('error_msg', 'Choose a different password.');
                res.redirect('/password_reset');
            }
            });
        });
    });
    }
    else
        {
            
            res.render('change_password', {email: req.body.email, hash: req.body.hash, err: "Passwords must be the same!"});
        }
        
    
});
Exemple #20
0
 new_pwd : function (req, res) {
     var pwd = req.param('password');
     if (req.session.tmp_email == undefined || pwd == undefined || pwd.length < 8) {
         req.session.msg = 'The password you tried to set is not valid (min 8 chars)';
         return res.redirect('/auth/login');
     }
     bcrypt.genSalt(10, function(err, salt) {
         bcrypt.hash(pwd, salt, function (err, hash) {
             if (err) {
                 sails.log.debug(err);
                 req.session.msg = 'Mmmmh pour une raison obscure, le hashage du mdp à echoué';
                 return res.view('/auth/login');
             }
             else {
                 pwd = hash;
                 User.update({email : req.session.tmp_email }, {pwd: pwd}).exec(function (err, result){
                     if(err) {
                         sails.log.debug(err);
                         req.session.msg = 'The password is not valid';
                         return res.view('/auth/login');
                     } else {
                         req.session.tmp_email = null;
                         req.session.msg = 'Update successfull';
                         res.redirect('/auth/login');
                     }
                 });
             }
         })
     });
 },
myHasher = function(password, tempUserData, insertTempUser, callback) {
  bcrypt.genSalt(8, function(err, salt) {
    bcrypt.hash(password, salt, function(err, hash) {
      return insertTempUser(hash, tempUserData, callback);
    });
  });
};
  }).then(function(users) {

    if(users.length > 0) {
      res.send("We already have an account with this username");
    } else {

      bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(req.body.password, salt, function(err, hash) {

          models.User.create({
            username: req.body.username,
            email: req.body.email,
            password_hash: hash,
            phone: req.body.phone,
            countrycode: req.body.countrycode
          }).then(function(user) {

            req.session.logged_in = true;
            req.session.user_id = user.id;
            req.session.user_email = user.email;
            req.session.username = user.username;
            res.redirect('/users/sign-in');
          });
        });
      });
    }
  });
userSchema.pre('save', function(next){

  // First, check to see if the password has been modified. If not, just move on.
  if(!this.isModified('password')) return next();

  // Store access to "this", which represents the current user document
  var user = this;

  // Generate an encryption "salt." This is a special way of increasing the
  // encryption power by wrapping the given string in a secret string. Something
  // like "secretpasswordsecret" and then encrypting that result.
  bcrypt.genSalt(10, function(err, salt){

    // If there was an error, allow execution to move to the next middleware
    if(err) return next(err);

    // If we are successful, use the salt to run the encryption on the given password
    bcrypt.hash(user.password, salt, function(err, hash){

      // If there was an error, allow execution to move to the next middleware
      if(err) return next(err);

      // If the encryption succeeded, then replace the un-encrypted password
      // in the given document with the newly encrypted one.
      user.password = hash;

      // Allow execution to move to the next middleware
      return next();
    });
  });
});
var hashPassword = function(password, id) {
	bcrypt.genSalt(10, function(err, salt) {
		bcrypt.hash(password, salt, function(err, hash) {
			users[id].password = hash;
		});
	});
};
Exemple #25
0
ClientSchema.pre('save', function(callback) {

    const client = this;
    const idModified = client.isModified('id');
    const secretModified = client.isModified('secret');

    if (idModified || secretModified) {
        client.id = idModified
            ? md5(client.id)
            : client.id ;
        if(secretModified){
            bcrypt.genSalt(5, (err, salt) => {
                if (err) {
                    log('Salting the secret failed.', true, err);
                    callback(err);
                }
                else {
                    bcrypt.hash(client.secret, salt, (err, hash) => {
                        if (err) {
                            log('Hashing the secret failed.', true, err);
                            callback(err)
                        }
                        else {
                            client.secret = hash;
                            callback();
                        }
                    });
                }
            });
        }
        else {
            callback();
        }
    }
});
Exemple #26
0
    return new Promise(function (resolve, reject) {

        bcrypt.genSalt(10, function(err, salt) {
            bcrypt.hash( adminPassword, salt, function (err, hash) {

                var Account = mongoose.model('Account');

                //preden shranimo novega admina, preverimo, ce obstaja ze email: bisadmin
                Account.findOne( { email:adminEmail }, function (err, doc) {

                    //ce dokument se ni narejen, sledece:
                    if(!doc){

                        var account = new Account({
                            role        : 'admin',
                            email       : adminEmail,
                            password    : hash
                        });

                        account.save(function (err) {
                            if(err){
                                reject(err);
                            }else{
                                resolve();
                            }
                        }); 
                    }else{
                        resolve();
                    }
                });
            });
        });
    });
Exemple #27
0
var hashPassword = function (password, cb) {
	bcrypt.genSalt(10, function (err, salt) {
		bcrypt.hash(password, salt, function (err, hash) {
			cb({hash: hash, salt: salt});
		});
	});
};
Exemple #28
0
exports.crypt = function(string, callback){
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(string, salt, function(err, hash) {
            callback(hash);
        });
    });
}
Exemple #29
0
schema.pre('save', function(done) {
	var user = this;

	// only hash the password if it has been modified (or is new)
	if (!user.isModified('password')) {
		return done();
	}

	// generate a salt
	bcrypt.genSalt(SALT_WORK_FACTOR, function(error, salt) {
		if (error) {
			return done(error);
		}

		// hash the password using our new salt
		bcrypt.hash(user.password, salt, function(error, hash) {
			if (error) {
				return done(error);
			}

			// override the cleartext password with the hashed one
			user.password = hash;
			done();
		});
	});
});
  }).then(function(users) {

		if (users.length > 0){
			console.log(users)
			res.send('we already have an email or username for this account')
		}else{

			bcrypt.genSalt(10, function(err, salt) {
					bcrypt.hash(req.body.password, salt, function(err, hash) {
						models.User.create({
							email: req.body.email,
							password_hash: hash
						}).then(function(user){

							req.session.logged_in = true;
							req.session.user_id = user.id;
							req.session.user_email = user.email;

							res.redirect('/people')
						});
					});
			});

		}
	});