user_handler.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. package api
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "golang.org/x/crypto/bcrypt"
  12. "gorm.io/gorm"
  13. "github.com/go-chi/chi"
  14. "github.com/porter-dev/porter/internal/analytics"
  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. // if app can send email verification, set the email verified to false
  36. EmailVerified: !app.Capabilities.Email,
  37. }
  38. user, err := app.writeUser(
  39. form,
  40. app.Repo.User.CreateUser,
  41. w,
  42. r,
  43. doesUserExist,
  44. )
  45. if err == nil {
  46. // send to segment
  47. app.analyticsClient.Identify(analytics.CreateSegmentIdentifyUser(user))
  48. app.analyticsClient.Track(analytics.UserCreateTrack(&analytics.UserCreateTrackOpts{
  49. UserScopedTrackOpts: analytics.GetUserScopedTrackOpts(user.ID),
  50. }))
  51. app.Logger.Info().Msgf("New user created: %d", user.ID)
  52. // non-fatal email verification flow
  53. app.startEmailVerificationFlow(user)
  54. var redirect string
  55. if valR := session.Values["redirect"]; valR != nil {
  56. redirect = session.Values["redirect"].(string)
  57. }
  58. session.Values["authenticated"] = true
  59. session.Values["user_id"] = user.ID
  60. session.Values["email"] = user.Email
  61. session.Values["redirect"] = ""
  62. session.Save(r, w)
  63. w.WriteHeader(http.StatusCreated)
  64. if err := app.sendUser(w, user.ID, user.Email, false, redirect); err != nil {
  65. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  66. return
  67. }
  68. }
  69. }
  70. // HandleAuthCheck checks whether current session is authenticated and returns user ID if so.
  71. func (app *App) HandleAuthCheck(w http.ResponseWriter, r *http.Request) {
  72. // first, check for token
  73. tok := app.getTokenFromRequest(r)
  74. if tok != nil {
  75. // read the user
  76. user, err := app.Repo.User.ReadUser(tok.IBy)
  77. if err != nil {
  78. http.Error(w, err.Error(), http.StatusInternalServerError)
  79. return
  80. }
  81. if err := app.sendUser(w, tok.IBy, user.Email, user.EmailVerified, ""); err != nil {
  82. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  83. return
  84. }
  85. return
  86. }
  87. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  88. if err != nil {
  89. http.Error(w, err.Error(), http.StatusInternalServerError)
  90. return
  91. }
  92. userID, _ := session.Values["user_id"].(uint)
  93. email, _ := session.Values["email"].(string)
  94. user, err := app.Repo.User.ReadUser(userID)
  95. if err != nil {
  96. http.Error(w, err.Error(), http.StatusInternalServerError)
  97. return
  98. }
  99. w.WriteHeader(http.StatusOK)
  100. if err := app.sendUser(w, userID, email, user.EmailVerified, ""); err != nil {
  101. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  102. return
  103. }
  104. }
  105. // HandleCLILoginUser verifies that a user is logged in, and generates an access
  106. // token for usage from the CLI
  107. func (app *App) HandleCLILoginUser(w http.ResponseWriter, r *http.Request) {
  108. queryParams, _ := url.ParseQuery(r.URL.RawQuery)
  109. redirect := queryParams["redirect"][0]
  110. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  111. if err != nil {
  112. http.Error(w, err.Error(), http.StatusInternalServerError)
  113. return
  114. }
  115. userID, _ := session.Values["user_id"].(uint)
  116. // generate the token
  117. jwt, err := token.GetTokenForUser(userID)
  118. if err != nil {
  119. app.handleErrorInternal(err, w)
  120. return
  121. }
  122. encoded, err := jwt.EncodeToken(&token.TokenGeneratorConf{
  123. TokenSecret: app.ServerConf.TokenGeneratorSecret,
  124. })
  125. if err != nil {
  126. app.handleErrorInternal(err, w)
  127. return
  128. }
  129. // generate 64 characters long authorization code
  130. code, err := repository.GenerateRandomBytes(32)
  131. if err != nil {
  132. app.handleErrorInternal(err, w)
  133. return
  134. }
  135. expiry := time.Now().Add(30 * time.Second)
  136. // create auth code object and send back authorization code
  137. authCode := &models.AuthCode{
  138. Token: encoded,
  139. AuthorizationCode: code,
  140. Expiry: &expiry,
  141. }
  142. authCode, err = app.Repo.AuthCode.CreateAuthCode(authCode)
  143. if err != nil {
  144. app.handleErrorInternal(err, w)
  145. return
  146. }
  147. http.Redirect(w, r, fmt.Sprintf("%s/?code=%s", redirect, url.QueryEscape(authCode.AuthorizationCode)), 302)
  148. }
  149. type ExchangeRequest struct {
  150. AuthorizationCode string `json:"authorization_code"`
  151. }
  152. type ExchangeResponse struct {
  153. Token string `json:"token"`
  154. }
  155. // HandleCLILoginExchangeToken exchanges an authorization code for a token
  156. func (app *App) HandleCLILoginExchangeToken(w http.ResponseWriter, r *http.Request) {
  157. // read the request body and look up the authorization token
  158. req := &ExchangeRequest{}
  159. if err := json.NewDecoder(r.Body).Decode(req); err != nil {
  160. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  161. return
  162. }
  163. authCode, err := app.Repo.AuthCode.ReadAuthCode(req.AuthorizationCode)
  164. if err != nil || authCode.IsExpired() {
  165. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  166. return
  167. }
  168. res := &ExchangeResponse{
  169. Token: authCode.Token,
  170. }
  171. w.WriteHeader(http.StatusOK)
  172. if err := json.NewEncoder(w).Encode(res); err != nil {
  173. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  174. return
  175. }
  176. }
  177. // HandleLoginUser checks the request header for cookie and validates the user.
  178. func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
  179. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  180. if err != nil {
  181. app.handleErrorDataRead(err, w)
  182. return
  183. }
  184. form := &forms.LoginUserForm{}
  185. // decode from JSON to form value
  186. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  187. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  188. return
  189. }
  190. storedUser, readErr := app.Repo.User.ReadUserByEmail(form.Email)
  191. if readErr != nil {
  192. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  193. Errors: []string{"email not registered"},
  194. Code: http.StatusUnauthorized,
  195. }, w)
  196. return
  197. }
  198. if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(form.Password)); err != nil {
  199. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  200. Errors: []string{"incorrect password"},
  201. Code: http.StatusUnauthorized,
  202. }, w)
  203. return
  204. }
  205. var redirect string
  206. if valR := session.Values["redirect"]; valR != nil {
  207. redirect = session.Values["redirect"].(string)
  208. }
  209. // Set user as authenticated
  210. session.Values["authenticated"] = true
  211. session.Values["user_id"] = storedUser.ID
  212. session.Values["email"] = storedUser.Email
  213. session.Values["redirect"] = ""
  214. if err := session.Save(r, w); err != nil {
  215. app.Logger.Warn().Err(err)
  216. }
  217. w.WriteHeader(http.StatusOK)
  218. if err := app.sendUser(w, storedUser.ID, storedUser.Email, storedUser.EmailVerified, redirect); err != nil {
  219. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  220. return
  221. }
  222. }
  223. // HandleLogoutUser detaches the user from the session
  224. func (app *App) HandleLogoutUser(w http.ResponseWriter, r *http.Request) {
  225. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  226. if err != nil {
  227. app.handleErrorDataRead(err, w)
  228. }
  229. session.Values["authenticated"] = false
  230. session.Values["user_id"] = nil
  231. session.Values["email"] = nil
  232. session.Save(r, w)
  233. w.WriteHeader(http.StatusOK)
  234. }
  235. // HandleReadUser returns an externalized User (models.UserExternal)
  236. // based on an ID
  237. func (app *App) HandleReadUser(w http.ResponseWriter, r *http.Request) {
  238. user, err := app.readUser(w, r)
  239. // error already handled by helper
  240. if err != nil {
  241. return
  242. }
  243. extUser := user.Externalize()
  244. if err := json.NewEncoder(w).Encode(extUser); err != nil {
  245. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  246. return
  247. }
  248. w.WriteHeader(http.StatusOK)
  249. }
  250. // HandleListUserProjects lists all projects belonging to a given user
  251. func (app *App) HandleListUserProjects(w http.ResponseWriter, r *http.Request) {
  252. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  253. if err != nil || id == 0 {
  254. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  255. return
  256. }
  257. projects, err := app.Repo.Project.ListProjectsByUserID(uint(id))
  258. if err != nil {
  259. app.handleErrorRead(err, ErrUserDataRead, w)
  260. }
  261. projectsExt := make([]*models.ProjectExternal, 0)
  262. for _, project := range projects {
  263. projectsExt = append(projectsExt, project.Externalize())
  264. }
  265. w.WriteHeader(http.StatusOK)
  266. if err := json.NewEncoder(w).Encode(projectsExt); err != nil {
  267. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  268. return
  269. }
  270. }
  271. // HandleDeleteUser removes a user after checking that the sent password is correct
  272. func (app *App) HandleDeleteUser(w http.ResponseWriter, r *http.Request) {
  273. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  274. if err != nil || id == 0 {
  275. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  276. return
  277. }
  278. // TODO -- HASH AND VERIFY PASSWORD BEFORE USER DELETION
  279. form := &forms.DeleteUserForm{
  280. ID: uint(id),
  281. }
  282. user, err := app.writeUser(form, app.Repo.User.DeleteUser, w, r)
  283. if err == nil {
  284. app.Logger.Info().Msgf("User deleted: %d", user.ID)
  285. w.WriteHeader(http.StatusNoContent)
  286. }
  287. }
  288. // InitiateEmailVerifyUser initiates the email verification flow for a logged-in user
  289. func (app *App) InitiateEmailVerifyUser(w http.ResponseWriter, r *http.Request) {
  290. userID, err := app.getUserIDFromRequest(r)
  291. if err != nil {
  292. app.handleErrorInternal(err, w)
  293. return
  294. }
  295. user, err := app.Repo.User.ReadUser(userID)
  296. if err != nil {
  297. app.handleErrorInternal(err, w)
  298. return
  299. }
  300. err = app.startEmailVerificationFlow(user)
  301. if err != nil {
  302. app.handleErrorInternal(err, w)
  303. return
  304. }
  305. w.WriteHeader(http.StatusOK)
  306. }
  307. // FinalizEmailVerifyUser completes the email verification flow for a user.
  308. func (app *App) FinalizEmailVerifyUser(w http.ResponseWriter, r *http.Request) {
  309. userID, err := app.getUserIDFromRequest(r)
  310. if err != nil {
  311. app.handleErrorInternal(err, w)
  312. return
  313. }
  314. user, err := app.Repo.User.ReadUser(userID)
  315. if err != nil {
  316. app.handleErrorInternal(err, w)
  317. return
  318. }
  319. vals, err := url.ParseQuery(r.URL.RawQuery)
  320. if err != nil {
  321. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL"), 302)
  322. return
  323. }
  324. var tokenStr string
  325. var tokenID uint
  326. if tokenArr, ok := vals["token"]; ok && len(tokenArr) == 1 {
  327. tokenStr = tokenArr[0]
  328. } else {
  329. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL: token required"), 302)
  330. return
  331. }
  332. if tokenIDArr, ok := vals["token_id"]; ok && len(tokenIDArr) == 1 {
  333. id, err := strconv.ParseUint(tokenIDArr[0], 10, 64)
  334. if err != nil {
  335. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL: valid token id required"), 302)
  336. return
  337. }
  338. tokenID = uint(id)
  339. } else {
  340. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL: valid token id required"), 302)
  341. return
  342. }
  343. // verify the token is valid
  344. token, err := app.Repo.PWResetToken.ReadPWResetToken(tokenID)
  345. if err != nil {
  346. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Email verification error: valid token required"), 302)
  347. return
  348. }
  349. // make sure the token is still valid and has not expired
  350. if !token.IsValid || token.IsExpired() {
  351. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Email verification error: valid token required"), 302)
  352. return
  353. }
  354. // make sure the token is correct
  355. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(tokenStr)); err != nil {
  356. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Email verification error: valid token required"), 302)
  357. return
  358. }
  359. user.EmailVerified = true
  360. user, err = app.Repo.User.UpdateUser(user)
  361. if err != nil {
  362. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Could not verify email address"), 302)
  363. return
  364. }
  365. // invalidate the token
  366. token.IsValid = false
  367. _, err = app.Repo.PWResetToken.UpdatePWResetToken(token)
  368. if err != nil {
  369. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Could not verify email address"), 302)
  370. return
  371. }
  372. http.Redirect(w, r, "/dashboard", 302)
  373. return
  374. }
  375. // InitiatePWResetUser initiates the password reset flow based on an email. The endpoint
  376. // checks if the email exists, but returns a 200 status code regardless, since we don't
  377. // want to leak in-use emails
  378. func (app *App) InitiatePWResetUser(w http.ResponseWriter, r *http.Request) {
  379. form := &forms.InitiateResetUserPasswordForm{}
  380. // decode from JSON to form value
  381. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  382. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  383. return
  384. }
  385. // validate the form
  386. if err := app.validator.Struct(form); err != nil {
  387. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  388. return
  389. }
  390. // check that the email exists; return 200 status code even if it doesn't
  391. user, err := app.Repo.User.ReadUserByEmail(form.Email)
  392. if err == gorm.ErrRecordNotFound {
  393. w.WriteHeader(http.StatusOK)
  394. return
  395. } else if err != nil {
  396. app.handleErrorDataRead(err, w)
  397. return
  398. }
  399. // if the user is a Github user, send them a Github email
  400. if user.GithubUserID != 0 {
  401. sgClient := email.SendgridClient{
  402. APIKey: app.ServerConf.SendgridAPIKey,
  403. PWGHTemplateID: app.ServerConf.SendgridPWGHTemplateID,
  404. SenderEmail: app.ServerConf.SendgridSenderEmail,
  405. }
  406. err = sgClient.SendGHPWEmail(
  407. fmt.Sprintf("%s/api/oauth/login/github", app.ServerConf.ServerURL),
  408. form.Email,
  409. )
  410. if err != nil {
  411. app.handleErrorInternal(err, w)
  412. return
  413. }
  414. w.WriteHeader(http.StatusOK)
  415. return
  416. }
  417. // convert the form to a project model
  418. pwReset, rawToken, err := form.ToPWResetToken()
  419. if err != nil {
  420. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  421. return
  422. }
  423. // handle write to the database
  424. pwReset, err = app.Repo.PWResetToken.CreatePWResetToken(pwReset)
  425. if err != nil {
  426. app.handleErrorDataWrite(err, w)
  427. return
  428. }
  429. queryVals := url.Values{
  430. "token": []string{rawToken},
  431. "email": []string{form.Email},
  432. "token_id": []string{fmt.Sprintf("%d", pwReset.ID)},
  433. }
  434. sgClient := email.SendgridClient{
  435. APIKey: app.ServerConf.SendgridAPIKey,
  436. PWResetTemplateID: app.ServerConf.SendgridPWResetTemplateID,
  437. SenderEmail: app.ServerConf.SendgridSenderEmail,
  438. }
  439. err = sgClient.SendPWResetEmail(
  440. fmt.Sprintf("%s/password/reset/finalize?%s", app.ServerConf.ServerURL, queryVals.Encode()),
  441. form.Email,
  442. )
  443. if err != nil {
  444. app.handleErrorInternal(err, w)
  445. return
  446. }
  447. w.WriteHeader(http.StatusOK)
  448. return
  449. }
  450. // VerifyPWResetUser makes sure that the token is correct and still valid
  451. func (app *App) VerifyPWResetUser(w http.ResponseWriter, r *http.Request) {
  452. form := &forms.VerifyResetUserPasswordForm{}
  453. // decode from JSON to form value
  454. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  455. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  456. return
  457. }
  458. // validate the form
  459. if err := app.validator.Struct(form); err != nil {
  460. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  461. return
  462. }
  463. token, err := app.Repo.PWResetToken.ReadPWResetToken(form.PWResetTokenID)
  464. if err != nil {
  465. w.WriteHeader(http.StatusForbidden)
  466. return
  467. }
  468. // make sure the token is still valid and has not expired
  469. if !token.IsValid || token.IsExpired() {
  470. w.WriteHeader(http.StatusForbidden)
  471. return
  472. }
  473. // check that the email matches
  474. if token.Email != form.Email {
  475. w.WriteHeader(http.StatusForbidden)
  476. return
  477. }
  478. // make sure the token is correct
  479. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  480. w.WriteHeader(http.StatusForbidden)
  481. return
  482. }
  483. w.WriteHeader(http.StatusOK)
  484. return
  485. }
  486. // FinalizPWResetUser completes the password reset flow based on an email.
  487. func (app *App) FinalizPWResetUser(w http.ResponseWriter, r *http.Request) {
  488. form := &forms.FinalizeResetUserPasswordForm{}
  489. // decode from JSON to form value
  490. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  491. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  492. return
  493. }
  494. // validate the form
  495. if err := app.validator.Struct(form); err != nil {
  496. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  497. return
  498. }
  499. // verify the token is valid
  500. token, err := app.Repo.PWResetToken.ReadPWResetToken(form.PWResetTokenID)
  501. if err != nil {
  502. w.WriteHeader(http.StatusForbidden)
  503. return
  504. }
  505. // make sure the token is still valid and has not expired
  506. if !token.IsValid || token.IsExpired() {
  507. w.WriteHeader(http.StatusForbidden)
  508. return
  509. }
  510. // check that the email matches
  511. if token.Email != form.Email {
  512. w.WriteHeader(http.StatusForbidden)
  513. return
  514. }
  515. // make sure the token is correct
  516. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  517. w.WriteHeader(http.StatusForbidden)
  518. return
  519. }
  520. // check that the email exists
  521. user, err := app.Repo.User.ReadUserByEmail(form.Email)
  522. if err != nil {
  523. w.WriteHeader(http.StatusForbidden)
  524. return
  525. }
  526. hashedPW, err := bcrypt.GenerateFromPassword([]byte(form.NewPassword), 8)
  527. if err != nil {
  528. app.handleErrorDataWrite(err, w)
  529. return
  530. }
  531. user.Password = string(hashedPW)
  532. user, err = app.Repo.User.UpdateUser(user)
  533. if err != nil {
  534. app.handleErrorDataWrite(err, w)
  535. return
  536. }
  537. // invalidate the token
  538. token.IsValid = false
  539. _, err = app.Repo.PWResetToken.UpdatePWResetToken(token)
  540. if err != nil {
  541. app.handleErrorDataWrite(err, w)
  542. return
  543. }
  544. w.WriteHeader(http.StatusOK)
  545. return
  546. }
  547. // ------------------------ User handler helper functions ------------------------ //
  548. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  549. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  550. // write to the database.
  551. func (app *App) writeUser(
  552. form forms.WriteUserForm,
  553. dbWrite repository.WriteUser,
  554. w http.ResponseWriter,
  555. r *http.Request,
  556. validators ...func(repo *repository.Repository, user *models.User) *HTTPError,
  557. ) (*models.User, error) {
  558. // decode from JSON to form value
  559. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  560. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  561. return nil, err
  562. }
  563. // validate the form
  564. if err := app.validator.Struct(form); err != nil {
  565. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  566. return nil, err
  567. }
  568. // convert the form to a user model -- WriteUserForm must implement ToUser
  569. userModel, err := form.ToUser(app.Repo.User)
  570. if err != nil {
  571. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  572. return nil, err
  573. }
  574. // Check any additional validators for any semantic errors
  575. // We have completed all syntax checks, so these will be sent
  576. // with http.StatusUnprocessableEntity (422), unless this is
  577. // an internal server error
  578. for _, validator := range validators {
  579. err := validator(app.Repo, userModel)
  580. if err != nil {
  581. goErr := errors.New(strings.Join(err.Errors, ", "))
  582. if err.Code == 500 {
  583. app.sendExternalError(
  584. goErr,
  585. http.StatusInternalServerError,
  586. *err,
  587. w,
  588. )
  589. } else {
  590. app.sendExternalError(
  591. goErr,
  592. http.StatusUnprocessableEntity,
  593. *err,
  594. w,
  595. )
  596. }
  597. return nil, goErr
  598. }
  599. }
  600. // handle write to the database
  601. user, err := dbWrite(userModel)
  602. if err != nil {
  603. app.handleErrorDataWrite(err, w)
  604. return nil, err
  605. }
  606. return user, nil
  607. }
  608. func (app *App) readUser(w http.ResponseWriter, r *http.Request) (*models.User, error) {
  609. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  610. if err != nil || id == 0 {
  611. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  612. return nil, err
  613. }
  614. user, err := app.Repo.User.ReadUser(uint(id))
  615. if err != nil {
  616. app.handleErrorRead(err, ErrUserDataRead, w)
  617. return nil, err
  618. }
  619. return user, nil
  620. }
  621. func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
  622. user, err := repo.User.ReadUserByEmail(user.Email)
  623. if user != nil && err == nil {
  624. return &HTTPError{
  625. Code: ErrUserValidateFields,
  626. Errors: []string{
  627. "email already taken",
  628. },
  629. }
  630. }
  631. if err != gorm.ErrRecordNotFound {
  632. return &ErrorDataRead
  633. }
  634. return nil
  635. }
  636. type SendUserExt struct {
  637. ID uint `json:"id"`
  638. Email string `json:"email"`
  639. EmailVerified bool `json:"email_verified"`
  640. Redirect string `json:"redirect,omitempty"`
  641. }
  642. func (app *App) sendUser(w http.ResponseWriter, userID uint, email string, emailVerified bool, redirect string) error {
  643. resUser := &SendUserExt{
  644. ID: userID,
  645. Email: email,
  646. EmailVerified: emailVerified,
  647. Redirect: redirect,
  648. }
  649. if err := json.NewEncoder(w).Encode(resUser); err != nil {
  650. return err
  651. }
  652. return nil
  653. }
  654. func (app *App) getUserIDFromRequest(r *http.Request) (uint, error) {
  655. // first, check for token
  656. tok := app.getTokenFromRequest(r)
  657. if tok != nil {
  658. return tok.IBy, nil
  659. }
  660. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  661. if err != nil {
  662. return 0, fmt.Errorf("could not get session: %s", err.Error())
  663. }
  664. sessID, ok := session.Values["user_id"]
  665. if !ok {
  666. return 0, fmt.Errorf("could not get user id from session")
  667. }
  668. userID, ok := sessID.(uint)
  669. if !ok {
  670. return 0, fmt.Errorf("could not get user id from session")
  671. }
  672. return userID, nil
  673. }
  674. func (app *App) startEmailVerificationFlow(user *models.User) error {
  675. form := &forms.InitiateResetUserPasswordForm{
  676. Email: user.Email,
  677. }
  678. // convert the form to a pw reset token model
  679. pwReset, rawToken, err := form.ToPWResetToken()
  680. if err != nil {
  681. return err
  682. }
  683. // handle write to the database
  684. pwReset, err = app.Repo.PWResetToken.CreatePWResetToken(pwReset)
  685. if err != nil {
  686. return err
  687. }
  688. queryVals := url.Values{
  689. "token": []string{rawToken},
  690. "token_id": []string{fmt.Sprintf("%d", pwReset.ID)},
  691. }
  692. sgClient := email.SendgridClient{
  693. APIKey: app.ServerConf.SendgridAPIKey,
  694. VerifyEmailTemplateID: app.ServerConf.SendgridVerifyEmailTemplateID,
  695. SenderEmail: app.ServerConf.SendgridSenderEmail,
  696. }
  697. return sgClient.SendEmailVerification(
  698. fmt.Sprintf("%s/api/email/verify/finalize?%s", app.ServerConf.ServerURL, queryVals.Encode()),
  699. form.Email,
  700. )
  701. }