user_handler.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. // HandleListUserProjects lists all projects belonging to a given user
  133. func (app *App) HandleListUserProjects(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. projects, err := app.repo.Project.ListProjectsByUserID(uint(id))
  140. if err != nil {
  141. app.handleErrorRead(err, ErrUserDataRead, w)
  142. }
  143. projectsExt := make([]*models.ProjectExternal, 0)
  144. for _, project := range projects {
  145. projectsExt = append(projectsExt, project.Externalize())
  146. }
  147. w.WriteHeader(http.StatusOK)
  148. if err := json.NewEncoder(w).Encode(projectsExt); err != nil {
  149. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  150. return
  151. }
  152. }
  153. // HandleDeleteUser removes a user after checking that the sent password is correct
  154. func (app *App) HandleDeleteUser(w http.ResponseWriter, r *http.Request) {
  155. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  156. if err != nil || id == 0 {
  157. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  158. return
  159. }
  160. // TODO -- HASH AND VERIFY PASSWORD BEFORE USER DELETION
  161. form := &forms.DeleteUserForm{
  162. ID: uint(id),
  163. }
  164. user, err := app.writeUser(form, app.repo.User.DeleteUser, w, r)
  165. if err == nil {
  166. app.logger.Info().Msgf("User deleted: %d", user.ID)
  167. w.WriteHeader(http.StatusNoContent)
  168. }
  169. }
  170. // ------------------------ User handler helper functions ------------------------ //
  171. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  172. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  173. // write to the database.
  174. func (app *App) writeUser(
  175. form forms.WriteUserForm,
  176. dbWrite repository.WriteUser,
  177. w http.ResponseWriter,
  178. r *http.Request,
  179. validators ...func(repo *repository.Repository, user *models.User) *HTTPError,
  180. ) (*models.User, error) {
  181. // decode from JSON to form value
  182. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  183. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  184. return nil, err
  185. }
  186. // validate the form
  187. if err := app.validator.Struct(form); err != nil {
  188. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  189. return nil, err
  190. }
  191. // convert the form to a user model -- WriteUserForm must implement ToUser
  192. userModel, err := form.ToUser(app.repo.User)
  193. if err != nil {
  194. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  195. return nil, err
  196. }
  197. // Check any additional validators for any semantic errors
  198. // We have completed all syntax checks, so these will be sent
  199. // with http.StatusUnprocessableEntity (422), unless this is
  200. // an internal server error
  201. for _, validator := range validators {
  202. err := validator(app.repo, userModel)
  203. if err != nil {
  204. goErr := errors.New(strings.Join(err.Errors, ", "))
  205. if err.Code == 500 {
  206. app.sendExternalError(
  207. goErr,
  208. http.StatusInternalServerError,
  209. *err,
  210. w,
  211. )
  212. } else {
  213. app.sendExternalError(
  214. goErr,
  215. http.StatusUnprocessableEntity,
  216. *err,
  217. w,
  218. )
  219. }
  220. return nil, goErr
  221. }
  222. }
  223. // handle write to the database
  224. user, err := dbWrite(userModel)
  225. if err != nil {
  226. app.handleErrorDataWrite(err, w)
  227. return nil, err
  228. }
  229. return user, nil
  230. }
  231. func (app *App) readUser(w http.ResponseWriter, r *http.Request) (*models.User, error) {
  232. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  233. if err != nil || id == 0 {
  234. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  235. return nil, err
  236. }
  237. user, err := app.repo.User.ReadUser(uint(id))
  238. if err != nil {
  239. app.handleErrorRead(err, ErrUserDataRead, w)
  240. return nil, err
  241. }
  242. return user, nil
  243. }
  244. func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
  245. user, err := repo.User.ReadUserByEmail(user.Email)
  246. if user != nil && err == nil {
  247. return &HTTPError{
  248. Code: ErrUserValidateFields,
  249. Errors: []string{
  250. "email already taken",
  251. },
  252. }
  253. }
  254. if err != gorm.ErrRecordNotFound {
  255. return &ErrorDataRead
  256. }
  257. return nil
  258. }
  259. func (app *App) sendUser(w http.ResponseWriter, userID uint, email string) error {
  260. resUser := &models.UserExternal{
  261. ID: userID,
  262. Email: email,
  263. }
  264. if err := json.NewEncoder(w).Encode(resUser); err != nil {
  265. return err
  266. }
  267. return nil
  268. }