user_handler.go 21 KB

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