user_handler.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. package api
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "golang.org/x/crypto/bcrypt"
  9. "gorm.io/gorm"
  10. "github.com/go-chi/chi"
  11. "github.com/porter-dev/porter/internal/forms"
  12. "github.com/porter-dev/porter/internal/models"
  13. "github.com/porter-dev/porter/internal/repository"
  14. )
  15. // Enumeration of user API error codes, represented as int64
  16. const (
  17. ErrUserDecode ErrorCode = iota + 600
  18. ErrUserValidateFields
  19. ErrUserDataRead
  20. )
  21. // HandleCreateUser validates a user form entry, converts the user to a gorm
  22. // model, and saves the user to the database
  23. func (app *App) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
  24. session, err := app.store.Get(r, app.cookieName)
  25. if err != nil {
  26. app.handleErrorDataRead(err, w)
  27. }
  28. form := &forms.CreateUserForm{}
  29. user, err := app.writeUser(
  30. form,
  31. app.repo.User.CreateUser,
  32. w,
  33. r,
  34. doesUserExist,
  35. )
  36. if err == nil {
  37. app.logger.Info().Msgf("New user created: %d", user.ID)
  38. session.Values["authenticated"] = true
  39. session.Values["user_id"] = user.ID
  40. session.Values["email"] = user.Email
  41. session.Save(r, w)
  42. w.WriteHeader(http.StatusCreated)
  43. if err := app.sendUser(w, user.ID, user.Email); err != nil {
  44. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  45. return
  46. }
  47. }
  48. }
  49. // HandleAuthCheck checks whether current session is authenticated and returns user ID if so.
  50. func (app *App) HandleAuthCheck(w http.ResponseWriter, r *http.Request) {
  51. session, err := app.store.Get(r, app.cookieName)
  52. if err != nil {
  53. http.Error(w, err.Error(), http.StatusInternalServerError)
  54. return
  55. }
  56. userID, _ := session.Values["user_id"].(uint)
  57. email, _ := session.Values["email"].(string)
  58. w.WriteHeader(http.StatusOK)
  59. if err := app.sendUser(w, userID, email); err != nil {
  60. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  61. return
  62. }
  63. }
  64. // HandleLoginUser checks the request header for cookie and validates the user.
  65. func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
  66. session, err := app.store.Get(r, app.cookieName)
  67. if err != nil {
  68. app.handleErrorDataRead(err, w)
  69. return
  70. }
  71. form := &forms.LoginUserForm{}
  72. // decode from JSON to form value
  73. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  74. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  75. return
  76. }
  77. storedUser, readErr := app.repo.User.ReadUserByEmail(form.Email)
  78. if readErr != nil {
  79. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  80. Errors: []string{"email not registered"},
  81. Code: http.StatusUnauthorized,
  82. }, w)
  83. return
  84. }
  85. if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(form.Password)); err != nil {
  86. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  87. Errors: []string{"incorrect password"},
  88. Code: http.StatusUnauthorized,
  89. }, w)
  90. return
  91. }
  92. // Set user as authenticated
  93. session.Values["authenticated"] = true
  94. session.Values["user_id"] = storedUser.ID
  95. session.Values["email"] = storedUser.Email
  96. if err := session.Save(r, w); err != nil {
  97. app.logger.Warn().Err(err)
  98. }
  99. w.WriteHeader(http.StatusOK)
  100. if err := app.sendUser(w, storedUser.ID, storedUser.Email); err != nil {
  101. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  102. return
  103. }
  104. }
  105. // HandleLogoutUser detaches the user from the session
  106. func (app *App) HandleLogoutUser(w http.ResponseWriter, r *http.Request) {
  107. session, err := app.store.Get(r, app.cookieName)
  108. if err != nil {
  109. app.handleErrorDataRead(err, w)
  110. }
  111. session.Values["authenticated"] = false
  112. session.Values["user_id"] = nil
  113. session.Values["email"] = nil
  114. session.Save(r, w)
  115. w.WriteHeader(http.StatusOK)
  116. }
  117. // HandleReadUser returns an externalized User (models.UserExternal)
  118. // based on an ID
  119. func (app *App) HandleReadUser(w http.ResponseWriter, r *http.Request) {
  120. user, err := app.readUser(w, r)
  121. // error already handled by helper
  122. if err != nil {
  123. return
  124. }
  125. extUser := user.Externalize()
  126. if err := json.NewEncoder(w).Encode(extUser); err != nil {
  127. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  128. return
  129. }
  130. w.WriteHeader(http.StatusOK)
  131. }
  132. // HandleDeleteUser removes a user after checking that the sent password is correct
  133. func (app *App) HandleDeleteUser(w http.ResponseWriter, r *http.Request) {
  134. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  135. if err != nil || id == 0 {
  136. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  137. return
  138. }
  139. // TODO -- HASH AND VERIFY PASSWORD BEFORE USER DELETION
  140. form := &forms.DeleteUserForm{
  141. ID: uint(id),
  142. }
  143. user, err := app.writeUser(form, app.repo.User.DeleteUser, w, r)
  144. if err == nil {
  145. app.logger.Info().Msgf("User deleted: %d", user.ID)
  146. w.WriteHeader(http.StatusNoContent)
  147. }
  148. }
  149. // ------------------------ User handler helper functions ------------------------ //
  150. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  151. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  152. // write to the database.
  153. func (app *App) writeUser(
  154. form forms.WriteUserForm,
  155. dbWrite repository.WriteUser,
  156. w http.ResponseWriter,
  157. r *http.Request,
  158. validators ...func(repo *repository.Repository, user *models.User) *HTTPError,
  159. ) (*models.User, error) {
  160. // decode from JSON to form value
  161. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  162. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  163. return nil, err
  164. }
  165. // validate the form
  166. if err := app.validator.Struct(form); err != nil {
  167. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  168. return nil, err
  169. }
  170. // convert the form to a user model -- WriteUserForm must implement ToUser
  171. userModel, err := form.ToUser(app.repo.User)
  172. if err != nil {
  173. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  174. return nil, err
  175. }
  176. // Check any additional validators for any semantic errors
  177. // We have completed all syntax checks, so these will be sent
  178. // with http.StatusUnprocessableEntity (422), unless this is
  179. // an internal server error
  180. for _, validator := range validators {
  181. err := validator(app.repo, userModel)
  182. if err != nil {
  183. goErr := errors.New(strings.Join(err.Errors, ", "))
  184. if err.Code == 500 {
  185. app.sendExternalError(
  186. goErr,
  187. http.StatusInternalServerError,
  188. *err,
  189. w,
  190. )
  191. } else {
  192. app.sendExternalError(
  193. goErr,
  194. http.StatusUnprocessableEntity,
  195. *err,
  196. w,
  197. )
  198. }
  199. return nil, goErr
  200. }
  201. }
  202. // handle write to the database
  203. user, err := dbWrite(userModel)
  204. if err != nil {
  205. app.handleErrorDataWrite(err, w)
  206. return nil, err
  207. }
  208. return user, nil
  209. }
  210. func (app *App) readUser(w http.ResponseWriter, r *http.Request) (*models.User, error) {
  211. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  212. if err != nil || id == 0 {
  213. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  214. return nil, err
  215. }
  216. user, err := app.repo.User.ReadUser(uint(id))
  217. if err != nil {
  218. app.handleErrorRead(err, ErrUserDataRead, w)
  219. return nil, err
  220. }
  221. return user, nil
  222. }
  223. func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
  224. user, err := repo.User.ReadUserByEmail(user.Email)
  225. if user != nil && err == nil {
  226. return &HTTPError{
  227. Code: ErrUserValidateFields,
  228. Errors: []string{
  229. "email already taken",
  230. },
  231. }
  232. }
  233. if err != gorm.ErrRecordNotFound {
  234. return &ErrorDataRead
  235. }
  236. return nil
  237. }
  238. func (app *App) sendUser(w http.ResponseWriter, userID uint, email string) error {
  239. resUser := &models.UserExternal{
  240. ID: userID,
  241. Email: email,
  242. }
  243. if err := json.NewEncoder(w).Encode(resUser); err != nil {
  244. return err
  245. }
  246. return nil
  247. }