user.go 2.5 KB

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