user_handler.go 22 KB

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