blob: e68bb63449fd7b85d43874fa580281c0f12a26bc [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
iomodo493dd482021-04-02 00:07:51 +040049// IsValidInput validates the user input and returns an error
50func (u *User) IsValidInput() error {
51 if !isValidUsername(u.Username) {
52 return invalidUserError("username", u.ID)
53 }
54
55 return nil
56}
57
iomodo352127d2021-03-26 20:10:32 +040058// Clone clones the object
iomodo07334d22021-02-24 01:08:40 +040059func (u *User) Clone() *User {
60 user := *u
61 return &user
62}
63
iomodo352127d2021-03-26 20:10:32 +040064// SanitizeInput removes input data from the user object that is not user controlled
65func (u *User) SanitizeInput() {
66 u.ID = ""
67 u.CreateAt = 0
68 u.UpdateAt = 0
69 u.DeleteAt = 0
70 u.LastPasswordUpdate = 0
71}
72
73// SanitizeOutput removes output data from the user object that is not user controlled
74func (u *User) SanitizeOutput() {
75 u.Password = ""
76}
77
iomodo48c837e2021-02-19 01:17:07 +040078func isValidID(value string) bool {
79 if len(value) != 26 {
80 return false
81 }
82
83 for _, r := range value {
84 if !unicode.IsLetter(r) && !unicode.IsNumber(r) {
85 return false
86 }
87 }
88
89 return true
90}
91
92func invalidUserError(fieldName string, userID string) error {
93 return errors.Errorf("Invalid User field: %s; id: %s", fieldName, userID)
94}
95
96func isValidUsername(s string) bool {
97 if len(s) < userNameMinLength || len(s) > userNameMaxLength {
98 return false
99 }
100
101 validUsernameChars := regexp.MustCompile(`^[a-z0-9\.\-_]+$`)
102 if !validUsernameChars.MatchString(s) {
103 return false
104 }
105
106 return true
107}