user.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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
  5. import (
  6. "errors"
  7. "github.com/miniflux/miniflux2/model"
  8. "net/http"
  9. )
  10. type UserForm struct {
  11. Username string
  12. Password string
  13. Confirmation string
  14. IsAdmin bool
  15. }
  16. func (u UserForm) ValidateCreation() error {
  17. if u.Username == "" || u.Password == "" || u.Confirmation == "" {
  18. return errors.New("All fields are mandatory.")
  19. }
  20. if u.Password != u.Confirmation {
  21. return errors.New("Passwords are not the same.")
  22. }
  23. if len(u.Password) < 6 {
  24. return errors.New("You must use at least 6 characters.")
  25. }
  26. return nil
  27. }
  28. func (u UserForm) ValidateModification() error {
  29. if u.Username == "" {
  30. return errors.New("The username is mandatory.")
  31. }
  32. if u.Password != "" {
  33. if u.Password != u.Confirmation {
  34. return errors.New("Passwords are not the same.")
  35. }
  36. if len(u.Password) < 6 {
  37. return errors.New("You must use at least 6 characters.")
  38. }
  39. }
  40. return nil
  41. }
  42. func (u UserForm) ToUser() *model.User {
  43. return &model.User{
  44. Username: u.Username,
  45. Password: u.Password,
  46. IsAdmin: u.IsAdmin,
  47. }
  48. }
  49. func (u UserForm) Merge(user *model.User) *model.User {
  50. user.Username = u.Username
  51. user.IsAdmin = u.IsAdmin
  52. if u.Password != "" {
  53. user.Password = u.Password
  54. }
  55. return user
  56. }
  57. func NewUserForm(r *http.Request) *UserForm {
  58. return &UserForm{
  59. Username: r.FormValue("username"),
  60. Password: r.FormValue("password"),
  61. Confirmation: r.FormValue("confirmation"),
  62. IsAdmin: r.FormValue("is_admin") == "1",
  63. }
  64. }