user_handler.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package api
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "golang.org/x/crypto/bcrypt"
  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. )
  15. // Enumeration of user API error codes, represented as int64
  16. const (
  17. ErrUserDecode ErrorCode = iota + 600
  18. ErrUserValidateFields
  19. ErrUserDataRead
  20. )
  21. // HandleCreateUser validates a user form entry, converts the user to a gorm
  22. // model, and saves the user to the database
  23. func (app *App) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
  24. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  25. if err != nil {
  26. app.handleErrorDataRead(err, w)
  27. }
  28. form := &forms.CreateUserForm{}
  29. user, err := app.writeUser(
  30. form,
  31. app.Repo.User.CreateUser,
  32. w,
  33. r,
  34. doesUserExist,
  35. )
  36. if err == nil {
  37. app.Logger.Info().Msgf("New user created: %d", user.ID)
  38. session.Values["authenticated"] = true
  39. session.Values["user_id"] = user.ID
  40. session.Values["email"] = user.Email
  41. session.Save(r, w)
  42. if val, ok := session.Values["redirect"].(string); ok && val != "" {
  43. http.Redirect(w, r, val, 302)
  44. return
  45. }
  46. w.WriteHeader(http.StatusCreated)
  47. if err := app.sendUser(w, user.ID, user.Email); err != nil {
  48. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  49. return
  50. }
  51. }
  52. }
  53. // HandleAuthCheck checks whether current session is authenticated and returns user ID if so.
  54. func (app *App) HandleAuthCheck(w http.ResponseWriter, r *http.Request) {
  55. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  56. if err != nil {
  57. http.Error(w, err.Error(), http.StatusInternalServerError)
  58. return
  59. }
  60. userID, _ := session.Values["user_id"].(uint)
  61. email, _ := session.Values["email"].(string)
  62. w.WriteHeader(http.StatusOK)
  63. if err := app.sendUser(w, userID, email); err != nil {
  64. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  65. return
  66. }
  67. }
  68. // HandleLoginUser checks the request header for cookie and validates the user.
  69. func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
  70. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  71. if err != nil {
  72. app.handleErrorDataRead(err, w)
  73. return
  74. }
  75. form := &forms.LoginUserForm{}
  76. // decode from JSON to form value
  77. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  78. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  79. return
  80. }
  81. storedUser, readErr := app.Repo.User.ReadUserByEmail(form.Email)
  82. if readErr != nil {
  83. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  84. Errors: []string{"email not registered"},
  85. Code: http.StatusUnauthorized,
  86. }, w)
  87. return
  88. }
  89. if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(form.Password)); err != nil {
  90. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  91. Errors: []string{"incorrect password"},
  92. Code: http.StatusUnauthorized,
  93. }, w)
  94. return
  95. }
  96. // Set user as authenticated
  97. session.Values["authenticated"] = true
  98. session.Values["user_id"] = storedUser.ID
  99. session.Values["email"] = storedUser.Email
  100. if err := session.Save(r, w); err != nil {
  101. app.Logger.Warn().Err(err)
  102. }
  103. if val, ok := session.Values["redirect"].(string); ok && val != "" {
  104. http.Redirect(w, r, val, 302)
  105. return
  106. }
  107. w.WriteHeader(http.StatusCreated)
  108. if err := app.sendUser(w, storedUser.ID, storedUser.Email); err != nil {
  109. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  110. return
  111. }
  112. }
  113. // HandleLogoutUser detaches the user from the session
  114. func (app *App) HandleLogoutUser(w http.ResponseWriter, r *http.Request) {
  115. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  116. if err != nil {
  117. app.handleErrorDataRead(err, w)
  118. }
  119. session.Values["authenticated"] = false
  120. session.Values["user_id"] = nil
  121. session.Values["email"] = nil
  122. session.Save(r, w)
  123. w.WriteHeader(http.StatusOK)
  124. }
  125. // HandleReadUser returns an externalized User (models.UserExternal)
  126. // based on an ID
  127. func (app *App) HandleReadUser(w http.ResponseWriter, r *http.Request) {
  128. user, err := app.readUser(w, r)
  129. // error already handled by helper
  130. if err != nil {
  131. return
  132. }
  133. extUser := user.Externalize()
  134. if err := json.NewEncoder(w).Encode(extUser); err != nil {
  135. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  136. return
  137. }
  138. w.WriteHeader(http.StatusOK)
  139. }
  140. // HandleListUserProjects lists all projects belonging to a given user
  141. func (app *App) HandleListUserProjects(w http.ResponseWriter, r *http.Request) {
  142. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  143. if err != nil || id == 0 {
  144. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  145. return
  146. }
  147. projects, err := app.Repo.Project.ListProjectsByUserID(uint(id))
  148. if err != nil {
  149. app.handleErrorRead(err, ErrUserDataRead, w)
  150. }
  151. projectsExt := make([]*models.ProjectExternal, 0)
  152. for _, project := range projects {
  153. projectsExt = append(projectsExt, project.Externalize())
  154. }
  155. w.WriteHeader(http.StatusOK)
  156. if err := json.NewEncoder(w).Encode(projectsExt); err != nil {
  157. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  158. return
  159. }
  160. }
  161. // HandleDeleteUser removes a user after checking that the sent password is correct
  162. func (app *App) HandleDeleteUser(w http.ResponseWriter, r *http.Request) {
  163. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  164. if err != nil || id == 0 {
  165. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  166. return
  167. }
  168. // TODO -- HASH AND VERIFY PASSWORD BEFORE USER DELETION
  169. form := &forms.DeleteUserForm{
  170. ID: uint(id),
  171. }
  172. user, err := app.writeUser(form, app.Repo.User.DeleteUser, w, r)
  173. if err == nil {
  174. app.Logger.Info().Msgf("User deleted: %d", user.ID)
  175. w.WriteHeader(http.StatusNoContent)
  176. }
  177. }
  178. // ------------------------ User handler helper functions ------------------------ //
  179. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  180. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  181. // write to the database.
  182. func (app *App) writeUser(
  183. form forms.WriteUserForm,
  184. dbWrite repository.WriteUser,
  185. w http.ResponseWriter,
  186. r *http.Request,
  187. validators ...func(repo *repository.Repository, user *models.User) *HTTPError,
  188. ) (*models.User, error) {
  189. // decode from JSON to form value
  190. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  191. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  192. return nil, err
  193. }
  194. // validate the form
  195. if err := app.validator.Struct(form); err != nil {
  196. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  197. return nil, err
  198. }
  199. // convert the form to a user model -- WriteUserForm must implement ToUser
  200. userModel, err := form.ToUser(app.Repo.User)
  201. if err != nil {
  202. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  203. return nil, err
  204. }
  205. // Check any additional validators for any semantic errors
  206. // We have completed all syntax checks, so these will be sent
  207. // with http.StatusUnprocessableEntity (422), unless this is
  208. // an internal server error
  209. for _, validator := range validators {
  210. err := validator(app.Repo, userModel)
  211. if err != nil {
  212. goErr := errors.New(strings.Join(err.Errors, ", "))
  213. if err.Code == 500 {
  214. app.sendExternalError(
  215. goErr,
  216. http.StatusInternalServerError,
  217. *err,
  218. w,
  219. )
  220. } else {
  221. app.sendExternalError(
  222. goErr,
  223. http.StatusUnprocessableEntity,
  224. *err,
  225. w,
  226. )
  227. }
  228. return nil, goErr
  229. }
  230. }
  231. // handle write to the database
  232. user, err := dbWrite(userModel)
  233. if err != nil {
  234. app.handleErrorDataWrite(err, w)
  235. return nil, err
  236. }
  237. return user, nil
  238. }
  239. func (app *App) readUser(w http.ResponseWriter, r *http.Request) (*models.User, error) {
  240. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  241. if err != nil || id == 0 {
  242. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  243. return nil, err
  244. }
  245. user, err := app.Repo.User.ReadUser(uint(id))
  246. if err != nil {
  247. app.handleErrorRead(err, ErrUserDataRead, w)
  248. return nil, err
  249. }
  250. return user, nil
  251. }
  252. func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
  253. user, err := repo.User.ReadUserByEmail(user.Email)
  254. if user != nil && err == nil {
  255. return &HTTPError{
  256. Code: ErrUserValidateFields,
  257. Errors: []string{
  258. "email already taken",
  259. },
  260. }
  261. }
  262. if err != gorm.ErrRecordNotFound {
  263. return &ErrorDataRead
  264. }
  265. return nil
  266. }
  267. func (app *App) sendUser(w http.ResponseWriter, userID uint, email string) error {
  268. resUser := &models.UserExternal{
  269. ID: userID,
  270. Email: email,
  271. }
  272. if err := json.NewEncoder(w).Encode(resUser); err != nil {
  273. return err
  274. }
  275. return nil
  276. }