| iomodo | 48c837e | 2021-02-19 01:17:07 +0400 | [diff] [blame] | 1 | package model |
| 2 | |
| 3 | import ( |
| iomodo | 48c837e | 2021-02-19 01:17:07 +0400 | [diff] [blame] | 4 | "regexp" |
| iomodo | 48c837e | 2021-02-19 01:17:07 +0400 | [diff] [blame] | 5 | "unicode" |
| 6 | |
| 7 | "github.com/pkg/errors" |
| 8 | ) |
| 9 | |
| 10 | const ( |
| 11 | userNameMaxLength = 64 |
| 12 | userNameMinLength = 1 |
| 13 | userEmailMaxLength = 128 |
| 14 | ) |
| 15 | |
| 16 | // User contains the details about the user. |
| iomodo | 48c837e | 2021-02-19 01:17:07 +0400 | [diff] [blame] | 17 | type 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"` |
| iomodo | 48c837e | 2021-02-19 01:17:07 +0400 | [diff] [blame] | 24 | 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. |
| 29 | func (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 | |
| iomodo | 48c837e | 2021-02-19 01:17:07 +0400 | [diff] [blame] | 46 | return nil |
| 47 | } |
| 48 | |
| 49 | func 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 | |
| 63 | func invalidUserError(fieldName string, userID string) error { |
| 64 | return errors.Errorf("Invalid User field: %s; id: %s", fieldName, userID) |
| 65 | } |
| 66 | |
| 67 | func 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 | } |