user_handler.go 22 KB

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