user_handler.go 22 KB

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