user_handler.go 22 KB

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