user_handler.go 7.9 KB

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