user_handler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. }
  313. sgClient := email.SendgridClient{
  314. APIKey: app.ServerConf.SendgridAPIKey,
  315. PWResetTemplateID: app.ServerConf.SendgridPWResetTemplateID,
  316. SenderEmail: app.ServerConf.SendgridSenderEmail,
  317. }
  318. err = sgClient.SendPWResetEmail(
  319. fmt.Sprintf("https://%s/auth/reset?%s", app.ServerConf.ServerURL, queryVals.Encode()),
  320. form.Email,
  321. )
  322. if err != nil {
  323. app.handleErrorInternal(err, w)
  324. return
  325. }
  326. w.WriteHeader(http.StatusOK)
  327. return
  328. }
  329. // VerifyPWResetUser makes sure that the token is correct and still valid
  330. func (app *App) VerifyPWResetUser(w http.ResponseWriter, r *http.Request) {
  331. form := &forms.VerifyResetUserPasswordForm{}
  332. // decode from JSON to form value
  333. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  334. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  335. return
  336. }
  337. // validate the form
  338. if err := app.validator.Struct(form); err != nil {
  339. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  340. return
  341. }
  342. token, err := app.Repo.PWResetToken.ReadPWResetToken(form.PWResetTokenID)
  343. if err != nil {
  344. w.WriteHeader(http.StatusForbidden)
  345. return
  346. }
  347. // make sure the token is still valid and has not expired
  348. if !token.IsValid || token.IsExpired() {
  349. w.WriteHeader(http.StatusForbidden)
  350. return
  351. }
  352. // check that the email matches
  353. if token.Email != form.Email {
  354. w.WriteHeader(http.StatusForbidden)
  355. return
  356. }
  357. // make sure the token is correct
  358. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  359. w.WriteHeader(http.StatusForbidden)
  360. return
  361. }
  362. w.WriteHeader(http.StatusOK)
  363. return
  364. }
  365. // FinalizPWResetUser completes the password reset flow based on an email.
  366. func (app *App) FinalizPWResetUser(w http.ResponseWriter, r *http.Request) {
  367. form := &forms.FinalizeResetUserPasswordForm{}
  368. // decode from JSON to form value
  369. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  370. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  371. return
  372. }
  373. // validate the form
  374. if err := app.validator.Struct(form); err != nil {
  375. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  376. return
  377. }
  378. // verify the token is valid
  379. token, err := app.Repo.PWResetToken.ReadPWResetToken(form.PWResetTokenID)
  380. if err != nil {
  381. w.WriteHeader(http.StatusForbidden)
  382. return
  383. }
  384. // make sure the token is still valid and has not expired
  385. if !token.IsValid || token.IsExpired() {
  386. w.WriteHeader(http.StatusForbidden)
  387. return
  388. }
  389. // check that the email matches
  390. if token.Email != form.Email {
  391. w.WriteHeader(http.StatusForbidden)
  392. return
  393. }
  394. // make sure the token is correct
  395. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  396. w.WriteHeader(http.StatusForbidden)
  397. return
  398. }
  399. // check that the email exists
  400. user, err := app.Repo.User.ReadUserByEmail(form.Email)
  401. if err != nil {
  402. w.WriteHeader(http.StatusForbidden)
  403. return
  404. }
  405. hashedPW, err := bcrypt.GenerateFromPassword([]byte(user.Password), 8)
  406. if err != nil {
  407. app.handleErrorDataWrite(err, w)
  408. return
  409. }
  410. user.Password = string(hashedPW)
  411. user, err = app.Repo.User.UpdateUser(user)
  412. if err != nil {
  413. app.handleErrorDataWrite(err, w)
  414. return
  415. }
  416. // invalidate the token
  417. token.IsValid = false
  418. _, err = app.Repo.PWResetToken.UpdatePWResetToken(token)
  419. if err != nil {
  420. app.handleErrorDataWrite(err, w)
  421. return
  422. }
  423. w.WriteHeader(http.StatusOK)
  424. return
  425. }
  426. // ------------------------ User handler helper functions ------------------------ //
  427. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  428. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  429. // write to the database.
  430. func (app *App) writeUser(
  431. form forms.WriteUserForm,
  432. dbWrite repository.WriteUser,
  433. w http.ResponseWriter,
  434. r *http.Request,
  435. validators ...func(repo *repository.Repository, user *models.User) *HTTPError,
  436. ) (*models.User, error) {
  437. // decode from JSON to form value
  438. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  439. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  440. return nil, err
  441. }
  442. // validate the form
  443. if err := app.validator.Struct(form); err != nil {
  444. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  445. return nil, err
  446. }
  447. // convert the form to a user model -- WriteUserForm must implement ToUser
  448. userModel, err := form.ToUser(app.Repo.User)
  449. if err != nil {
  450. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  451. return nil, err
  452. }
  453. // Check any additional validators for any semantic errors
  454. // We have completed all syntax checks, so these will be sent
  455. // with http.StatusUnprocessableEntity (422), unless this is
  456. // an internal server error
  457. for _, validator := range validators {
  458. err := validator(app.Repo, userModel)
  459. if err != nil {
  460. goErr := errors.New(strings.Join(err.Errors, ", "))
  461. if err.Code == 500 {
  462. app.sendExternalError(
  463. goErr,
  464. http.StatusInternalServerError,
  465. *err,
  466. w,
  467. )
  468. } else {
  469. app.sendExternalError(
  470. goErr,
  471. http.StatusUnprocessableEntity,
  472. *err,
  473. w,
  474. )
  475. }
  476. return nil, goErr
  477. }
  478. }
  479. // handle write to the database
  480. user, err := dbWrite(userModel)
  481. if err != nil {
  482. app.handleErrorDataWrite(err, w)
  483. return nil, err
  484. }
  485. return user, nil
  486. }
  487. func (app *App) readUser(w http.ResponseWriter, r *http.Request) (*models.User, error) {
  488. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  489. if err != nil || id == 0 {
  490. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  491. return nil, err
  492. }
  493. user, err := app.Repo.User.ReadUser(uint(id))
  494. if err != nil {
  495. app.handleErrorRead(err, ErrUserDataRead, w)
  496. return nil, err
  497. }
  498. return user, nil
  499. }
  500. func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
  501. user, err := repo.User.ReadUserByEmail(user.Email)
  502. if user != nil && err == nil {
  503. return &HTTPError{
  504. Code: ErrUserValidateFields,
  505. Errors: []string{
  506. "email already taken",
  507. },
  508. }
  509. }
  510. if err != gorm.ErrRecordNotFound {
  511. return &ErrorDataRead
  512. }
  513. return nil
  514. }
  515. type SendUserExt struct {
  516. ID uint `json:"id"`
  517. Email string `json:"email"`
  518. Redirect string `json:"redirect,omitempty"`
  519. }
  520. func (app *App) sendUser(w http.ResponseWriter, userID uint, email, redirect string) error {
  521. resUser := &SendUserExt{
  522. ID: userID,
  523. Email: email,
  524. Redirect: redirect,
  525. }
  526. if err := json.NewEncoder(w).Encode(resUser); err != nil {
  527. return err
  528. }
  529. return nil
  530. }
  531. func (app *App) getUserIDFromRequest(r *http.Request) (uint, error) {
  532. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  533. if err != nil {
  534. return 0, err
  535. }
  536. // first, check for token
  537. tok := app.getTokenFromRequest(r)
  538. if tok != nil {
  539. return tok.IBy, nil
  540. }
  541. userID, _ := session.Values["user_id"].(uint)
  542. return userID, nil
  543. }