user_handler.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. redirect := session.Values["redirect"]
  39. session.Values["authenticated"] = true
  40. session.Values["user_id"] = user.ID
  41. session.Values["email"] = user.Email
  42. session.Values["redirect"] = ""
  43. session.Save(r, w)
  44. if val, ok := redirect.(string); ok && val != "" {
  45. http.Redirect(w, r, val, 302)
  46. return
  47. }
  48. w.WriteHeader(http.StatusCreated)
  49. if err := app.sendUser(w, user.ID, user.Email); err != nil {
  50. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  51. return
  52. }
  53. }
  54. }
  55. // HandleAuthCheck checks whether current session is authenticated and returns user ID if so.
  56. func (app *App) HandleAuthCheck(w http.ResponseWriter, r *http.Request) {
  57. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  58. if err != nil {
  59. http.Error(w, err.Error(), http.StatusInternalServerError)
  60. return
  61. }
  62. userID, _ := session.Values["user_id"].(uint)
  63. email, _ := session.Values["email"].(string)
  64. w.WriteHeader(http.StatusOK)
  65. if err := app.sendUser(w, userID, email); err != nil {
  66. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  67. return
  68. }
  69. }
  70. // HandleLoginUser checks the request header for cookie and validates the user.
  71. func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
  72. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  73. if err != nil {
  74. app.handleErrorDataRead(err, w)
  75. return
  76. }
  77. form := &forms.LoginUserForm{}
  78. // decode from JSON to form value
  79. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  80. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  81. return
  82. }
  83. storedUser, readErr := app.Repo.User.ReadUserByEmail(form.Email)
  84. if readErr != nil {
  85. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  86. Errors: []string{"email not registered"},
  87. Code: http.StatusUnauthorized,
  88. }, w)
  89. return
  90. }
  91. if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(form.Password)); err != nil {
  92. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  93. Errors: []string{"incorrect password"},
  94. Code: http.StatusUnauthorized,
  95. }, w)
  96. return
  97. }
  98. redirect := session.Values["redirect"]
  99. // Set user as authenticated
  100. session.Values["authenticated"] = true
  101. session.Values["user_id"] = storedUser.ID
  102. session.Values["email"] = storedUser.Email
  103. session.Values["redirect"] = ""
  104. if err := session.Save(r, w); err != nil {
  105. app.Logger.Warn().Err(err)
  106. }
  107. if val, ok := redirect.(string); ok && val != "" {
  108. http.Redirect(w, r, val, 302)
  109. return
  110. }
  111. w.WriteHeader(http.StatusCreated)
  112. if err := app.sendUser(w, storedUser.ID, storedUser.Email); err != nil {
  113. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  114. return
  115. }
  116. }
  117. // HandleLogoutUser detaches the user from the session
  118. func (app *App) HandleLogoutUser(w http.ResponseWriter, r *http.Request) {
  119. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  120. if err != nil {
  121. app.handleErrorDataRead(err, w)
  122. }
  123. session.Values["authenticated"] = false
  124. session.Values["user_id"] = nil
  125. session.Values["email"] = nil
  126. session.Save(r, w)
  127. w.WriteHeader(http.StatusOK)
  128. }
  129. // HandleReadUser returns an externalized User (models.UserExternal)
  130. // based on an ID
  131. func (app *App) HandleReadUser(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. extUser := user.Externalize()
  138. if err := json.NewEncoder(w).Encode(extUser); err != nil {
  139. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  140. return
  141. }
  142. w.WriteHeader(http.StatusOK)
  143. }
  144. // HandleListUserProjects lists all projects belonging to a given user
  145. func (app *App) HandleListUserProjects(w http.ResponseWriter, r *http.Request) {
  146. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  147. if err != nil || id == 0 {
  148. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  149. return
  150. }
  151. projects, err := app.Repo.Project.ListProjectsByUserID(uint(id))
  152. if err != nil {
  153. app.handleErrorRead(err, ErrUserDataRead, w)
  154. }
  155. projectsExt := make([]*models.ProjectExternal, 0)
  156. for _, project := range projects {
  157. projectsExt = append(projectsExt, project.Externalize())
  158. }
  159. w.WriteHeader(http.StatusOK)
  160. if err := json.NewEncoder(w).Encode(projectsExt); err != nil {
  161. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  162. return
  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, "user_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, "user_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. }
  271. func (app *App) sendUser(w http.ResponseWriter, userID uint, email string) error {
  272. resUser := &models.UserExternal{
  273. ID: userID,
  274. Email: email,
  275. }
  276. if err := json.NewEncoder(w).Encode(resUser); err != nil {
  277. return err
  278. }
  279. return nil
  280. }