user.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 // import "miniflux.app/model"
  5. import (
  6. "errors"
  7. "time"
  8. "miniflux.app/timezone"
  9. )
  10. // User represents a user in the system.
  11. type User struct {
  12. ID int64 `json:"id"`
  13. Username string `json:"username"`
  14. Password string `json:"password,omitempty"`
  15. IsAdmin bool `json:"is_admin"`
  16. Theme string `json:"theme"`
  17. Language string `json:"language"`
  18. Timezone string `json:"timezone"`
  19. EntryDirection string `json:"entry_sorting_direction"`
  20. KeyboardShortcuts bool `json:"keyboard_shortcuts"`
  21. LastLoginAt *time.Time `json:"last_login_at,omitempty"`
  22. Extra map[string]string `json:"extra"`
  23. }
  24. // NewUser returns a new User.
  25. func NewUser() *User {
  26. return &User{Extra: make(map[string]string)}
  27. }
  28. // ValidateUserCreation validates new user.
  29. func (u User) ValidateUserCreation() error {
  30. if err := u.ValidateUserLogin(); err != nil {
  31. return err
  32. }
  33. return u.ValidatePassword()
  34. }
  35. // ValidateUserModification validates user modification payload.
  36. func (u User) ValidateUserModification() error {
  37. if u.Theme != "" {
  38. return ValidateTheme(u.Theme)
  39. }
  40. if u.Password != "" {
  41. return u.ValidatePassword()
  42. }
  43. return nil
  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. // UseTimezone converts last login date to the given timezone.
  63. func (u *User) UseTimezone(tz string) {
  64. if u.LastLoginAt != nil {
  65. *u.LastLoginAt = timezone.Convert(tz, *u.LastLoginAt)
  66. }
  67. }
  68. // Users represents a list of users.
  69. type Users []*User
  70. // UseTimezone converts last login timestamp of all users to the given timezone.
  71. func (u Users) UseTimezone(tz string) {
  72. for _, user := range u {
  73. user.UseTimezone(tz)
  74. }
  75. }