-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin_service.go
100 lines (76 loc) · 1.99 KB
/
admin_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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package sm
import (
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
)
type admservice struct {
repository AdminRepository
}
func NewAdminService(repository AdminRepository) AdminService {
return &admservice{
repository: repository,
}
}
func (this *admservice) Login(username, password string) (*AdminUser, error) {
user, err := this.repository.GetByUsername(username)
if err != nil {
return nil, err
} else if user == nil {
return nil, nil
}
if bcrypt.CompareHashAndPassword(
[]byte(user.Password),
[]byte(password)) != nil {
return nil, nil
}
return user, nil
}
func (this *admservice) CreateAdminUser(
username, password string) (*AdminUser, error) {
if len(username) < 1 {
return nil, ErrAdminNameTooShort
} else if len(password) < 5 {
return nil, ErrPasswordTooShort
}
hashed_password, err := bcrypt.GenerateFromPassword(
[]byte(password), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
log.Infof("Creating admin username=%s", username)
user := AdminUser{
Username: username,
Password: string(hashed_password),
}
err = this.repository.Insert(&user)
if err != nil {
return nil, err
}
return &user, nil
}
func (this *admservice) ChangePassword(
admin_id int64, old_password, new_password string) error {
log.Infof("change from %v", old_password)
if len(old_password) == 0 {
return ErrInvalidCredentials
} else if len(new_password) < 8 {
return ErrPasswordTooShort
}
user, err := this.repository.GetByID(admin_id)
if err != nil {
return err
} else if user == nil {
return ErrInvalidCredentials
}
log.Infof("Compare password %v %v", old_password, new_password)
if bcrypt.CompareHashAndPassword(
[]byte(user.Password),
[]byte(old_password)) != nil {
return ErrInvalidCredentials
}
new_hash, err := bcrypt.GenerateFromPassword(
[]byte(new_password), bcrypt.DefaultCost)
user.Password = string(new_hash)
log.Infof("change admin password username=%v", user.Username)
return this.repository.SavePassword(user)
}