This repository has been archived by the owner on Oct 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
94 lines (75 loc) · 1.6 KB
/
user.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
package auth
import (
"errors"
"fmt"
"golang.org/x/crypto/bcrypt"
"gopkg.in/kwiscale/orm.v0"
)
const (
minlength = 3
minpassword = 5
)
type User struct {
orm.Model
Login string
Password string
}
func (u *User) check() error {
if len(u.Login) < minlength {
return errors.New(fmt.Sprintf("Login size should be > %d", minlength))
}
if len(u.Password) < minpassword {
return errors.New(fmt.Sprintf("Password length too short, should be length > %d", minpassword))
}
return nil
}
func (u *User) encryptPasswd() error {
p, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err == nil {
u.Password = string(p)
}
return err
}
func (u *User) Create() []error {
err := u.check()
if err != nil {
return []error{err}
}
err = u.encryptPasswd()
if err != nil {
return []error{err}
}
d := orm.Get()
defer d.Close()
d.FirstOrCreate(u, map[string]string{"login": u.Login})
return d.GetErrors()
}
func (u *User) Save() error {
err := u.check()
if err != nil {
return err
}
db := orm.Get()
defer db.Close()
old := User{}
db.Find(&old, map[string]uint{"id": u.ID})
if u.Login != old.Login {
return errors.New("Login cannot be changed")
}
if u.Password != "" && u.Password != old.Password {
u.encryptPasswd()
}
db.Save(u)
return nil
}
func (u *User) Delete() []error {
d := orm.Get()
defer d.Close()
return d.Delete(u).GetErrors()
}
func (u *User) Signin(login, pass string) bool {
db := orm.Get()
defer db.Close()
db.Find(u, map[string]string{"login": login})
return bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(pass)) == nil
}