user_handler.go 8.1 KB

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