user.go 2.3 KB

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