-
Notifications
You must be signed in to change notification settings - Fork 3
/
service.go
59 lines (49 loc) · 1.53 KB
/
service.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Package password provides password management through bcrypt.
package password
import (
"fmt"
"golang.org/x/crypto/bcrypt"
auth "github.com/fmitra/authenticator"
)
// Password is a credential validator for password authentication.
type Password struct {
// cost is the bcrypt hash repetition. Higher cost results
// in slower computations.
cost int
// minLength is the minimum length of a password.
minLength int
// maxLength is the maximum length of a password.
// We enforce a maximum length to mitigate DOS attacks.
maxLength int
}
// Hash hashes a password for storage.
func (p *Password) Hash(password string) ([]byte, error) {
// bcrypt will manage its own salt
hash, err := bcrypt.GenerateFromPassword([]byte(password), p.cost)
if err != nil {
return []byte(""), err
}
return hash, nil
}
// Validate validates if a submitted password is valid for a
// stored password hash.
func (p *Password) Validate(user *auth.User, password string) error {
bPasswdHash := []byte(user.Password)
bPasswd := []byte(password)
return bcrypt.CompareHashAndPassword(bPasswdHash, bPasswd)
}
// OKForUser tells us if a password meets minimum requirements to
// be set for any users.
func (p *Password) OKForUser(password string) error {
if len(password) < p.minLength {
return auth.ErrInvalidField(
fmt.Sprintf("password must be at least %v characters long", p.minLength),
)
}
if len(password) > p.maxLength {
return auth.ErrInvalidField(
fmt.Sprintf("password cannot be longer than %v characters", p.maxLength),
)
}
return nil
}