user_handler.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. package api
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strconv"
  6. "github.com/go-chi/chi"
  7. "github.com/porter-dev/porter/internal/forms"
  8. "github.com/porter-dev/porter/internal/models"
  9. "github.com/porter-dev/porter/internal/repository"
  10. "golang.org/x/crypto/bcrypt"
  11. )
  12. // Enumeration of user API error codes, represented as int64
  13. const (
  14. ErrUserDecode ErrorCode = iota
  15. ErrUserValidateFields
  16. ErrUserDataWrite
  17. ErrUserDataRead
  18. )
  19. // HandleCreateUser validates a user form entry, converts the user to a gorm
  20. // model, and saves the user to the database
  21. func (app *App) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
  22. form := &forms.CreateUserForm{}
  23. user, err := app.writeUser(form, app.repo.User.CreateUser, w, r)
  24. if err == nil {
  25. app.logger.Info().Msgf("New user created: %d", user.ID)
  26. w.WriteHeader(http.StatusCreated)
  27. }
  28. }
  29. // HandleLoginUser checks the request header for cookie and validates the user.
  30. func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
  31. session, _ := app.store.Get(r, "cookie-name")
  32. // read in email and password from request
  33. email := chi.URLParam(r, "email")
  34. password := chi.URLParam(r, "password")
  35. // Authentication goes here
  36. // Select User by Username (app.repo.User.ReadUserByUsername) and return storedCreds object that has Password.
  37. storedUser, readErr := app.repo.User.ReadUserByEmail(email)
  38. if readErr != nil {
  39. // You're not registered error
  40. app.logger.Warn().Err(readErr)
  41. w.WriteHeader(http.StatusUnauthorized)
  42. return
  43. }
  44. if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(password)); err != nil {
  45. // If the two passwords don't match, return a 401 status
  46. w.WriteHeader(http.StatusUnauthorized)
  47. return
  48. }
  49. // Set user as authenticated
  50. session.Values["authenticated"] = true
  51. session.Save(r, w)
  52. }
  53. // HandleReadUser returns an externalized User (models.UserExternal)
  54. // based on an ID
  55. func (app *App) HandleReadUser(w http.ResponseWriter, r *http.Request) {
  56. id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64)
  57. if err != nil || id == 0 {
  58. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  59. return
  60. }
  61. user, err := app.repo.User.ReadUser(uint(id))
  62. if err != nil {
  63. app.handleErrorRead(err, ErrUserDataRead, w)
  64. return
  65. }
  66. extUser := user.Externalize()
  67. if err := json.NewEncoder(w).Encode(extUser); err != nil {
  68. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  69. return
  70. }
  71. w.WriteHeader(http.StatusOK)
  72. }
  73. // HandleUpdateUser validates an update user form entry, updates the user
  74. // in the database, and writes status accepted
  75. func (app *App) HandleUpdateUser(w http.ResponseWriter, r *http.Request) {
  76. id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64)
  77. if err != nil || id == 0 {
  78. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  79. return
  80. }
  81. form := &forms.UpdateUserForm{
  82. ID: uint(id),
  83. }
  84. user, err := app.writeUser(form, app.repo.User.UpdateUser, w, r)
  85. if err == nil {
  86. app.logger.Info().Msgf("User updated: %d", user.ID)
  87. w.WriteHeader(http.StatusAccepted)
  88. }
  89. }
  90. // HandleDeleteUser is majestic
  91. func (app *App) HandleDeleteUser(w http.ResponseWriter, r *http.Request) {
  92. id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64)
  93. if err != nil || id == 0 {
  94. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  95. return
  96. }
  97. // TODO -- HASH AND VERIFY PASSWORD BEFORE USER DELETION
  98. form := &forms.DeleteUserForm{
  99. ID: uint(id),
  100. Password: "testing",
  101. }
  102. user, err := app.writeUser(form, app.repo.User.DeleteUser, w, r)
  103. if err == nil {
  104. app.logger.Info().Msgf("User deleted: %d", user.ID)
  105. w.WriteHeader(http.StatusAccepted)
  106. }
  107. }
  108. // ------------------------ User handler helper functions ------------------------ //
  109. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  110. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  111. // write to the database.
  112. func (app *App) writeUser(
  113. form forms.WriteUserForm,
  114. dbWrite repository.WriteUser,
  115. w http.ResponseWriter,
  116. r *http.Request,
  117. ) (*models.User, error) {
  118. // decode from JSON to form value
  119. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  120. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  121. return nil, err
  122. }
  123. // validate the form
  124. if err := app.validator.Struct(form); err != nil {
  125. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  126. return nil, err
  127. }
  128. // convert the form to a user model -- WriteUserForm must implement ToUser
  129. userModel, err := form.ToUser()
  130. if err != nil {
  131. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  132. return nil, err
  133. }
  134. // handle write to the database
  135. user, err := dbWrite(userModel)
  136. if err != nil {
  137. app.handleErrorDataWrite(err, ErrUserDataWrite, w)
  138. return nil, err
  139. }
  140. return user, nil
  141. }