user_handler.go 22 KB

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