user_handler.go 8.2 KB

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