user_handler.go 22 KB

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