user_handler.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. package api
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "gorm.io/gorm"
  9. "github.com/go-chi/chi"
  10. "github.com/porter-dev/porter/internal/forms"
  11. "github.com/porter-dev/porter/internal/models"
  12. "github.com/porter-dev/porter/internal/repository"
  13. )
  14. // Enumeration of user API error codes, represented as int64
  15. const (
  16. ErrUserDecode ErrorCode = iota + 600
  17. ErrUserValidateFields
  18. ErrUserDataRead
  19. )
  20. // HandleCreateUser validates a user form entry, converts the user to a gorm
  21. // model, and saves the user to the database
  22. func (app *App) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
  23. form := &forms.CreateUserForm{}
  24. user, err := app.writeUser(
  25. form,
  26. app.repo.User.CreateUser,
  27. w,
  28. r,
  29. doesUserExist,
  30. )
  31. if err == nil {
  32. app.logger.Info().Msgf("New user created: %d", user.ID)
  33. w.WriteHeader(http.StatusCreated)
  34. }
  35. }
  36. // HandleReadUser returns an externalized User (models.UserExternal)
  37. // based on an ID
  38. func (app *App) HandleReadUser(w http.ResponseWriter, r *http.Request) {
  39. id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64)
  40. if err != nil || id == 0 {
  41. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  42. return
  43. }
  44. user, err := app.repo.User.ReadUser(uint(id))
  45. if err != nil {
  46. app.handleErrorRead(err, ErrUserDataRead, w)
  47. return
  48. }
  49. extUser := user.Externalize()
  50. if err := json.NewEncoder(w).Encode(extUser); err != nil {
  51. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  52. return
  53. }
  54. w.WriteHeader(http.StatusOK)
  55. }
  56. // HandleUpdateUser validates an update user form entry, updates the user
  57. // in the database, and writes status accepted
  58. func (app *App) HandleUpdateUser(w http.ResponseWriter, r *http.Request) {
  59. id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64)
  60. if err != nil || id == 0 {
  61. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  62. return
  63. }
  64. form := &forms.UpdateUserForm{
  65. ID: uint(id),
  66. }
  67. user, err := app.writeUser(form, app.repo.User.UpdateUser, w, r)
  68. if err == nil {
  69. app.logger.Info().Msgf("User updated: %d", user.ID)
  70. w.WriteHeader(http.StatusNoContent)
  71. }
  72. }
  73. // HandleDeleteUser is majestic
  74. func (app *App) HandleDeleteUser(w http.ResponseWriter, r *http.Request) {
  75. id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64)
  76. if err != nil || id == 0 {
  77. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  78. return
  79. }
  80. // TODO -- HASH AND VERIFY PASSWORD BEFORE USER DELETION
  81. form := &forms.DeleteUserForm{
  82. ID: uint(id),
  83. }
  84. user, err := app.writeUser(form, app.repo.User.DeleteUser, w, r)
  85. if err == nil {
  86. app.logger.Info().Msgf("User deleted: %d", user.ID)
  87. w.WriteHeader(http.StatusNoContent)
  88. }
  89. }
  90. // ------------------------ User handler helper functions ------------------------ //
  91. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  92. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  93. // write to the database.
  94. func (app *App) writeUser(
  95. form forms.WriteUserForm,
  96. dbWrite repository.WriteUser,
  97. w http.ResponseWriter,
  98. r *http.Request,
  99. validators ...func(repo *repository.Repository, user *models.User) *HTTPError,
  100. ) (*models.User, error) {
  101. // decode from JSON to form value
  102. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  103. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  104. return nil, err
  105. }
  106. // validate the form
  107. if err := app.validator.Struct(form); err != nil {
  108. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  109. return nil, err
  110. }
  111. // convert the form to a user model -- WriteUserForm must implement ToUser
  112. userModel, err := form.ToUser()
  113. if err != nil {
  114. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  115. return nil, err
  116. }
  117. // Check any additional validators for any semantic errors
  118. // We have completed all syntax checks, so these will be sent
  119. // with http.StatusUnprocessableEntity (422), unless this is
  120. // an internal server error
  121. for _, validator := range validators {
  122. err := validator(app.repo, userModel)
  123. if err != nil {
  124. goErr := errors.New(strings.Join(err.Errors, ", "))
  125. if err.Code == 500 {
  126. app.sendExternalError(
  127. goErr,
  128. http.StatusInternalServerError,
  129. *err,
  130. w,
  131. )
  132. } else {
  133. app.sendExternalError(
  134. goErr,
  135. http.StatusUnprocessableEntity,
  136. *err,
  137. w,
  138. )
  139. }
  140. return nil, goErr
  141. }
  142. }
  143. // handle write to the database
  144. user, err := dbWrite(userModel)
  145. if err != nil {
  146. app.handleErrorDataWrite(err, w)
  147. return nil, err
  148. }
  149. return user, nil
  150. }
  151. func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
  152. user, err := repo.User.ReadUserByEmail(user.Email)
  153. if user != nil && err == nil {
  154. return &HTTPError{
  155. Code: ErrUserValidateFields,
  156. Errors: []string{
  157. "email already taken",
  158. },
  159. }
  160. }
  161. if err != gorm.ErrRecordNotFound {
  162. return &ErrorDataRead
  163. }
  164. return nil
  165. }