user_handler.go 8.6 KB

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