user.go 2.4 KB

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