blob: 156f4faa7a3f5e160d9cce650171c97eef1ab04c [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 (
11 userNameMaxLength = 64
12 userNameMinLength = 1
13 userEmailMaxLength = 128
14)
15
16// User contains the details about the user.
iomodo48c837e2021-02-19 01:17:07 +040017type User struct {
18 ID string `json:"id"`
19 CreateAt int64 `json:"create_at,omitempty"`
20 UpdateAt int64 `json:"update_at,omitempty"`
21 DeleteAt int64 `json:"delete_at"`
22 Username string `json:"username"`
23 Password string `json:"password,omitempty"`
iomodo48c837e2021-02-19 01:17:07 +040024 LastPasswordUpdate int64 `json:"last_password_update,omitempty"`
25}
26
27// IsValid validates the user and returns an error if it isn't configured
28// correctly.
29func (u *User) IsValid() error {
30 if !isValidID(u.ID) {
31 return invalidUserError("id", "")
32 }
33
34 if u.CreateAt == 0 {
35 return invalidUserError("create_at", u.ID)
36 }
37
38 if u.UpdateAt == 0 {
39 return invalidUserError("update_at", u.ID)
40 }
41
42 if !isValidUsername(u.Username) {
43 return invalidUserError("username", u.ID)
44 }
45
iomodo48c837e2021-02-19 01:17:07 +040046 return nil
47}
48
iomodo07334d22021-02-24 01:08:40 +040049func (u *User) Clone() *User {
50 user := *u
51 return &user
52}
53
iomodo48c837e2021-02-19 01:17:07 +040054func isValidID(value string) bool {
55 if len(value) != 26 {
56 return false
57 }
58
59 for _, r := range value {
60 if !unicode.IsLetter(r) && !unicode.IsNumber(r) {
61 return false
62 }
63 }
64
65 return true
66}
67
68func invalidUserError(fieldName string, userID string) error {
69 return errors.Errorf("Invalid User field: %s; id: %s", fieldName, userID)
70}
71
72func isValidUsername(s string) bool {
73 if len(s) < userNameMinLength || len(s) > userNameMaxLength {
74 return false
75 }
76
77 validUsernameChars := regexp.MustCompile(`^[a-z0-9\.\-_]+$`)
78 if !validUsernameChars.MatchString(s) {
79 return false
80 }
81
82 return true
83}