user_handler.go 9.1 KB

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