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