-
Notifications
You must be signed in to change notification settings - Fork 1
/
user.go
70 lines (62 loc) · 1.84 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
package user
import (
"errors"
"github.com/asaskevich/govalidator"
"github.com/gofrs/uuid"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
// Following are available user roles.
const (
// Black is an administrator role. Black Team - an Administrator team responsible for Infrastructure
Black = "black"
// Blue is a competitor role.
Blue = "blue"
// Red is a role of Hackers.
Red = "red"
Anonymous = ""
)
type User struct {
ID uuid.UUID `json:"id,omitempty" gorm:"type:uuid;primary_key;"`
Username string `json:"username" gorm:"unique;not null;default:null"`
PasswordHash string `json:"password_hash" gorm:"not null;default:null"`
TeamID uuid.UUID `json:"team_id,omitempty" gorm:"type:uuid"`
Role string `json:"role" gorm:"default:'blue'"`
}
var ErrNameMustBeAlphanumeric = errors.New("name must be alphanumeric")
var ErrInvalidRoleSpecified = errors.New("incorrect role specified")
// BeforeSave ensures that user is part of either Black, Blue, or Red roles. It also ensures that username is alphanumeric
func (u *User) BeforeSave(_ *gorm.DB) (err error) {
if u.Username != "" && !govalidator.IsAlphanumeric(u.Username) {
return ErrNameMustBeAlphanumeric
}
if u.Role != "" {
var validStatus bool
for _, item := range []string{Black, Blue, Red} {
if item == u.Role {
validStatus = true
}
}
if !validStatus {
return ErrInvalidRoleSpecified
}
return nil
}
return nil
}
// BeforeCreate ensures UUID is set.
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
if u.ID == uuid.Nil {
uid, err := uuid.NewV4()
if err != nil {
return err
}
u.ID = uid
}
return nil
}
// IsCorrectPassword compares password to the hash
func (u *User) IsCorrectPassword(password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password))
return err == nil
}