user.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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"`
  15. Theme string `json:"theme"`
  16. Language string `json:"language"`
  17. Timezone string `json:"timezone"`
  18. LastLoginAt *time.Time `json:"last_login_at"`
  19. }
  20. func (u User) ValidateUserCreation() error {
  21. if err := u.ValidateUserLogin(); err != nil {
  22. return err
  23. }
  24. if err := u.ValidatePassword(); err != nil {
  25. return err
  26. }
  27. return nil
  28. }
  29. func (u User) ValidateUserModification() error {
  30. if u.Username == "" {
  31. return errors.New("The username is mandatory")
  32. }
  33. if err := u.ValidatePassword(); err != nil {
  34. return err
  35. }
  36. return nil
  37. }
  38. func (u User) ValidateUserLogin() error {
  39. if u.Username == "" {
  40. return errors.New("The username is mandatory")
  41. }
  42. if u.Password == "" {
  43. return errors.New("The password is mandatory")
  44. }
  45. return nil
  46. }
  47. func (u User) ValidatePassword() error {
  48. if u.Password != "" && len(u.Password) < 6 {
  49. return errors.New("The password must have at least 6 characters")
  50. }
  51. return nil
  52. }
  53. // Merge update the current user with another user.
  54. func (u *User) Merge(override *User) {
  55. if u.Username != override.Username {
  56. u.Username = override.Username
  57. }
  58. if u.Password != override.Password {
  59. u.Password = override.Password
  60. }
  61. if u.IsAdmin != override.IsAdmin {
  62. u.IsAdmin = override.IsAdmin
  63. }
  64. if u.Theme != override.Theme {
  65. u.Theme = override.Theme
  66. }
  67. if u.Language != override.Language {
  68. u.Language = override.Language
  69. }
  70. if u.Timezone != override.Timezone {
  71. u.Timezone = override.Timezone
  72. }
  73. }
  74. // Users represents a list of users.
  75. type Users []*User