user_handler.go 8.7 KB

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