user.go 2.6 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 // 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. EntriesPerPage int `json:"entries_per_page"`
  21. KeyboardShortcuts bool `json:"keyboard_shortcuts"`
  22. ShowReadingTime bool `json:"show_reading_time"`
  23. LastLoginAt *time.Time `json:"last_login_at,omitempty"`
  24. Extra map[string]string `json:"extra"`
  25. EntrySwipe bool `json:"entry_swipe"`
  26. }
  27. // NewUser returns a new User.
  28. func NewUser() *User {
  29. return &User{Extra: make(map[string]string)}
  30. }
  31. // ValidateUserCreation validates new user.
  32. func (u User) ValidateUserCreation() error {
  33. if err := u.ValidateUserLogin(); err != nil {
  34. return err
  35. }
  36. return u.ValidatePassword()
  37. }
  38. // ValidateUserModification validates user modification payload.
  39. func (u User) ValidateUserModification() error {
  40. if u.Theme != "" {
  41. return ValidateTheme(u.Theme)
  42. }
  43. if u.Password != "" {
  44. return u.ValidatePassword()
  45. }
  46. return nil
  47. }
  48. // ValidateUserLogin validates user credential requirements.
  49. func (u User) ValidateUserLogin() error {
  50. if u.Username == "" {
  51. return errors.New("The username is mandatory")
  52. }
  53. if u.Password == "" {
  54. return errors.New("The password is mandatory")
  55. }
  56. return nil
  57. }
  58. // ValidatePassword validates user password requirements.
  59. func (u User) ValidatePassword() error {
  60. if u.Password != "" && len(u.Password) < 6 {
  61. return errors.New("The password must have at least 6 characters")
  62. }
  63. return nil
  64. }
  65. // UseTimezone converts last login date to the given timezone.
  66. func (u *User) UseTimezone(tz string) {
  67. if u.LastLoginAt != nil {
  68. *u.LastLoginAt = timezone.Convert(tz, *u.LastLoginAt)
  69. }
  70. }
  71. // Users represents a list of users.
  72. type Users []*User
  73. // UseTimezone converts last login timestamp of all users to the given timezone.
  74. func (u Users) UseTimezone(tz string) {
  75. for _, user := range u {
  76. user.UseTimezone(tz)
  77. }
  78. }