user_handler.go 8.0 KB

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