blob: dd34110bf8a4a49c08784041e5df15a5729932e2 [file] [log] [blame]
iomodo48c837e2021-02-19 01:17:07 +04001package model
2
3import (
iomodo48c837e2021-02-19 01:17:07 +04004 "regexp"
iomodo48c837e2021-02-19 01:17:07 +04005 "unicode"
6
7 "github.com/pkg/errors"
8)
9
10const (
iomodo838bd5c2021-03-21 15:37:03 +040011 userNameMaxLength = 64
12 userNameMinLength = 1
iomodo48c837e2021-02-19 01:17:07 +040013)
14
15// User contains the details about the user.
iomodo48c837e2021-02-19 01:17:07 +040016type User struct {
17 ID string `json:"id"`
18 CreateAt int64 `json:"create_at,omitempty"`
19 UpdateAt int64 `json:"update_at,omitempty"`
20 DeleteAt int64 `json:"delete_at"`
21 Username string `json:"username"`
22 Password string `json:"password,omitempty"`
iomodo48c837e2021-02-19 01:17:07 +040023 LastPasswordUpdate int64 `json:"last_password_update,omitempty"`
24}
25
26// IsValid validates the user and returns an error if it isn't configured
27// correctly.
28func (u *User) IsValid() error {
29 if !isValidID(u.ID) {
30 return invalidUserError("id", "")
31 }
32
33 if u.CreateAt == 0 {
34 return invalidUserError("create_at", u.ID)
35 }
36
37 if u.UpdateAt == 0 {
38 return invalidUserError("update_at", u.ID)
39 }
40
41 if !isValidUsername(u.Username) {
42 return invalidUserError("username", u.ID)
43 }
44
iomodo48c837e2021-02-19 01:17:07 +040045 return nil
46}
47
iomodo07334d22021-02-24 01:08:40 +040048func (u *User) Clone() *User {
49 user := *u
50 return &user
51}
52
iomodo48c837e2021-02-19 01:17:07 +040053func isValidID(value string) bool {
54 if len(value) != 26 {
55 return false
56 }
57
58 for _, r := range value {
59 if !unicode.IsLetter(r) && !unicode.IsNumber(r) {
60 return false
61 }
62 }
63
64 return true
65}
66
67func invalidUserError(fieldName string, userID string) error {
68 return errors.Errorf("Invalid User field: %s; id: %s", fieldName, userID)
69}
70
71func isValidUsername(s string) bool {
72 if len(s) < userNameMinLength || len(s) > userNameMaxLength {
73 return false
74 }
75
76 validUsernameChars := regexp.MustCompile(`^[a-z0-9\.\-_]+$`)
iomodo48c837e2021-02-19 01:17:07 +040077
iomodo838bd5c2021-03-21 15:37:03 +040078 return validUsernameChars.MatchString(s)
iomodo48c837e2021-02-19 01:17:07 +040079}