2
0

user_handler.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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/api/types"
  15. "github.com/porter-dev/porter/internal/analytics"
  16. "github.com/porter-dev/porter/internal/auth/token"
  17. "github.com/porter-dev/porter/internal/forms"
  18. "github.com/porter-dev/porter/internal/models"
  19. "github.com/porter-dev/porter/internal/notifier"
  20. "github.com/porter-dev/porter/internal/repository"
  21. )
  22. // Enumeration of user API error codes, represented as int64
  23. const (
  24. ErrUserDecode ErrorCode = iota + 600
  25. ErrUserValidateFields
  26. ErrUserDataRead
  27. )
  28. // HandleCreateUser validates a user form entry, converts the user to a gorm
  29. // model, and saves the user to the database
  30. func (app *App) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
  31. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  32. if err != nil {
  33. app.handleErrorDataRead(err, w)
  34. }
  35. form := &forms.CreateUserForm{
  36. // if app can send email verification, set the email verified to false
  37. EmailVerified: !app.Capabilities.Email,
  38. }
  39. user, err := app.writeUser(
  40. form,
  41. app.Repo.User().CreateUser,
  42. w,
  43. r,
  44. doesUserExist,
  45. )
  46. if err == nil {
  47. // send to segment
  48. app.AnalyticsClient.Identify(analytics.CreateSegmentIdentifyUser(user))
  49. app.AnalyticsClient.Track(analytics.UserCreateTrack(&analytics.UserCreateTrackOpts{
  50. UserScopedTrackOpts: analytics.GetUserScopedTrackOpts(user.ID),
  51. Email: user.Email,
  52. }))
  53. app.Logger.Info().Msgf("New user created: %d", user.ID)
  54. // non-fatal email verification flow
  55. app.startEmailVerificationFlow(user)
  56. var redirect string
  57. if valR := session.Values["redirect"]; valR != nil {
  58. redirect = session.Values["redirect"].(string)
  59. }
  60. session.Values["authenticated"] = true
  61. session.Values["user_id"] = user.ID
  62. session.Values["email"] = user.Email
  63. session.Values["redirect"] = ""
  64. session.Save(r, w)
  65. w.WriteHeader(http.StatusCreated)
  66. if err := app.sendUser(w, user.ID, user.Email, false, redirect); err != nil {
  67. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  68. return
  69. }
  70. }
  71. }
  72. // HandleAuthCheck checks whether current session is authenticated and returns user ID if so.
  73. func (app *App) HandleAuthCheck(w http.ResponseWriter, r *http.Request) {
  74. // first, check for token
  75. tok := app.getTokenFromRequest(r)
  76. if tok != nil {
  77. // read the user
  78. user, err := app.Repo.User().ReadUser(tok.IBy)
  79. if err != nil {
  80. http.Error(w, err.Error(), http.StatusInternalServerError)
  81. return
  82. }
  83. if err := app.sendUser(w, tok.IBy, user.Email, user.EmailVerified, ""); err != nil {
  84. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  85. return
  86. }
  87. return
  88. }
  89. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  90. if err != nil {
  91. http.Error(w, err.Error(), http.StatusInternalServerError)
  92. return
  93. }
  94. userID, _ := session.Values["user_id"].(uint)
  95. email, _ := session.Values["email"].(string)
  96. user, err := app.Repo.User().ReadUser(userID)
  97. if err != nil {
  98. http.Error(w, err.Error(), http.StatusInternalServerError)
  99. return
  100. }
  101. w.WriteHeader(http.StatusOK)
  102. if err := app.sendUser(w, userID, email, user.EmailVerified, ""); err != nil {
  103. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  104. return
  105. }
  106. }
  107. // HandleCLILoginUser verifies that a user is logged in, and generates an access
  108. // token for usage from the CLI
  109. func (app *App) HandleCLILoginUser(w http.ResponseWriter, r *http.Request) {
  110. queryParams, _ := url.ParseQuery(r.URL.RawQuery)
  111. redirect := queryParams["redirect"][0]
  112. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  113. if err != nil {
  114. http.Error(w, err.Error(), http.StatusInternalServerError)
  115. return
  116. }
  117. userID, _ := session.Values["user_id"].(uint)
  118. // generate the token
  119. jwt, err := token.GetTokenForUser(userID)
  120. if err != nil {
  121. app.handleErrorInternal(err, w)
  122. return
  123. }
  124. encoded, err := jwt.EncodeToken(&token.TokenGeneratorConf{
  125. TokenSecret: app.ServerConf.TokenGeneratorSecret,
  126. })
  127. if err != nil {
  128. app.handleErrorInternal(err, w)
  129. return
  130. }
  131. // generate 64 characters long authorization code
  132. code, err := repository.GenerateRandomBytes(32)
  133. if err != nil {
  134. app.handleErrorInternal(err, w)
  135. return
  136. }
  137. expiry := time.Now().Add(30 * time.Second)
  138. // create auth code object and send back authorization code
  139. authCode := &models.AuthCode{
  140. Token: encoded,
  141. AuthorizationCode: code,
  142. Expiry: &expiry,
  143. }
  144. authCode, err = app.Repo.AuthCode().CreateAuthCode(authCode)
  145. if err != nil {
  146. app.handleErrorInternal(err, w)
  147. return
  148. }
  149. http.Redirect(w, r, fmt.Sprintf("%s/?code=%s", redirect, url.QueryEscape(authCode.AuthorizationCode)), 302)
  150. }
  151. type ExchangeRequest struct {
  152. AuthorizationCode string `json:"authorization_code"`
  153. }
  154. type ExchangeResponse struct {
  155. Token string `json:"token"`
  156. }
  157. // HandleCLILoginExchangeToken exchanges an authorization code for a token
  158. func (app *App) HandleCLILoginExchangeToken(w http.ResponseWriter, r *http.Request) {
  159. // read the request body and look up the authorization token
  160. req := &ExchangeRequest{}
  161. if err := json.NewDecoder(r.Body).Decode(req); err != nil {
  162. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  163. return
  164. }
  165. authCode, err := app.Repo.AuthCode().ReadAuthCode(req.AuthorizationCode)
  166. if err != nil || authCode.IsExpired() {
  167. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  168. return
  169. }
  170. res := &ExchangeResponse{
  171. Token: authCode.Token,
  172. }
  173. w.WriteHeader(http.StatusOK)
  174. if err := json.NewEncoder(w).Encode(res); err != nil {
  175. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  176. return
  177. }
  178. }
  179. // HandleLoginUser checks the request header for cookie and validates the user.
  180. func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
  181. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  182. if err != nil {
  183. app.handleErrorDataRead(err, w)
  184. return
  185. }
  186. form := &forms.LoginUserForm{}
  187. // decode from JSON to form value
  188. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  189. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  190. return
  191. }
  192. storedUser, readErr := app.Repo.User().ReadUserByEmail(form.Email)
  193. if readErr != nil {
  194. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  195. Errors: []string{"email not registered"},
  196. Code: http.StatusUnauthorized,
  197. }, w)
  198. return
  199. }
  200. if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(form.Password)); err != nil {
  201. app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
  202. Errors: []string{"incorrect password"},
  203. Code: http.StatusUnauthorized,
  204. }, w)
  205. return
  206. }
  207. var redirect string
  208. if valR := session.Values["redirect"]; valR != nil {
  209. redirect = session.Values["redirect"].(string)
  210. }
  211. // Set user as authenticated
  212. session.Values["authenticated"] = true
  213. session.Values["user_id"] = storedUser.ID
  214. session.Values["email"] = storedUser.Email
  215. session.Values["redirect"] = ""
  216. if err := session.Save(r, w); err != nil {
  217. app.Logger.Warn().Err(err)
  218. }
  219. w.WriteHeader(http.StatusOK)
  220. if err := app.sendUser(w, storedUser.ID, storedUser.Email, storedUser.EmailVerified, redirect); err != nil {
  221. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  222. return
  223. }
  224. }
  225. // HandleLogoutUser detaches the user from the session
  226. func (app *App) HandleLogoutUser(w http.ResponseWriter, r *http.Request) {
  227. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  228. if err != nil {
  229. app.handleErrorDataRead(err, w)
  230. }
  231. session.Values["authenticated"] = false
  232. session.Values["user_id"] = nil
  233. session.Values["email"] = nil
  234. session.Save(r, w)
  235. w.WriteHeader(http.StatusOK)
  236. }
  237. // HandleReadUser returns an externalized User (models.UserExternal)
  238. // based on an ID
  239. func (app *App) HandleReadUser(w http.ResponseWriter, r *http.Request) {
  240. user, err := app.readUser(w, r)
  241. // error already handled by helper
  242. if err != nil {
  243. return
  244. }
  245. extUser := user.Externalize()
  246. if err := json.NewEncoder(w).Encode(extUser); err != nil {
  247. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  248. return
  249. }
  250. w.WriteHeader(http.StatusOK)
  251. }
  252. // HandleListUserProjects lists all projects belonging to a given user
  253. func (app *App) HandleListUserProjects(w http.ResponseWriter, r *http.Request) {
  254. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  255. if err != nil || id == 0 {
  256. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  257. return
  258. }
  259. projects, err := app.Repo.Project().ListProjectsByUserID(uint(id))
  260. if err != nil {
  261. app.handleErrorRead(err, ErrUserDataRead, w)
  262. }
  263. projectsExt := make([]*types.Project, 0)
  264. for _, project := range projects {
  265. projectsExt = append(projectsExt, project.ToProjectType())
  266. }
  267. w.WriteHeader(http.StatusOK)
  268. if err := json.NewEncoder(w).Encode(projectsExt); err != nil {
  269. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  270. return
  271. }
  272. }
  273. // HandleDeleteUser removes a user after checking that the sent password is correct
  274. func (app *App) HandleDeleteUser(w http.ResponseWriter, r *http.Request) {
  275. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  276. if err != nil || id == 0 {
  277. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  278. return
  279. }
  280. // TODO -- HASH AND VERIFY PASSWORD BEFORE USER DELETION
  281. form := &forms.DeleteUserForm{
  282. ID: uint(id),
  283. }
  284. user, err := app.writeUser(form, app.Repo.User().DeleteUser, w, r)
  285. if err == nil {
  286. app.Logger.Info().Msgf("User deleted: %d", user.ID)
  287. w.WriteHeader(http.StatusNoContent)
  288. }
  289. }
  290. // InitiateEmailVerifyUser initiates the email verification flow for a logged-in user
  291. func (app *App) InitiateEmailVerifyUser(w http.ResponseWriter, r *http.Request) {
  292. userID, err := app.getUserIDFromRequest(r)
  293. if err != nil {
  294. app.handleErrorInternal(err, w)
  295. return
  296. }
  297. user, err := app.Repo.User().ReadUser(userID)
  298. if err != nil {
  299. app.handleErrorInternal(err, w)
  300. return
  301. }
  302. err = app.startEmailVerificationFlow(user)
  303. if err != nil {
  304. app.handleErrorInternal(err, w)
  305. return
  306. }
  307. w.WriteHeader(http.StatusOK)
  308. }
  309. // FinalizeEmailVerifyUser completes the email verification flow for a user.
  310. func (app *App) FinalizeEmailVerifyUser(w http.ResponseWriter, r *http.Request) {
  311. userID, err := app.getUserIDFromRequest(r)
  312. if err != nil {
  313. app.handleErrorInternal(err, w)
  314. return
  315. }
  316. user, err := app.Repo.User().ReadUser(userID)
  317. if err != nil {
  318. app.handleErrorInternal(err, w)
  319. return
  320. }
  321. vals, err := url.ParseQuery(r.URL.RawQuery)
  322. if err != nil {
  323. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL"), 302)
  324. return
  325. }
  326. var tokenStr string
  327. var tokenID uint
  328. if tokenArr, ok := vals["token"]; ok && len(tokenArr) == 1 {
  329. tokenStr = tokenArr[0]
  330. } else {
  331. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL: token required"), 302)
  332. return
  333. }
  334. if tokenIDArr, ok := vals["token_id"]; ok && len(tokenIDArr) == 1 {
  335. id, err := strconv.ParseUint(tokenIDArr[0], 10, 64)
  336. if err != nil {
  337. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL: valid token id required"), 302)
  338. return
  339. }
  340. tokenID = uint(id)
  341. } else {
  342. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL: valid token id required"), 302)
  343. return
  344. }
  345. // verify the token is valid
  346. token, err := app.Repo.PWResetToken().ReadPWResetToken(tokenID)
  347. if err != nil {
  348. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Email verification error: valid token required"), 302)
  349. return
  350. }
  351. // make sure the token is still valid and has not expired
  352. if !token.IsValid || token.IsExpired() {
  353. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Email verification error: valid token required"), 302)
  354. return
  355. }
  356. // make sure the token is correct
  357. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(tokenStr)); err != nil {
  358. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Email verification error: valid token required"), 302)
  359. return
  360. }
  361. user.EmailVerified = true
  362. user, err = app.Repo.User().UpdateUser(user)
  363. if err != nil {
  364. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Could not verify email address"), 302)
  365. return
  366. }
  367. // invalidate the token
  368. token.IsValid = false
  369. _, err = app.Repo.PWResetToken().UpdatePWResetToken(token)
  370. if err != nil {
  371. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Could not verify email address"), 302)
  372. return
  373. }
  374. app.AnalyticsClient.Track(analytics.UserVerifyEmailTrack(&analytics.UserVerifyEmailTrackOpts{
  375. UserScopedTrackOpts: analytics.GetUserScopedTrackOpts(user.ID),
  376. Email: user.Email,
  377. }))
  378. http.Redirect(w, r, "/dashboard", 302)
  379. return
  380. }
  381. // InitiatePWResetUser initiates the password reset flow based on an email. The endpoint
  382. // checks if the email exists, but returns a 200 status code regardless, since we don't
  383. // want to leak in-use emails
  384. func (app *App) InitiatePWResetUser(w http.ResponseWriter, r *http.Request) {
  385. form := &forms.InitiateResetUserPasswordForm{}
  386. // decode from JSON to form value
  387. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  388. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  389. return
  390. }
  391. // validate the form
  392. if err := app.validator.Struct(form); err != nil {
  393. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  394. return
  395. }
  396. // check that the email exists; return 200 status code even if it doesn't
  397. user, err := app.Repo.User().ReadUserByEmail(form.Email)
  398. if err == gorm.ErrRecordNotFound {
  399. w.WriteHeader(http.StatusOK)
  400. return
  401. } else if err != nil {
  402. app.handleErrorDataRead(err, w)
  403. return
  404. }
  405. // if the user is a Github user, send them a Github email
  406. if user.GithubUserID != 0 {
  407. err := app.notifier.SendGithubRelinkEmail(
  408. &notifier.SendGithubRelinkEmailOpts{
  409. Email: user.Email,
  410. URL: fmt.Sprintf("%s/api/oauth/login/github", app.ServerConf.ServerURL),
  411. },
  412. )
  413. if err != nil {
  414. app.handleErrorInternal(err, w)
  415. return
  416. }
  417. w.WriteHeader(http.StatusOK)
  418. return
  419. }
  420. // convert the form to a project model
  421. pwReset, rawToken, err := form.ToPWResetToken()
  422. if err != nil {
  423. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  424. return
  425. }
  426. // handle write to the database
  427. pwReset, err = app.Repo.PWResetToken().CreatePWResetToken(pwReset)
  428. if err != nil {
  429. app.handleErrorDataWrite(err, w)
  430. return
  431. }
  432. queryVals := url.Values{
  433. "token": []string{rawToken},
  434. "email": []string{form.Email},
  435. "token_id": []string{fmt.Sprintf("%d", pwReset.ID)},
  436. }
  437. err = app.notifier.SendPasswordResetEmail(
  438. &notifier.SendPasswordResetEmailOpts{
  439. Email: user.Email,
  440. URL: fmt.Sprintf("%s/password/reset/finalize?%s", app.ServerConf.ServerURL, queryVals.Encode()),
  441. },
  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. return app.notifier.SendEmailVerification(
  693. &notifier.SendEmailVerificationOpts{
  694. Email: form.Email,
  695. URL: fmt.Sprintf("%s/api/email/verify/finalize?%s", app.ServerConf.ServerURL, queryVals.Encode()),
  696. },
  697. )
  698. }