user_handler.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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.StatusAccepted)
  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. Password: "testing",
  84. }
  85. user, err := app.writeUser(form, app.repo.User.DeleteUser, w, r)
  86. if err == nil {
  87. app.logger.Info().Msgf("User deleted: %d", user.ID)
  88. w.WriteHeader(http.StatusAccepted)
  89. }
  90. }
  91. // ------------------------ User handler helper functions ------------------------ //
  92. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  93. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  94. // write to the database.
  95. func (app *App) writeUser(
  96. form forms.WriteUserForm,
  97. dbWrite repository.WriteUser,
  98. w http.ResponseWriter,
  99. r *http.Request,
  100. validators ...func(repo *repository.Repository, user *models.User) *HTTPError,
  101. ) (*models.User, error) {
  102. // decode from JSON to form value
  103. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  104. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  105. return nil, err
  106. }
  107. // validate the form
  108. if err := app.validator.Struct(form); err != nil {
  109. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  110. return nil, err
  111. }
  112. // convert the form to a user model -- WriteUserForm must implement ToUser
  113. userModel, err := form.ToUser()
  114. if err != nil {
  115. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  116. return nil, err
  117. }
  118. // Check any additional validators for any semantic errors
  119. // We have completed all syntax checks, so these will be sent
  120. // with http.StatusUnprocessableEntity (422), unless this is
  121. // an internal server error
  122. for _, validator := range validators {
  123. err := validator(app.repo, userModel)
  124. if err != nil {
  125. goErr := errors.New(strings.Join(err.Errors, ", "))
  126. if err.Code == 500 {
  127. app.sendExternalError(
  128. goErr,
  129. http.StatusInternalServerError,
  130. *err,
  131. w,
  132. )
  133. } else {
  134. app.sendExternalError(
  135. goErr,
  136. http.StatusUnprocessableEntity,
  137. *err,
  138. w,
  139. )
  140. }
  141. return nil, goErr
  142. }
  143. }
  144. // handle write to the database
  145. user, err := dbWrite(userModel)
  146. if err != nil {
  147. app.handleErrorDataWrite(err, w)
  148. return nil, err
  149. }
  150. return user, nil
  151. }
  152. func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
  153. user, err := repo.User.ReadUserByEmail(user.Email)
  154. if user != nil && err == nil {
  155. return &HTTPError{
  156. Code: ErrUserValidateFields,
  157. Errors: []string{
  158. "Email already taken",
  159. },
  160. }
  161. }
  162. if err != gorm.ErrRecordNotFound {
  163. return &ErrorDataRead
  164. }
  165. return nil
  166. }