user_handler.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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. // FinalizeEmailVerifyUser completes the email verification flow for a user.
  309. func (app *App) FinalizeEmailVerifyUser(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. app.AnalyticsClient.Track(analytics.UserVerifyEmailTrack(&analytics.UserVerifyEmailTrackOpts{
  374. UserScopedTrackOpts: analytics.GetUserScopedTrackOpts(user.ID),
  375. Email: user.Email,
  376. }))
  377. http.Redirect(w, r, "/dashboard", 302)
  378. return
  379. }
  380. // InitiatePWResetUser initiates the password reset flow based on an email. The endpoint
  381. // checks if the email exists, but returns a 200 status code regardless, since we don't
  382. // want to leak in-use emails
  383. func (app *App) InitiatePWResetUser(w http.ResponseWriter, r *http.Request) {
  384. form := &forms.InitiateResetUserPasswordForm{}
  385. // decode from JSON to form value
  386. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  387. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  388. return
  389. }
  390. // validate the form
  391. if err := app.validator.Struct(form); err != nil {
  392. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  393. return
  394. }
  395. // check that the email exists; return 200 status code even if it doesn't
  396. user, err := app.Repo.User.ReadUserByEmail(form.Email)
  397. if err == gorm.ErrRecordNotFound {
  398. w.WriteHeader(http.StatusOK)
  399. return
  400. } else if err != nil {
  401. app.handleErrorDataRead(err, w)
  402. return
  403. }
  404. // if the user is a Github user, send them a Github email
  405. if user.GithubUserID != 0 {
  406. sgClient := email.SendgridClient{
  407. APIKey: app.ServerConf.SendgridAPIKey,
  408. PWGHTemplateID: app.ServerConf.SendgridPWGHTemplateID,
  409. SenderEmail: app.ServerConf.SendgridSenderEmail,
  410. }
  411. err = sgClient.SendGHPWEmail(
  412. fmt.Sprintf("%s/api/oauth/login/github", app.ServerConf.ServerURL),
  413. form.Email,
  414. )
  415. if err != nil {
  416. app.handleErrorInternal(err, w)
  417. return
  418. }
  419. w.WriteHeader(http.StatusOK)
  420. return
  421. }
  422. // convert the form to a project model
  423. pwReset, rawToken, err := form.ToPWResetToken()
  424. if err != nil {
  425. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  426. return
  427. }
  428. // handle write to the database
  429. pwReset, err = app.Repo.PWResetToken.CreatePWResetToken(pwReset)
  430. if err != nil {
  431. app.handleErrorDataWrite(err, w)
  432. return
  433. }
  434. queryVals := url.Values{
  435. "token": []string{rawToken},
  436. "email": []string{form.Email},
  437. "token_id": []string{fmt.Sprintf("%d", pwReset.ID)},
  438. }
  439. sgClient := email.SendgridClient{
  440. APIKey: app.ServerConf.SendgridAPIKey,
  441. PWResetTemplateID: app.ServerConf.SendgridPWResetTemplateID,
  442. SenderEmail: app.ServerConf.SendgridSenderEmail,
  443. }
  444. err = sgClient.SendPWResetEmail(
  445. fmt.Sprintf("%s/password/reset/finalize?%s", app.ServerConf.ServerURL, queryVals.Encode()),
  446. form.Email,
  447. )
  448. if err != nil {
  449. app.handleErrorInternal(err, w)
  450. return
  451. }
  452. w.WriteHeader(http.StatusOK)
  453. return
  454. }
  455. // VerifyPWResetUser makes sure that the token is correct and still valid
  456. func (app *App) VerifyPWResetUser(w http.ResponseWriter, r *http.Request) {
  457. form := &forms.VerifyResetUserPasswordForm{}
  458. // decode from JSON to form value
  459. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  460. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  461. return
  462. }
  463. // validate the form
  464. if err := app.validator.Struct(form); err != nil {
  465. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  466. return
  467. }
  468. token, err := app.Repo.PWResetToken.ReadPWResetToken(form.PWResetTokenID)
  469. if err != nil {
  470. w.WriteHeader(http.StatusForbidden)
  471. return
  472. }
  473. // make sure the token is still valid and has not expired
  474. if !token.IsValid || token.IsExpired() {
  475. w.WriteHeader(http.StatusForbidden)
  476. return
  477. }
  478. // check that the email matches
  479. if token.Email != form.Email {
  480. w.WriteHeader(http.StatusForbidden)
  481. return
  482. }
  483. // make sure the token is correct
  484. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  485. w.WriteHeader(http.StatusForbidden)
  486. return
  487. }
  488. w.WriteHeader(http.StatusOK)
  489. return
  490. }
  491. // FinalizPWResetUser completes the password reset flow based on an email.
  492. func (app *App) FinalizPWResetUser(w http.ResponseWriter, r *http.Request) {
  493. form := &forms.FinalizeResetUserPasswordForm{}
  494. // decode from JSON to form value
  495. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  496. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  497. return
  498. }
  499. // validate the form
  500. if err := app.validator.Struct(form); err != nil {
  501. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  502. return
  503. }
  504. // verify the token is valid
  505. token, err := app.Repo.PWResetToken.ReadPWResetToken(form.PWResetTokenID)
  506. if err != nil {
  507. w.WriteHeader(http.StatusForbidden)
  508. return
  509. }
  510. // make sure the token is still valid and has not expired
  511. if !token.IsValid || token.IsExpired() {
  512. w.WriteHeader(http.StatusForbidden)
  513. return
  514. }
  515. // check that the email matches
  516. if token.Email != form.Email {
  517. w.WriteHeader(http.StatusForbidden)
  518. return
  519. }
  520. // make sure the token is correct
  521. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  522. w.WriteHeader(http.StatusForbidden)
  523. return
  524. }
  525. // check that the email exists
  526. user, err := app.Repo.User.ReadUserByEmail(form.Email)
  527. if err != nil {
  528. w.WriteHeader(http.StatusForbidden)
  529. return
  530. }
  531. hashedPW, err := bcrypt.GenerateFromPassword([]byte(form.NewPassword), 8)
  532. if err != nil {
  533. app.handleErrorDataWrite(err, w)
  534. return
  535. }
  536. user.Password = string(hashedPW)
  537. user, err = app.Repo.User.UpdateUser(user)
  538. if err != nil {
  539. app.handleErrorDataWrite(err, w)
  540. return
  541. }
  542. // invalidate the token
  543. token.IsValid = false
  544. _, err = app.Repo.PWResetToken.UpdatePWResetToken(token)
  545. if err != nil {
  546. app.handleErrorDataWrite(err, w)
  547. return
  548. }
  549. w.WriteHeader(http.StatusOK)
  550. return
  551. }
  552. // ------------------------ User handler helper functions ------------------------ //
  553. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  554. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  555. // write to the database.
  556. func (app *App) writeUser(
  557. form forms.WriteUserForm,
  558. dbWrite repository.WriteUser,
  559. w http.ResponseWriter,
  560. r *http.Request,
  561. validators ...func(repo *repository.Repository, user *models.User) *HTTPError,
  562. ) (*models.User, error) {
  563. // decode from JSON to form value
  564. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  565. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  566. return nil, err
  567. }
  568. // validate the form
  569. if err := app.validator.Struct(form); err != nil {
  570. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  571. return nil, err
  572. }
  573. // convert the form to a user model -- WriteUserForm must implement ToUser
  574. userModel, err := form.ToUser(app.Repo.User)
  575. if err != nil {
  576. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  577. return nil, err
  578. }
  579. // Check any additional validators for any semantic errors
  580. // We have completed all syntax checks, so these will be sent
  581. // with http.StatusUnprocessableEntity (422), unless this is
  582. // an internal server error
  583. for _, validator := range validators {
  584. err := validator(app.Repo, userModel)
  585. if err != nil {
  586. goErr := errors.New(strings.Join(err.Errors, ", "))
  587. if err.Code == 500 {
  588. app.sendExternalError(
  589. goErr,
  590. http.StatusInternalServerError,
  591. *err,
  592. w,
  593. )
  594. } else {
  595. app.sendExternalError(
  596. goErr,
  597. http.StatusUnprocessableEntity,
  598. *err,
  599. w,
  600. )
  601. }
  602. return nil, goErr
  603. }
  604. }
  605. // handle write to the database
  606. user, err := dbWrite(userModel)
  607. if err != nil {
  608. app.handleErrorDataWrite(err, w)
  609. return nil, err
  610. }
  611. return user, nil
  612. }
  613. func (app *App) readUser(w http.ResponseWriter, r *http.Request) (*models.User, error) {
  614. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  615. if err != nil || id == 0 {
  616. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  617. return nil, err
  618. }
  619. user, err := app.Repo.User.ReadUser(uint(id))
  620. if err != nil {
  621. app.handleErrorRead(err, ErrUserDataRead, w)
  622. return nil, err
  623. }
  624. return user, nil
  625. }
  626. func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
  627. user, err := repo.User.ReadUserByEmail(user.Email)
  628. if user != nil && err == nil {
  629. return &HTTPError{
  630. Code: ErrUserValidateFields,
  631. Errors: []string{
  632. "email already taken",
  633. },
  634. }
  635. }
  636. if err != gorm.ErrRecordNotFound {
  637. return &ErrorDataRead
  638. }
  639. return nil
  640. }
  641. type SendUserExt struct {
  642. ID uint `json:"id"`
  643. Email string `json:"email"`
  644. EmailVerified bool `json:"email_verified"`
  645. Redirect string `json:"redirect,omitempty"`
  646. }
  647. func (app *App) sendUser(w http.ResponseWriter, userID uint, email string, emailVerified bool, redirect string) error {
  648. resUser := &SendUserExt{
  649. ID: userID,
  650. Email: email,
  651. EmailVerified: emailVerified,
  652. Redirect: redirect,
  653. }
  654. if err := json.NewEncoder(w).Encode(resUser); err != nil {
  655. return err
  656. }
  657. return nil
  658. }
  659. func (app *App) getUserIDFromRequest(r *http.Request) (uint, error) {
  660. // first, check for token
  661. tok := app.getTokenFromRequest(r)
  662. if tok != nil {
  663. return tok.IBy, nil
  664. }
  665. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  666. if err != nil {
  667. return 0, fmt.Errorf("could not get session: %s", err.Error())
  668. }
  669. sessID, ok := session.Values["user_id"]
  670. if !ok {
  671. return 0, fmt.Errorf("could not get user id from session")
  672. }
  673. userID, ok := sessID.(uint)
  674. if !ok {
  675. return 0, fmt.Errorf("could not get user id from session")
  676. }
  677. return userID, nil
  678. }
  679. func (app *App) startEmailVerificationFlow(user *models.User) error {
  680. form := &forms.InitiateResetUserPasswordForm{
  681. Email: user.Email,
  682. }
  683. // convert the form to a pw reset token model
  684. pwReset, rawToken, err := form.ToPWResetToken()
  685. if err != nil {
  686. return err
  687. }
  688. // handle write to the database
  689. pwReset, err = app.Repo.PWResetToken.CreatePWResetToken(pwReset)
  690. if err != nil {
  691. return err
  692. }
  693. queryVals := url.Values{
  694. "token": []string{rawToken},
  695. "token_id": []string{fmt.Sprintf("%d", pwReset.ID)},
  696. }
  697. sgClient := email.SendgridClient{
  698. APIKey: app.ServerConf.SendgridAPIKey,
  699. VerifyEmailTemplateID: app.ServerConf.SendgridVerifyEmailTemplateID,
  700. SenderEmail: app.ServerConf.SendgridSenderEmail,
  701. }
  702. return sgClient.SendEmailVerification(
  703. fmt.Sprintf("%s/api/email/verify/finalize?%s", app.ServerConf.ServerURL, queryVals.Encode()),
  704. form.Email,
  705. )
  706. }