user_handler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. package api
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "math/rand"
  7. "net/http"
  8. "net/url"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "golang.org/x/crypto/bcrypt"
  13. "gorm.io/gorm"
  14. "github.com/go-chi/chi"
  15. "github.com/porter-dev/porter/internal/auth/token"
  16. "github.com/porter-dev/porter/internal/forms"
  17. "github.com/porter-dev/porter/internal/integrations/email"
  18. "github.com/porter-dev/porter/internal/models"
  19. "github.com/porter-dev/porter/internal/repository"
  20. )
  21. // Enumeration of user API error codes, represented as int64
  22. const (
  23. ErrUserDecode ErrorCode = iota + 600
  24. ErrUserValidateFields
  25. ErrUserDataRead
  26. )
  27. // HandleCreateUser validates a user form entry, converts the user to a gorm
  28. // model, and saves the user to the database
  29. func (app *App) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
  30. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  31. if err != nil {
  32. app.handleErrorDataRead(err, w)
  33. }
  34. form := &forms.CreateUserForm{}
  35. user, err := app.writeUser(
  36. form,
  37. app.Repo.User.CreateUser,
  38. w,
  39. r,
  40. doesUserExist,
  41. )
  42. if err == nil {
  43. app.Logger.Info().Msgf("New user created: %d", user.ID)
  44. var redirect string
  45. if valR := session.Values["redirect"]; valR != nil {
  46. redirect = session.Values["redirect"].(string)
  47. }
  48. session.Values["authenticated"] = true
  49. session.Values["user_id"] = user.ID
  50. session.Values["email"] = user.Email
  51. session.Values["redirect"] = ""
  52. session.Save(r, w)
  53. w.WriteHeader(http.StatusCreated)
  54. if err := app.sendUser(w, user.ID, user.Email, redirect); err != nil {
  55. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  56. return
  57. }
  58. }
  59. }
  60. // HandleAuthCheck checks whether current session is authenticated and returns user ID if so.
  61. func (app *App) HandleAuthCheck(w http.ResponseWriter, r *http.Request) {
  62. // first, check for token
  63. tok := app.getTokenFromRequest(r)
  64. if tok != nil {
  65. // read the user
  66. user, err := app.Repo.User.ReadUser(tok.IBy)
  67. if err != nil {
  68. http.Error(w, err.Error(), http.StatusInternalServerError)
  69. return
  70. }
  71. if err := app.sendUser(w, tok.IBy, user.Email, ""); err != nil {
  72. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  73. return
  74. }
  75. return
  76. }
  77. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  78. if err != nil {
  79. http.Error(w, err.Error(), http.StatusInternalServerError)
  80. return
  81. }
  82. userID, _ := session.Values["user_id"].(uint)
  83. email, _ := session.Values["email"].(string)
  84. w.WriteHeader(http.StatusOK)
  85. if err := app.sendUser(w, userID, email, ""); err != nil {
  86. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  87. return
  88. }
  89. }
  90. // HandleCLILoginUser verifies that a user is logged in, and generates an access
  91. // token for usage from the CLI
  92. func (app *App) HandleCLILoginUser(w http.ResponseWriter, r *http.Request) {
  93. queryParams, _ := url.ParseQuery(r.URL.RawQuery)
  94. redirect := queryParams["redirect"][0]
  95. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  96. if err != nil {
  97. http.Error(w, err.Error(), http.StatusInternalServerError)
  98. return
  99. }
  100. userID, _ := session.Values["user_id"].(uint)
  101. // generate the token
  102. jwt, err := token.GetTokenForUser(userID)
  103. if err != nil {
  104. app.handleErrorInternal(err, w)
  105. return
  106. }
  107. encoded, err := jwt.EncodeToken(&token.TokenGeneratorConf{
  108. TokenSecret: app.ServerConf.TokenGeneratorSecret,
  109. })
  110. if err != nil {
  111. app.handleErrorInternal(err, w)
  112. return
  113. }
  114. // generate 64 characters long authorization code
  115. const letters = "abcdefghijklmnopqrstuvwxyz123456789"
  116. code := make([]byte, 64)
  117. for i := range code {
  118. code[i] = letters[rand.Intn(len(letters))]
  119. }
  120. expiry := time.Now().Add(30 * time.Second)
  121. // create auth code object and send back authorization code
  122. authCode := &models.AuthCode{
  123. Token: encoded,
  124. AuthorizationCode: string(code),
  125. Expiry: &expiry,
  126. }
  127. authCode, err = app.Repo.AuthCode.CreateAuthCode(authCode)
  128. if err != nil {
  129. app.handleErrorInternal(err, w)
  130. return
  131. }
  132. http.Redirect(w, r, fmt.Sprintf("%s/?code=%s", redirect, url.QueryEscape(authCode.AuthorizationCode)), 302)
  133. }
  134. type ExchangeRequest struct {
  135. AuthorizationCode string `json:"authorization_code"`
  136. }
  137. type ExchangeResponse struct {
  138. Token string `json:"token"`
  139. }
  140. // HandleCLILoginExchangeToken exchanges an authorization code for a token
  141. func (app *App) HandleCLILoginExchangeToken(w http.ResponseWriter, r *http.Request) {
  142. // read the request body and look up the authorization token
  143. req := &ExchangeRequest{}
  144. if err := json.NewDecoder(r.Body).Decode(req); err != nil {
  145. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  146. return
  147. }
  148. authCode, err := app.Repo.AuthCode.ReadAuthCode(req.AuthorizationCode)
  149. if err != nil || authCode.IsExpired() {
  150. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  151. return
  152. }
  153. res := &ExchangeResponse{
  154. Token: authCode.Token,
  155. }
  156. w.WriteHeader(http.StatusOK)
  157. if err := json.NewEncoder(w).Encode(res); err != nil {
  158. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  159. return
  160. }
  161. }
  162. // HandleLoginUser checks the request header for cookie and validates the user.
  163. func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
  164. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  165. if err != nil {
  166. app.handleErrorDataRead(err, w)
  167. return
  168. }
  169. form := &forms.LoginUserForm{}
  170. // decode from JSON to form value
  171. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  172. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  173. return
  174. }
  175. storedUser, readErr := app.Repo.User.ReadUserByEmail(form.Email)
  176. if readErr != nil {
  177. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  178. Errors: []string{"email not registered"},
  179. Code: http.StatusUnauthorized,
  180. }, w)
  181. return
  182. }
  183. if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(form.Password)); err != nil {
  184. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  185. Errors: []string{"incorrect password"},
  186. Code: http.StatusUnauthorized,
  187. }, w)
  188. return
  189. }
  190. var redirect string
  191. if valR := session.Values["redirect"]; valR != nil {
  192. redirect = session.Values["redirect"].(string)
  193. }
  194. // Set user as authenticated
  195. session.Values["authenticated"] = true
  196. session.Values["user_id"] = storedUser.ID
  197. session.Values["email"] = storedUser.Email
  198. session.Values["redirect"] = ""
  199. if err := session.Save(r, w); err != nil {
  200. app.Logger.Warn().Err(err)
  201. }
  202. w.WriteHeader(http.StatusOK)
  203. if err := app.sendUser(w, storedUser.ID, storedUser.Email, redirect); err != nil {
  204. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  205. return
  206. }
  207. }
  208. // HandleLogoutUser detaches the user from the session
  209. func (app *App) HandleLogoutUser(w http.ResponseWriter, r *http.Request) {
  210. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  211. if err != nil {
  212. app.handleErrorDataRead(err, w)
  213. }
  214. session.Values["authenticated"] = false
  215. session.Values["user_id"] = nil
  216. session.Values["email"] = nil
  217. session.Save(r, w)
  218. w.WriteHeader(http.StatusOK)
  219. }
  220. // HandleReadUser returns an externalized User (models.UserExternal)
  221. // based on an ID
  222. func (app *App) HandleReadUser(w http.ResponseWriter, r *http.Request) {
  223. user, err := app.readUser(w, r)
  224. // error already handled by helper
  225. if err != nil {
  226. return
  227. }
  228. extUser := user.Externalize()
  229. if err := json.NewEncoder(w).Encode(extUser); err != nil {
  230. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  231. return
  232. }
  233. w.WriteHeader(http.StatusOK)
  234. }
  235. // HandleListUserProjects lists all projects belonging to a given user
  236. func (app *App) HandleListUserProjects(w http.ResponseWriter, r *http.Request) {
  237. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  238. if err != nil || id == 0 {
  239. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  240. return
  241. }
  242. projects, err := app.Repo.Project.ListProjectsByUserID(uint(id))
  243. if err != nil {
  244. app.handleErrorRead(err, ErrUserDataRead, w)
  245. }
  246. projectsExt := make([]*models.ProjectExternal, 0)
  247. for _, project := range projects {
  248. projectsExt = append(projectsExt, project.Externalize())
  249. }
  250. w.WriteHeader(http.StatusOK)
  251. if err := json.NewEncoder(w).Encode(projectsExt); err != nil {
  252. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  253. return
  254. }
  255. }
  256. // HandleDeleteUser removes a user after checking that the sent password is correct
  257. func (app *App) HandleDeleteUser(w http.ResponseWriter, r *http.Request) {
  258. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  259. if err != nil || id == 0 {
  260. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  261. return
  262. }
  263. // TODO -- HASH AND VERIFY PASSWORD BEFORE USER DELETION
  264. form := &forms.DeleteUserForm{
  265. ID: uint(id),
  266. }
  267. user, err := app.writeUser(form, app.Repo.User.DeleteUser, w, r)
  268. if err == nil {
  269. app.Logger.Info().Msgf("User deleted: %d", user.ID)
  270. w.WriteHeader(http.StatusNoContent)
  271. }
  272. }
  273. // InitiatePWResetUser initiates the password reset flow based on an email. The endpoint
  274. // checks if the email exists, but returns a 200 status code regardless, since we don't
  275. // want to leak in-use emails
  276. func (app *App) InitiatePWResetUser(w http.ResponseWriter, r *http.Request) {
  277. form := &forms.InitiateResetUserPasswordForm{}
  278. // decode from JSON to form value
  279. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  280. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  281. return
  282. }
  283. // validate the form
  284. if err := app.validator.Struct(form); err != nil {
  285. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  286. return
  287. }
  288. // check that the email exists; return 200 status code even if it doesn't
  289. _, err := app.Repo.User.ReadUserByEmail(form.Email)
  290. if err == gorm.ErrRecordNotFound {
  291. w.WriteHeader(http.StatusOK)
  292. return
  293. } else if err != nil {
  294. app.handleErrorDataRead(err, w)
  295. return
  296. }
  297. // convert the form to a project model
  298. pwReset, rawToken, err := form.ToPWResetToken()
  299. if err != nil {
  300. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  301. return
  302. }
  303. // handle write to the database
  304. pwReset, err = app.Repo.PWResetToken.CreatePWResetToken(pwReset)
  305. if err != nil {
  306. app.handleErrorDataWrite(err, w)
  307. return
  308. }
  309. queryVals := url.Values{
  310. "token": []string{rawToken},
  311. "email": []string{form.Email},
  312. "token_id": []string{fmt.Sprintf("%d", pwReset.ID)},
  313. }
  314. sgClient := email.SendgridClient{
  315. APIKey: app.ServerConf.SendgridAPIKey,
  316. PWResetTemplateID: app.ServerConf.SendgridPWResetTemplateID,
  317. SenderEmail: app.ServerConf.SendgridSenderEmail,
  318. }
  319. err = sgClient.SendPWResetEmail(
  320. fmt.Sprintf("%s/password/reset/finalize?%s", app.ServerConf.ServerURL, queryVals.Encode()),
  321. form.Email,
  322. )
  323. if err != nil {
  324. app.handleErrorInternal(err, w)
  325. return
  326. }
  327. w.WriteHeader(http.StatusOK)
  328. return
  329. }
  330. // VerifyPWResetUser makes sure that the token is correct and still valid
  331. func (app *App) VerifyPWResetUser(w http.ResponseWriter, r *http.Request) {
  332. form := &forms.VerifyResetUserPasswordForm{}
  333. // decode from JSON to form value
  334. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  335. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  336. return
  337. }
  338. // validate the form
  339. if err := app.validator.Struct(form); err != nil {
  340. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  341. return
  342. }
  343. token, err := app.Repo.PWResetToken.ReadPWResetToken(form.PWResetTokenID)
  344. if err != nil {
  345. w.WriteHeader(http.StatusForbidden)
  346. return
  347. }
  348. // make sure the token is still valid and has not expired
  349. if !token.IsValid || token.IsExpired() {
  350. w.WriteHeader(http.StatusForbidden)
  351. return
  352. }
  353. // check that the email matches
  354. if token.Email != form.Email {
  355. w.WriteHeader(http.StatusForbidden)
  356. return
  357. }
  358. // make sure the token is correct
  359. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  360. w.WriteHeader(http.StatusForbidden)
  361. return
  362. }
  363. w.WriteHeader(http.StatusOK)
  364. return
  365. }
  366. // FinalizPWResetUser completes the password reset flow based on an email.
  367. func (app *App) FinalizPWResetUser(w http.ResponseWriter, r *http.Request) {
  368. form := &forms.FinalizeResetUserPasswordForm{}
  369. // decode from JSON to form value
  370. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  371. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  372. return
  373. }
  374. // validate the form
  375. if err := app.validator.Struct(form); err != nil {
  376. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  377. return
  378. }
  379. // verify the token is valid
  380. token, err := app.Repo.PWResetToken.ReadPWResetToken(form.PWResetTokenID)
  381. if err != nil {
  382. w.WriteHeader(http.StatusForbidden)
  383. return
  384. }
  385. // make sure the token is still valid and has not expired
  386. if !token.IsValid || token.IsExpired() {
  387. w.WriteHeader(http.StatusForbidden)
  388. return
  389. }
  390. // check that the email matches
  391. if token.Email != form.Email {
  392. w.WriteHeader(http.StatusForbidden)
  393. return
  394. }
  395. // make sure the token is correct
  396. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  397. w.WriteHeader(http.StatusForbidden)
  398. return
  399. }
  400. // check that the email exists
  401. user, err := app.Repo.User.ReadUserByEmail(form.Email)
  402. if err != nil {
  403. w.WriteHeader(http.StatusForbidden)
  404. return
  405. }
  406. hashedPW, err := bcrypt.GenerateFromPassword([]byte(form.NewPassword), 8)
  407. if err != nil {
  408. app.handleErrorDataWrite(err, w)
  409. return
  410. }
  411. user.Password = string(hashedPW)
  412. user, err = app.Repo.User.UpdateUser(user)
  413. if err != nil {
  414. app.handleErrorDataWrite(err, w)
  415. return
  416. }
  417. // invalidate the token
  418. token.IsValid = false
  419. _, err = app.Repo.PWResetToken.UpdatePWResetToken(token)
  420. if err != nil {
  421. app.handleErrorDataWrite(err, w)
  422. return
  423. }
  424. w.WriteHeader(http.StatusOK)
  425. return
  426. }
  427. // ------------------------ User handler helper functions ------------------------ //
  428. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  429. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  430. // write to the database.
  431. func (app *App) writeUser(
  432. form forms.WriteUserForm,
  433. dbWrite repository.WriteUser,
  434. w http.ResponseWriter,
  435. r *http.Request,
  436. validators ...func(repo *repository.Repository, user *models.User) *HTTPError,
  437. ) (*models.User, error) {
  438. // decode from JSON to form value
  439. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  440. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  441. return nil, err
  442. }
  443. // validate the form
  444. if err := app.validator.Struct(form); err != nil {
  445. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  446. return nil, err
  447. }
  448. // convert the form to a user model -- WriteUserForm must implement ToUser
  449. userModel, err := form.ToUser(app.Repo.User)
  450. if err != nil {
  451. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  452. return nil, err
  453. }
  454. // Check any additional validators for any semantic errors
  455. // We have completed all syntax checks, so these will be sent
  456. // with http.StatusUnprocessableEntity (422), unless this is
  457. // an internal server error
  458. for _, validator := range validators {
  459. err := validator(app.Repo, userModel)
  460. if err != nil {
  461. goErr := errors.New(strings.Join(err.Errors, ", "))
  462. if err.Code == 500 {
  463. app.sendExternalError(
  464. goErr,
  465. http.StatusInternalServerError,
  466. *err,
  467. w,
  468. )
  469. } else {
  470. app.sendExternalError(
  471. goErr,
  472. http.StatusUnprocessableEntity,
  473. *err,
  474. w,
  475. )
  476. }
  477. return nil, goErr
  478. }
  479. }
  480. // handle write to the database
  481. user, err := dbWrite(userModel)
  482. if err != nil {
  483. app.handleErrorDataWrite(err, w)
  484. return nil, err
  485. }
  486. return user, nil
  487. }
  488. func (app *App) readUser(w http.ResponseWriter, r *http.Request) (*models.User, error) {
  489. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  490. if err != nil || id == 0 {
  491. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  492. return nil, err
  493. }
  494. user, err := app.Repo.User.ReadUser(uint(id))
  495. if err != nil {
  496. app.handleErrorRead(err, ErrUserDataRead, w)
  497. return nil, err
  498. }
  499. return user, nil
  500. }
  501. func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
  502. user, err := repo.User.ReadUserByEmail(user.Email)
  503. if user != nil && err == nil {
  504. return &HTTPError{
  505. Code: ErrUserValidateFields,
  506. Errors: []string{
  507. "email already taken",
  508. },
  509. }
  510. }
  511. if err != gorm.ErrRecordNotFound {
  512. return &ErrorDataRead
  513. }
  514. return nil
  515. }
  516. type SendUserExt struct {
  517. ID uint `json:"id"`
  518. Email string `json:"email"`
  519. Redirect string `json:"redirect,omitempty"`
  520. }
  521. func (app *App) sendUser(w http.ResponseWriter, userID uint, email, redirect string) error {
  522. resUser := &SendUserExt{
  523. ID: userID,
  524. Email: email,
  525. Redirect: redirect,
  526. }
  527. if err := json.NewEncoder(w).Encode(resUser); err != nil {
  528. return err
  529. }
  530. return nil
  531. }
  532. func (app *App) getUserIDFromRequest(r *http.Request) (uint, error) {
  533. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  534. if err != nil {
  535. return 0, err
  536. }
  537. // first, check for token
  538. tok := app.getTokenFromRequest(r)
  539. if tok != nil {
  540. return tok.IBy, nil
  541. }
  542. userID, _ := session.Values["user_id"].(uint)
  543. return userID, nil
  544. }