user.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package model
  5. import (
  6. "errors"
  7. "time"
  8. )
  9. // User represents a user in the system.
  10. type User struct {
  11. ID int64 `json:"id"`
  12. Username string `json:"username"`
  13. Password string `json:"password,omitempty"`
  14. IsAdmin bool `json:"is_admin,omitempty"`
  15. Theme string `json:"theme,omitempty"`
  16. Language string `json:"language,omitempty"`
  17. Timezone string `json:"timezone,omitempty"`
  18. LastLoginAt *time.Time `json:"last_login_at,omitempty"`
  19. Extra map[string]string `json:"-"`
  20. }
  21. // NewUser returns a new User.
  22. func NewUser() *User {
  23. return &User{Extra: make(map[string]string)}
  24. }
  25. // ValidateUserCreation validates new user.
  26. func (u User) ValidateUserCreation() error {
  27. if err := u.ValidateUserLogin(); err != nil {
  28. return err
  29. }
  30. return u.ValidatePassword()
  31. }
  32. // ValidateUserModification validates user for modification.
  33. func (u User) ValidateUserModification() error {
  34. if u.ID <= 0 {
  35. return errors.New("The ID is mandatory")
  36. }
  37. if u.Username == "" {
  38. return errors.New("The username is mandatory")
  39. }
  40. if err := u.ValidatePassword(); err != nil {
  41. return err
  42. }
  43. return ValidateTheme(u.Theme)
  44. }
  45. // ValidateUserLogin validates user credential requirements.
  46. func (u User) ValidateUserLogin() error {
  47. if u.Username == "" {
  48. return errors.New("The username is mandatory")
  49. }
  50. if u.Password == "" {
  51. return errors.New("The password is mandatory")
  52. }
  53. return nil
  54. }
  55. // ValidatePassword validates user password requirements.
  56. func (u User) ValidatePassword() error {
  57. if u.Password != "" && len(u.Password) < 6 {
  58. return errors.New("The password must have at least 6 characters")
  59. }
  60. return nil
  61. }
  62. // Merge update the current user with another user.
  63. func (u *User) Merge(override *User) {
  64. if u.Username != override.Username {
  65. u.Username = override.Username
  66. }
  67. if u.Password != override.Password {
  68. u.Password = override.Password
  69. }
  70. if u.IsAdmin != override.IsAdmin {
  71. u.IsAdmin = override.IsAdmin
  72. }
  73. if u.Theme != override.Theme {
  74. u.Theme = override.Theme
  75. }
  76. if u.Language != override.Language {
  77. u.Language = override.Language
  78. }
  79. if u.Timezone != override.Timezone {
  80. u.Timezone = override.Timezone
  81. }
  82. }
  83. // Users represents a list of users.
  84. type Users []*User