blob: 6feb94895afd0e74a396ed67fdc66c3c7c02fcae [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
49func isValidID(value string) bool {
50 if len(value) != 26 {
51 return false
52 }
53
54 for _, r := range value {
55 if !unicode.IsLetter(r) && !unicode.IsNumber(r) {
56 return false
57 }
58 }
59
60 return true
61}
62
63func invalidUserError(fieldName string, userID string) error {
64 return errors.Errorf("Invalid User field: %s; id: %s", fieldName, userID)
65}
66
67func isValidUsername(s string) bool {
68 if len(s) < userNameMinLength || len(s) > userNameMaxLength {
69 return false
70 }
71
72 validUsernameChars := regexp.MustCompile(`^[a-z0-9\.\-_]+$`)
73 if !validUsernameChars.MatchString(s) {
74 return false
75 }
76
77 return true
78}