user_handler.go 8.4 KB

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