4
0

user.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 form // import "miniflux.app/ui/form"
  5. import (
  6. "net/http"
  7. "miniflux.app/errors"
  8. "miniflux.app/model"
  9. )
  10. // UserForm represents the user form.
  11. type UserForm struct {
  12. Username string
  13. Password string
  14. Confirmation string
  15. IsAdmin bool
  16. }
  17. // ValidateCreation validates user creation.
  18. func (u UserForm) ValidateCreation() error {
  19. if u.Username == "" || u.Password == "" || u.Confirmation == "" {
  20. return errors.NewLocalizedError("error.fields_mandatory")
  21. }
  22. if u.Password != u.Confirmation {
  23. return errors.NewLocalizedError("error.different_passwords")
  24. }
  25. if len(u.Password) < 6 {
  26. return errors.NewLocalizedError("error.password_min_length")
  27. }
  28. return nil
  29. }
  30. // ValidateModification validates user modification.
  31. func (u UserForm) ValidateModification() error {
  32. if u.Username == "" {
  33. return errors.NewLocalizedError("error.user_mandatory_fields")
  34. }
  35. if u.Password != "" {
  36. if u.Password != u.Confirmation {
  37. return errors.NewLocalizedError("error.different_passwords")
  38. }
  39. if len(u.Password) < 6 {
  40. return errors.NewLocalizedError("error.password_min_length")
  41. }
  42. }
  43. return nil
  44. }
  45. // ToUser returns a User from the form values.
  46. func (u UserForm) ToUser() *model.User {
  47. return &model.User{
  48. Username: u.Username,
  49. Password: u.Password,
  50. IsAdmin: u.IsAdmin,
  51. }
  52. }
  53. // Merge updates the fields of the given user.
  54. func (u UserForm) Merge(user *model.User) *model.User {
  55. user.Username = u.Username
  56. user.IsAdmin = u.IsAdmin
  57. if u.Password != "" {
  58. user.Password = u.Password
  59. }
  60. return user
  61. }
  62. // NewUserForm returns a new UserForm.
  63. func NewUserForm(r *http.Request) *UserForm {
  64. return &UserForm{
  65. Username: r.FormValue("username"),
  66. Password: r.FormValue("password"),
  67. Confirmation: r.FormValue("confirmation"),
  68. IsAdmin: r.FormValue("is_admin") == "1",
  69. }
  70. }