func (suite *HandlerUtilsTestSuite) TestChangePassword(c *C) {
	TRACE.Println("Running test: TestChangePassword")
	tx := dbConnection.Begin()

	testString := "UniqueTestUser123321"

	testCreateUserRequest := CreateUserRequest{Username: testString, LegalName: testString, Password: testString}
	status, err := CreateNewUser(testCreateUserRequest, tx)

	c.Assert(err, IsNil)
	c.Assert(status, Equals, 200)

	var testUser User

	tx.Where(&User{UserName: testString}).Find(&testUser)

	compareErr := bcrypt.CompareHashAndPassword([]byte(testUser.Password), []byte(testString))
	c.Assert(compareErr, IsNil)

	newPassword := "******"
	changePasswordStatus, changePasswordErr := ChangePassword(testString, newPassword, tx)
	c.Assert(changePasswordErr, IsNil)
	c.Assert(changePasswordStatus, Equals, 200)

	tx.Where(&User{UserName: testString}).Find(&testUser)

	compareErr = bcrypt.CompareHashAndPassword([]byte(testUser.Password), []byte(newPassword))
	c.Assert(compareErr, IsNil)

	changePasswordStatusUnregisteredUser, changePasswordErrUnregisteredUser := ChangePassword("unregisteredUser123321", newPassword, tx)
	c.Assert(changePasswordErrUnregisteredUser, Equals, UnregisteredUser)
	c.Assert(changePasswordStatusUnregisteredUser, Equals, 401)

	tx.Rollback()
}
Exemple #2
0
// Ensure the server can create a new user.
func TestServer_CreateUser(t *testing.T) {
	s := OpenServer(NewMessagingClient())
	defer s.Close()

	// Create a user.
	if err := s.CreateUser("susy", "pass", true); err != nil {
		t.Fatal(err)
	}
	s.Restart()

	// Verify that the user exists.
	if u := s.User("susy"); u == nil {
		t.Fatalf("user not found")
	} else if u.Name != "susy" {
		t.Fatalf("username mismatch: %v", u.Name)
	} else if !u.Admin {
		t.Fatalf("admin mismatch: %v", u.Admin)
	} else if bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte("pass")) != nil {
		t.Fatal("invalid password")
	}

	// Verify that the authenticated user exists.
	u, err := s.Authenticate("susy", "pass")
	if err != nil {
		t.Fatalf("error fetching authenticated user")
	} else if u.Name != "susy" {
		t.Fatalf("username mismatch: %v", u.Name)
	} else if !u.Admin {
		t.Fatalf("admin mismatch: %v", u.Admin)
	} else if bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte("pass")) != nil {
		t.Fatal("invalid password")
	}

}
func AuthAdmin(email, pass string, db *services.MySQL) (*Admin, *app.Msg, error) {
	const (
		ADMIN_AUTH_SQL = "SELECT id, name, password, status  FROM admin_users WHERE email=?"
	)
	var id, name, bcryptpass, status string

	if len(email) == 0 || len(pass) == 0 {
		return nil, app.NewErrMsg("The email or password is empty."), nil
	}

	rows, err := db.Query(ADMIN_AUTH_SQL, email)
	if err != nil {
		return nil, nil, err
	}
	defer rows.Close()

	if !rows.Next() {
		return nil, app.NewErrMsg("The email or password is incorrect."), nil
	}

	rows.Scan(&id, &name, &bcryptpass, &status)
	perr := bcrypt.CompareHashAndPassword([]byte(bcryptpass), []byte(pass))
	if perr != nil {
		return nil, app.NewErrMsg("The email or password is incorrect."), nil
	}
	if status == "inactive" {
		return nil, app.NewErrMsg("Please contact sysadmin"), nil
	}
	return &Admin{ID: id, Name: name, Email: email}, nil, nil
}
Exemple #4
0
func ValidateUserPassword(email, password string) (user structs.User, err error) {
	model.DB.Where("email = ?", email).First(&user)
	bytePassword := []byte(password)
	byteHash := []byte(user.HashedPassword)
	err = bcrypt.CompareHashAndPassword(byteHash, bytePassword)
	return user, err
}
Exemple #5
0
// Login a User
func (u *Users) Login(email string, password string) revel.Result {
	// Grab User with Email
	var user *models.User
	err := users.Find(map[string]string{"email": email}).One(&user)
	if err != nil {
		u.Flash.Error("Incorrect username or password.")
		return u.Redirect(routes.App.Index())
	}

	// Check Passwords
	bytes, _ := hex.DecodeString(user.HashedPassword)
	if bcrypt.CompareHashAndPassword(bytes, []byte(password)) != nil {
		u.Flash.Error("Incorrect username or password.")
		return u.Redirect(routes.App.Index())
	}

	// Only login if they are verified
	if user.Verified {
		u.Session["user"] = email
	} else {
		u.Flash.Error("You cannot login until you verify your email.")
	}

	return u.Redirect(routes.App.Index())
}
Exemple #6
0
func (u PasswordCredential) CheckPassword(password []byte) bool {
	if bcrypt.CompareHashAndPassword(u.PassHash, password) == nil {
		return true
	} else {
		return false
	}
}
Exemple #7
0
func (player *Player) CheckPassword(password string) bool {
	e := bcrypt.CompareHashAndPassword(bytes.NewBufferString(player.PasswordHash).Bytes(), bytes.NewBufferString(password).Bytes())
	if e == nil {
		return true
	}
	return false
}
Exemple #8
0
func ValidatePassword(pwh, pw []byte) bool {
	err := bcrypt.CompareHashAndPassword(pwh, pw)
	if err != nil {
		return false
	}
	return true
}
func (suite *HandlerUtilsTestSuite) TestCreateNewUserWithUniqueUsername(c *C) {
	TRACE.Println("Running test: TestCreateNewUserWithUniqueUsername")

	tx := dbConnection.Begin()

	testString := "UniqueTestUser123321"

	var testCreateUserRequest CreateUserRequest
	testCreateUserRequest.Username = testString
	testCreateUserRequest.LegalName = testString
	testCreateUserRequest.Password = testString

	status, err := CreateNewUser(testCreateUserRequest, tx)

	c.Check(err, IsNil)
	c.Assert(status, Equals, 200)

	var user User

	dbErr := tx.Where(&User{UserName: testString}).First(&user).Error
	c.Assert(dbErr, IsNil)
	comparePasswordErr := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(testString))
	c.Assert(comparePasswordErr, IsNil)

	var passwordRecord PasswordRecord
	tx.Where(&PasswordRecord{UserId: user.Id}).Find(&passwordRecord)
	c.Assert(passwordRecord.LoginCount, Equals, 0)

	tx.Rollback()
}
// Optimized wrapper around bcrypt.CompareHashAndPassword that caches successful results in
// memory to avoid the _very_ high overhead of calling bcrypt.
func compareHashAndPassword(hash []byte, password []byte) bool {
	// Actually we cache the SHA1 digest of the password to avoid keeping passwords in RAM.
	s := sha1.New()
	s.Write(password)
	digest := string(s.Sum(nil))
	key := digest + string(hash)

	cacheLock.Lock()
	_, valid := cachedHashes[key]
	cacheLock.Unlock()
	if valid {
		return true
	}

	// Cache missed; now we make the very slow (~100ms) bcrypt call:
	if err := bcrypt.CompareHashAndPassword(hash, password); err != nil {
		// Note: It's important to only cache successful matches, not failures.
		// Failure is supposed to be slow, to make online attacks impractical.
		return false
	}

	cacheLock.Lock()
	if len(cachedHashes) >= kMaxCacheSize {
		cachedHashes = map[string]struct{}{}
	}
	cachedHashes[key] = struct{}{}
	cacheLock.Unlock()
	return true
}
Exemple #11
0
/*
Endpoint: given email (or screen_name) + password,
return user_id and api_key
*/
func (c *Users) Authenticate() revel.Result {
	var authInfo UserAuthenticateInput
	data, err := ioutil.ReadAll(c.Request.Body)
	if err := json.Unmarshal([]byte(data), &authInfo); err != nil {
		return c.RenderError(err)
	}

	authInfo.Email = strings.ToLower(authInfo.Email)

	user, err := authInfo.Model()
	if err != nil {
		c.Response.Status = 401
		return c.RenderError(err)
	}

	out := UserAuthenticateOutput{user.Id, user.Api_key}

	if authInfo.Api_key == user.Api_key { // TODO: fix client-side auth so we don't have this hack
		return c.RenderJson(out)
	}

	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(authInfo.Password))

	if err != nil {
		c.Response.Status = 401
		return c.RenderText("")
	}

	return c.RenderJson(out)
}
Exemple #12
0
/*
Attempts to authenticate a user and returns a JWT if successful
*/
func (ud UserDomain) Authenticate(ar *AuthenticationRequest) (*string, error) {
	u := User{}

	err := ud.Collection.Find(bson.M{"username": ar.Username}).One(&u)

	if err != nil {
		return nil, err
	}

	// check password against hash
	err = bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(ar.Password))

	if err != nil {
		return nil, fmt.Errorf("Invalid password for %s", ar.Username)
	}

	token := jwt.New(jwt.GetSigningMethod("HS256"))

	token.Header["user_id"] = u.Uid
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["exp"] = time.Now().Add(time.Hour * 24).Unix()

	// TODO!  move this signing key to .env (and maybe use rsa key)
	tokenString, err := token.SignedString([]byte("dogfort"))

	if err != nil {
		return nil, err
	} else {
		return &tokenString, nil
	}
}
Exemple #13
0
func (c Account) LoginAccount(account, password string, remember bool) r.Result {

	var profile *models.Profile

	// If account is a valid email address, retrieve account by email
	// otherwise, retrieve account by username
	models.ValidateUserEmail(c.Validation, account).Key("account")

	if c.Validation.HasErrors() {
		c.Validation.Clear()
		profile = c.getProfileByUserName(account)
	} else {
		profile = c.getProfileByEmailAddress(account)
	}

	if profile != nil {
		err := bcrypt.CompareHashAndPassword(profile.User.HashedPassword, []byte(password))
		if err == nil {
			c.DoLogin(profile.User, remember)
			c.Flash.Success("Welcome back, " + profile.Name)
			return c.Redirect(routes.Profile.Show(profile.UserName))
		}
	}

	c.Flash.Error("Sign In failed.")
	return c.Redirect(routes.Account.Login())
}
Exemple #14
0
func equal(encryption, password []byte) bool {
	err := bcrypt.CompareHashAndPassword(encryption, password)
	if err != nil {
		return false
	}
	return true
}
Exemple #15
0
// Checks if the password matches the hash
//
// If the cost of the given hash is below the cost we currently use, the 2nd return value will contain a new and stronger hash.
// If the 2nd return value is present, you must update the hash for the password to it or you're missing out on the security benefits and wasting CPU cycles.
// If the given hash is already strong enough, the 2nd argument will be nil.
func (self *Hasher) Validate(password []byte, hash []byte) (bool, []byte, error) {
	err := bcrypt.CompareHashAndPassword(hash, password)

	if err != nil {
		// password and hash do not match
		return false, nil, nil
	} else {
		// password matches the hash

		costOfHash, err := bcrypt.Cost(hash)

		if err != nil || costOfHash < self.currentCost {
			// if unable to determine the cost (err != nil), treat it the same as an outdated hash

			newHash, err := self.Hash(password)

			if err != nil {
				return true, nil, err
			} else {
				return true, newHash, nil
			}
		} else {
			// the hash is valid and is sufficiently strong
			return true, nil, nil
		}
	}
}
Exemple #16
0
func (s *S) TestUserCheckPasswordUsesBcrypt(c *gocheck.C) {
	u := auth.User{Email: "paradisum", Password: "******"}
	err := hashPassword(&u)
	c.Assert(err, gocheck.IsNil)
	err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte("abcd1234"))
	c.Assert(err, gocheck.IsNil)
}
Exemple #17
0
func dbauthenticate(username, password string) error {
	var passhash string

	stmt, err := db.Prepare(`
	select passhash from user where username = ?;
	`)

	if err != nil {
		panic(err)
	}

	stmt.Exec(username)
	if !sql.Must(stmt.Next()) {
		return errors.New("No such user.")
	}

	err = stmt.Scan(&passhash)
	if err != nil {
		panic(err)
	}

	err = bcrypt.CompareHashAndPassword([]byte(passhash), []byte(password))

	return err
}
Exemple #18
0
func (u *User) isPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	if err != nil {
		return false
	}
	return true
}
Exemple #19
0
func UserLogin(r *http.Request, db *sql.DB, s sessions.Session, rw http.ResponseWriter) (int, string) {
	var id string
	var pass string

	email, password := r.FormValue("email"), r.FormValue("password")
	err := db.QueryRow("select id, password from appuser where email=$1", email).Scan(&id, &pass)

	if err != nil || bcrypt.CompareHashAndPassword([]byte(pass), []byte(password)) != nil {
		//return 401, "Not Authorized. Buuuurn!"
		http.Redirect(rw, r, "/wrong", http.StatusFound)
	}

	//set the user id in the session
	s.Set("userId", id)

	//return user
	if returnUrl, ok := s.Get("returnUrl").(string); ok {
		s.Delete("returnUrl")
		http.Redirect(rw, r, returnUrl, http.StatusFound)
	} else {
		http.Redirect(rw, r, "/", http.StatusFound)
	}

	return 200, "User id is " + id
}
Exemple #20
0
func (user *User) CheckPassword(password string) bool {
	if user.Password == "" {
		return false
	}
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	return err == nil
}
Exemple #21
0
func login(a *appContext, w http.ResponseWriter, r *http.Request) (int, error) {
	user := r.FormValue("username")
	pass := r.FormValue("password")

	if len(user) == 0 || len(pass) == 0 {
		return http.StatusUnauthorized, errors.New("Please supply non-empty username and password")
	} else {
		userHash, err := getUserHash(a.db, user)
		if err != nil {
			return http.StatusUnauthorized, err
		}
		err = bcrypt.CompareHashAndPassword([]byte(userHash), []byte(pass))
		if err == nil {
			session, err := a.store.Get(r, "user")
			if err != nil {
				return http.StatusInternalServerError, err
			}

			var userId int
			userId, err = getUserId(a.db, user)
			if err != nil {
				return http.StatusInternalServerError, err
			}
			session.Values["id"] = userId
			session.Save(r, w)

			http.Redirect(w, r, "/", 302)

		} else {
			return http.StatusUnauthorized, err
		}
	}

	return http.StatusOK, nil
}
Exemple #22
0
func CompareSecret(encrypted_secret, plain_secret []byte) bool {
	if err := bcrypt.CompareHashAndPassword(encrypted_secret, plain_secret); err != nil {
		return false
	}

	return true
}
Exemple #23
0
func authHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	data := r.Form
	user := data.Get("user")
	pass := data.Get("password")

	hashed_pass, err := dbmap.SelectStr("select Password from Nurse where Nurse.Name=?", user)
	if err != nil {
		panic(err)
	}

	valid_login := bcrypt.CompareHashAndPassword([]byte(hashed_pass), []byte(pass))

	if valid_login != nil {
		fmt.Fprintf(w, "Invalid Login")
	} else {
		key, err := dbmap.SelectStr("select Key from Nurse where Nurse.Name=?", user)
		if err != nil {
			panic(err)
		} else {
			if key == "" {
				key = genKey(user)
				dbmap.Exec("update Nurse set Key=? where Name=?", key, user)
				fmt.Fprintf(w, key)
			} else {
				fmt.Fprintf(w, key)
			}

		}
	}
}
Exemple #24
0
// Login logs a user in. They will be redirected to dest or to the last
// location an authorization redirect was triggered (if found) on success. A
// message will be added to the session on failure with the reason.
func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string, dest string) error {
	session, _ := a.cookiejar.Get(req, "auth")
	if session.Values["username"] != nil {
		return errors.New("already authenticated")
	}
	if user, ok := a.backend.User(u); ok {
		verify := bcrypt.CompareHashAndPassword(user.Hash, []byte(u+p))
		if verify != nil {
			a.addMessage(rw, req, "Invalid username or password.")
			return errors.New("password doesn't match")
		}
	} else {
		a.addMessage(rw, req, "Invalid username or password.")
		return errors.New("user not found")
	}
	session.Values["username"] = u
	session.Save(req, rw)

	redirectSession, _ := a.cookiejar.Get(req, "redirects")
	if flashes := redirectSession.Flashes(); len(flashes) > 0 {
		dest = flashes[0].(string)
	}
	http.Redirect(rw, req, dest, http.StatusSeeOther)
	return nil
}
Exemple #25
0
// passwordEqual returns true iff the hash matches the password.
func passwordEqual(hash, password string) bool {
	if err := bcrypt.CompareHashAndPassword([]byte(hash),
		[]byte(password)); err != nil {
		return false
	}
	return true
}
Exemple #26
0
func Login(conn *db.Connection) http.Handler {
	return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		var rU models.RequestUser
		err := json.NewDecoder(req.Body).Decode(&rU)
		if err != nil {
			renderJSON(res, 400, Error{"Error parsing JSON"})
			return
		}

		var user models.User
		err = conn.C("users").Find(bson.M{"email": rU.Email}).One(&user)
		if err != nil {
			renderJSON(res, 401, Error{"User not found"})
			return
		}

		err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(rU.Password))
		if err != nil {
			renderJSON(res, 401, Error{"Invalid password"})
			return
		}

		renderJSON(res, 200, user)
	})
}
Exemple #27
0
func Unequal(current string, request string) bool {
	a := []byte(current)
	b := []byte(request)

	err := bcrypt.CompareHashAndPassword(a, b)

	return err != nil
}
Exemple #28
0
// checkPass verifies that the given user exists and that the password matches.
func checkPass(username, pass string, ip net.Addr) (user *world.User, err error) {
	if world.FindPlayer(username) != nil {
		return nil, ErrDupe
	}
	hash, err := db.Password(username)
	if err != nil {
		return nil, err
	}

	passb := []byte(pass)
	if hash == nil {
		// User does not exist. Fake out the time we would otherwise take to run
		// the hash.  Ignore the error, we really only care about sucking up
		// some CPU cycles here.
		_ = bcrypt.CompareHashAndPassword(fakehash, passb)
		return nil, ErrAuth
	}

	err = bcrypt.CompareHashAndPassword(hash, passb)
	if err == bcrypt.ErrMismatchedHashAndPassword {
		return nil, ErrAuth
	}
	if err != nil {
		return nil, err
	}

	cost, err := bcrypt.Cost(hash)
	if err != nil {
		return nil, err
	}

	// Handle bcrypt cost change, rehash with new cost.
	if cost != bcryptCost {
		hash, err = bcrypt.GenerateFromPassword(passb, bcryptCost)
		if err != nil {
			return nil, err
		}
	}

	// Login successful, update info.
	if err := db.SaveUser(username, ip, hash); err != nil {
		return nil, err
	}

	return &world.User{Username: username, IP: ip}, nil
}
Exemple #29
0
func (this *User) ValidatePassword(v *r.Validation, password string) {
	bin := []byte(_APPSECRET + password + this.Username)
	hbin, _ := base64.StdEncoding.DecodeString(this.Password)
	err := bcrypt.CompareHashAndPassword(hbin, bin)
	if err != nil {
		v.Error("密码不匹配")
	}
}
Exemple #30
0
// 重置密码要用的
func (u *User) CheckPWD(raw_pwd string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(u.Email+raw_pwd))
	if err != nil {
		// 密码不对
		return false
	}
	return true
}