user_handler.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. package api
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "github.com/porter-dev/porter/internal/kubernetes"
  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, 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. // HandleAuthCheck checks whether current session is authenticated.
  46. func (app *App) HandleAuthCheck(w http.ResponseWriter, r *http.Request) {
  47. session, err := app.store.Get(r, app.cookieName)
  48. cook, _ := r.Cookie("porter")
  49. fmt.Println("cooki", cook)
  50. if err != nil {
  51. http.Error(w, err.Error(), http.StatusInternalServerError)
  52. }
  53. if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
  54. app.logger.Info().Msgf(strconv.FormatBool(auth))
  55. w.WriteHeader(http.StatusOK)
  56. w.Write([]byte("false"))
  57. return
  58. }
  59. w.WriteHeader(http.StatusOK)
  60. w.Write([]byte("true"))
  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, ErrUserDataRead, 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().Msgf()
  94. fmt.Println(err)
  95. }
  96. w.WriteHeader(http.StatusOK)
  97. }
  98. // HandleReadUser returns an externalized User (models.UserExternal)
  99. // based on an ID
  100. func (app *App) HandleReadUser(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. extUser := user.Externalize()
  107. if err := json.NewEncoder(w).Encode(extUser); err != nil {
  108. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  109. return
  110. }
  111. w.WriteHeader(http.StatusOK)
  112. }
  113. // HandleReadUserClusters returns the externalized User.Clusters (models.ClusterConfigs)
  114. // based on a user ID
  115. func (app *App) HandleReadUserClusters(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. extClusters := make([]models.ClusterConfigExternal, 0)
  122. for _, cluster := range user.Clusters {
  123. extClusters = append(extClusters, *cluster.Externalize())
  124. }
  125. if err := json.NewEncoder(w).Encode(extClusters); err != nil {
  126. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  127. return
  128. }
  129. w.WriteHeader(http.StatusOK)
  130. }
  131. // HandleReadUserClustersAll returns all models.ClusterConfigs parsed from a KubeConfig
  132. // that is attached to a specific user, identified through the user ID
  133. func (app *App) HandleReadUserClustersAll(w http.ResponseWriter, r *http.Request) {
  134. user, err := app.readUser(w, r)
  135. // if there is an error, it's already handled by helper
  136. if err == nil {
  137. clusters, err := kubernetes.GetAllClusterConfigsFromBytes(user.RawKubeConfig)
  138. if err != nil {
  139. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  140. return
  141. }
  142. extClusters := make([]models.ClusterConfigExternal, 0)
  143. for _, cluster := range clusters {
  144. extClusters = append(extClusters, *cluster.Externalize())
  145. }
  146. if err := json.NewEncoder(w).Encode(extClusters); err != nil {
  147. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  148. return
  149. }
  150. w.WriteHeader(http.StatusOK)
  151. }
  152. }
  153. // HandleUpdateUser validates an update user form entry, updates the user
  154. // in the database, and writes status accepted
  155. func (app *App) HandleUpdateUser(w http.ResponseWriter, r *http.Request) {
  156. id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64)
  157. if err != nil || id == 0 {
  158. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  159. return
  160. }
  161. form := &forms.UpdateUserForm{
  162. ID: uint(id),
  163. }
  164. user, err := app.writeUser(form, app.repo.User.UpdateUser, w, r)
  165. if err == nil {
  166. app.logger.Info().Msgf("User updated: %d", user.ID)
  167. w.WriteHeader(http.StatusNoContent)
  168. }
  169. }
  170. // HandleDeleteUser removes a user after checking that the sent password is correct
  171. func (app *App) HandleDeleteUser(w http.ResponseWriter, r *http.Request) {
  172. id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64)
  173. if err != nil || id == 0 {
  174. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  175. return
  176. }
  177. // TODO -- HASH AND VERIFY PASSWORD BEFORE USER DELETION
  178. form := &forms.DeleteUserForm{
  179. ID: uint(id),
  180. }
  181. user, err := app.writeUser(form, app.repo.User.DeleteUser, w, r)
  182. if err == nil {
  183. app.logger.Info().Msgf("User deleted: %d", user.ID)
  184. w.WriteHeader(http.StatusNoContent)
  185. }
  186. }
  187. // ------------------------ User handler helper functions ------------------------ //
  188. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  189. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  190. // write to the database.
  191. func (app *App) writeUser(
  192. form forms.WriteUserForm,
  193. dbWrite repository.WriteUser,
  194. w http.ResponseWriter,
  195. r *http.Request,
  196. validators ...func(repo *repository.Repository, user *models.User) *HTTPError,
  197. ) (*models.User, error) {
  198. // decode from JSON to form value
  199. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  200. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  201. return nil, err
  202. }
  203. // validate the form
  204. if err := app.validator.Struct(form); err != nil {
  205. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  206. return nil, err
  207. }
  208. // convert the form to a user model -- WriteUserForm must implement ToUser
  209. userModel, err := form.ToUser()
  210. if err != nil {
  211. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  212. return nil, err
  213. }
  214. // Check any additional validators for any semantic errors
  215. // We have completed all syntax checks, so these will be sent
  216. // with http.StatusUnprocessableEntity (422), unless this is
  217. // an internal server error
  218. for _, validator := range validators {
  219. err := validator(app.repo, userModel)
  220. if err != nil {
  221. goErr := errors.New(strings.Join(err.Errors, ", "))
  222. if err.Code == 500 {
  223. app.sendExternalError(
  224. goErr,
  225. http.StatusInternalServerError,
  226. *err,
  227. w,
  228. )
  229. } else {
  230. app.sendExternalError(
  231. goErr,
  232. http.StatusUnprocessableEntity,
  233. *err,
  234. w,
  235. )
  236. }
  237. return nil, goErr
  238. }
  239. }
  240. // handle write to the database
  241. user, err := dbWrite(userModel)
  242. if err != nil {
  243. app.handleErrorDataWrite(err, w)
  244. return nil, err
  245. }
  246. return user, nil
  247. }
  248. func (app *App) readUser(w http.ResponseWriter, r *http.Request) (*models.User, error) {
  249. id, err := strconv.ParseUint(chi.URLParam(r, "id"), 0, 64)
  250. if err != nil || id == 0 {
  251. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  252. return nil, err
  253. }
  254. user, err := app.repo.User.ReadUser(uint(id))
  255. if err != nil {
  256. app.handleErrorRead(err, ErrUserDataRead, w)
  257. return nil, err
  258. }
  259. return user, nil
  260. }
  261. func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
  262. user, err := repo.User.ReadUserByEmail(user.Email)
  263. if user != nil && err == nil {
  264. return &HTTPError{
  265. Code: ErrUserValidateFields,
  266. Errors: []string{
  267. "email already taken",
  268. },
  269. }
  270. }
  271. if err != gorm.ErrRecordNotFound {
  272. return &ErrorDataRead
  273. }
  274. return nil
  275. }