user_handler.go 8.4 KB

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