-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbcrypt_auth.go
36 lines (30 loc) · 872 Bytes
/
bcrypt_auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package users
import (
"golang.org/x/crypto/bcrypt"
)
type bcryptAuth struct {
repo Repository
}
// NewBcryptAuth returns Authenticator using bcrypt
// algorithm in Authenticate method to compare provided
// password with stored hash.
func newBcryptAuth(repo Repository) Authenticator {
return &bcryptAuth{repo}
}
// Authenticate implements Authenticator interface.
func (b *bcryptAuth) Authenticate(username, password string) (bool, error) {
u, err := b.repo.Get(username)
if err != nil {
return false, err
}
err = bcrypt.CompareHashAndPassword([]byte(u.Secret), []byte(password))
if err != nil {
err = ErrIncorrectPassword
}
return (err == nil), err
}
// BcryptHash return bcrypt hash of provided password.
func BcryptHash(password string) string {
hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(hash)
}