user_handler.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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/models"
  17. "github.com/porter-dev/porter/internal/notifier"
  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. err = app.notifier.SendEmailVerification(
  330. &notifier.SendEmailVerificationOpts{
  331. Email: user.Email,
  332. URL: fmt.Sprintf("%s/api/email/verify/finalize?%s", app.ServerConf.ServerURL, queryVals.Encode()),
  333. },
  334. )
  335. if err != nil {
  336. app.handleErrorInternal(err, w)
  337. return
  338. }
  339. w.WriteHeader(http.StatusOK)
  340. return
  341. }
  342. // FinalizEmailVerifyUser completes the email verification flow for a user.
  343. func (app *App) FinalizEmailVerifyUser(w http.ResponseWriter, r *http.Request) {
  344. userID, err := app.getUserIDFromRequest(r)
  345. if err != nil {
  346. app.handleErrorInternal(err, w)
  347. return
  348. }
  349. user, err := app.Repo.User().ReadUser(userID)
  350. if err != nil {
  351. app.handleErrorInternal(err, w)
  352. return
  353. }
  354. vals, err := url.ParseQuery(r.URL.RawQuery)
  355. if err != nil {
  356. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL"), 302)
  357. return
  358. }
  359. var tokenStr string
  360. var tokenID uint
  361. if tokenArr, ok := vals["token"]; ok && len(tokenArr) == 1 {
  362. tokenStr = tokenArr[0]
  363. } else {
  364. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL: token required"), 302)
  365. return
  366. }
  367. if tokenIDArr, ok := vals["token_id"]; ok && len(tokenIDArr) == 1 {
  368. id, err := strconv.ParseUint(tokenIDArr[0], 10, 64)
  369. if err != nil {
  370. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL: valid token id required"), 302)
  371. return
  372. }
  373. tokenID = uint(id)
  374. } else {
  375. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Invalid email verification URL: valid token id required"), 302)
  376. return
  377. }
  378. // verify the token is valid
  379. token, err := app.Repo.PWResetToken().ReadPWResetToken(tokenID)
  380. if err != nil {
  381. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Email verification error: valid token required"), 302)
  382. return
  383. }
  384. // make sure the token is still valid and has not expired
  385. if !token.IsValid || token.IsExpired() {
  386. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Email verification error: valid token required"), 302)
  387. return
  388. }
  389. // make sure the token is correct
  390. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(tokenStr)); err != nil {
  391. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Email verification error: valid token required"), 302)
  392. return
  393. }
  394. user.EmailVerified = true
  395. user, err = app.Repo.User().UpdateUser(user)
  396. if err != nil {
  397. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Could not verify email address"), 302)
  398. return
  399. }
  400. // invalidate the token
  401. token.IsValid = false
  402. _, err = app.Repo.PWResetToken().UpdatePWResetToken(token)
  403. if err != nil {
  404. http.Redirect(w, r, "/dashboard?error="+url.QueryEscape("Could not verify email address"), 302)
  405. return
  406. }
  407. http.Redirect(w, r, "/dashboard", 302)
  408. return
  409. }
  410. // InitiatePWResetUser initiates the password reset flow based on an email. The endpoint
  411. // checks if the email exists, but returns a 200 status code regardless, since we don't
  412. // want to leak in-use emails
  413. func (app *App) InitiatePWResetUser(w http.ResponseWriter, r *http.Request) {
  414. form := &forms.InitiateResetUserPasswordForm{}
  415. // decode from JSON to form value
  416. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  417. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  418. return
  419. }
  420. // validate the form
  421. if err := app.validator.Struct(form); err != nil {
  422. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  423. return
  424. }
  425. // check that the email exists; return 200 status code even if it doesn't
  426. user, err := app.Repo.User().ReadUserByEmail(form.Email)
  427. if err == gorm.ErrRecordNotFound {
  428. w.WriteHeader(http.StatusOK)
  429. return
  430. } else if err != nil {
  431. app.handleErrorDataRead(err, w)
  432. return
  433. }
  434. // if the user is a Github user, send them a Github email
  435. if user.GithubUserID != 0 {
  436. err := app.notifier.SendGithubRelinkEmail(
  437. &notifier.SendGithubRelinkEmailOpts{
  438. Email: user.Email,
  439. URL: fmt.Sprintf("%s/api/oauth/login/github", app.ServerConf.ServerURL),
  440. },
  441. )
  442. if err != nil {
  443. app.handleErrorInternal(err, w)
  444. return
  445. }
  446. w.WriteHeader(http.StatusOK)
  447. return
  448. }
  449. // convert the form to a project model
  450. pwReset, rawToken, err := form.ToPWResetToken()
  451. if err != nil {
  452. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  453. return
  454. }
  455. // handle write to the database
  456. pwReset, err = app.Repo.PWResetToken().CreatePWResetToken(pwReset)
  457. if err != nil {
  458. app.handleErrorDataWrite(err, w)
  459. return
  460. }
  461. queryVals := url.Values{
  462. "token": []string{rawToken},
  463. "email": []string{form.Email},
  464. "token_id": []string{fmt.Sprintf("%d", pwReset.ID)},
  465. }
  466. err = app.notifier.SendPasswordResetEmail(
  467. &notifier.SendPasswordResetEmailOpts{
  468. Email: user.Email,
  469. URL: fmt.Sprintf("%s/password/reset/finalize?%s", app.ServerConf.ServerURL, queryVals.Encode()),
  470. },
  471. )
  472. if err != nil {
  473. app.handleErrorInternal(err, w)
  474. return
  475. }
  476. w.WriteHeader(http.StatusOK)
  477. return
  478. }
  479. // VerifyPWResetUser makes sure that the token is correct and still valid
  480. func (app *App) VerifyPWResetUser(w http.ResponseWriter, r *http.Request) {
  481. form := &forms.VerifyResetUserPasswordForm{}
  482. // decode from JSON to form value
  483. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  484. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  485. return
  486. }
  487. // validate the form
  488. if err := app.validator.Struct(form); err != nil {
  489. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  490. return
  491. }
  492. token, err := app.Repo.PWResetToken().ReadPWResetToken(form.PWResetTokenID)
  493. if err != nil {
  494. w.WriteHeader(http.StatusForbidden)
  495. return
  496. }
  497. // make sure the token is still valid and has not expired
  498. if !token.IsValid || token.IsExpired() {
  499. w.WriteHeader(http.StatusForbidden)
  500. return
  501. }
  502. // check that the email matches
  503. if token.Email != form.Email {
  504. w.WriteHeader(http.StatusForbidden)
  505. return
  506. }
  507. // make sure the token is correct
  508. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  509. w.WriteHeader(http.StatusForbidden)
  510. return
  511. }
  512. w.WriteHeader(http.StatusOK)
  513. return
  514. }
  515. // FinalizPWResetUser completes the password reset flow based on an email.
  516. func (app *App) FinalizPWResetUser(w http.ResponseWriter, r *http.Request) {
  517. form := &forms.FinalizeResetUserPasswordForm{}
  518. // decode from JSON to form value
  519. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  520. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  521. return
  522. }
  523. // validate the form
  524. if err := app.validator.Struct(form); err != nil {
  525. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  526. return
  527. }
  528. // verify the token is valid
  529. token, err := app.Repo.PWResetToken().ReadPWResetToken(form.PWResetTokenID)
  530. if err != nil {
  531. w.WriteHeader(http.StatusForbidden)
  532. return
  533. }
  534. // make sure the token is still valid and has not expired
  535. if !token.IsValid || token.IsExpired() {
  536. w.WriteHeader(http.StatusForbidden)
  537. return
  538. }
  539. // check that the email matches
  540. if token.Email != form.Email {
  541. w.WriteHeader(http.StatusForbidden)
  542. return
  543. }
  544. // make sure the token is correct
  545. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  546. w.WriteHeader(http.StatusForbidden)
  547. return
  548. }
  549. // check that the email exists
  550. user, err := app.Repo.User().ReadUserByEmail(form.Email)
  551. if err != nil {
  552. w.WriteHeader(http.StatusForbidden)
  553. return
  554. }
  555. hashedPW, err := bcrypt.GenerateFromPassword([]byte(form.NewPassword), 8)
  556. if err != nil {
  557. app.handleErrorDataWrite(err, w)
  558. return
  559. }
  560. user.Password = string(hashedPW)
  561. user, err = app.Repo.User().UpdateUser(user)
  562. if err != nil {
  563. app.handleErrorDataWrite(err, w)
  564. return
  565. }
  566. // invalidate the token
  567. token.IsValid = false
  568. _, err = app.Repo.PWResetToken().UpdatePWResetToken(token)
  569. if err != nil {
  570. app.handleErrorDataWrite(err, w)
  571. return
  572. }
  573. w.WriteHeader(http.StatusOK)
  574. return
  575. }
  576. // ------------------------ User handler helper functions ------------------------ //
  577. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  578. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  579. // write to the database.
  580. func (app *App) writeUser(
  581. form forms.WriteUserForm,
  582. dbWrite repository.WriteUser,
  583. w http.ResponseWriter,
  584. r *http.Request,
  585. validators ...func(repo repository.Repository, user *models.User) *HTTPError,
  586. ) (*models.User, error) {
  587. // decode from JSON to form value
  588. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  589. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  590. return nil, err
  591. }
  592. // validate the form
  593. if err := app.validator.Struct(form); err != nil {
  594. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  595. return nil, err
  596. }
  597. // convert the form to a user model -- WriteUserForm must implement ToUser
  598. userModel, err := form.ToUser(app.Repo.User())
  599. if err != nil {
  600. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  601. return nil, err
  602. }
  603. // Check any additional validators for any semantic errors
  604. // We have completed all syntax checks, so these will be sent
  605. // with http.StatusUnprocessableEntity (422), unless this is
  606. // an internal server error
  607. for _, validator := range validators {
  608. err := validator(app.Repo, userModel)
  609. if err != nil {
  610. goErr := errors.New(strings.Join(err.Errors, ", "))
  611. if err.Code == 500 {
  612. app.sendExternalError(
  613. goErr,
  614. http.StatusInternalServerError,
  615. *err,
  616. w,
  617. )
  618. } else {
  619. app.sendExternalError(
  620. goErr,
  621. http.StatusUnprocessableEntity,
  622. *err,
  623. w,
  624. )
  625. }
  626. return nil, goErr
  627. }
  628. }
  629. // handle write to the database
  630. user, err := dbWrite(userModel)
  631. if err != nil {
  632. app.handleErrorDataWrite(err, w)
  633. return nil, err
  634. }
  635. return user, nil
  636. }
  637. func (app *App) readUser(w http.ResponseWriter, r *http.Request) (*models.User, error) {
  638. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  639. if err != nil || id == 0 {
  640. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  641. return nil, err
  642. }
  643. user, err := app.Repo.User().ReadUser(uint(id))
  644. if err != nil {
  645. app.handleErrorRead(err, ErrUserDataRead, w)
  646. return nil, err
  647. }
  648. return user, nil
  649. }
  650. func doesUserExist(repo repository.Repository, user *models.User) *HTTPError {
  651. user, err := repo.User().ReadUserByEmail(user.Email)
  652. if user != nil && err == nil {
  653. return &HTTPError{
  654. Code: ErrUserValidateFields,
  655. Errors: []string{
  656. "email already taken",
  657. },
  658. }
  659. }
  660. if err != gorm.ErrRecordNotFound {
  661. return &ErrorDataRead
  662. }
  663. return nil
  664. }
  665. type SendUserExt struct {
  666. ID uint `json:"id"`
  667. Email string `json:"email"`
  668. EmailVerified bool `json:"email_verified"`
  669. Redirect string `json:"redirect,omitempty"`
  670. }
  671. func (app *App) sendUser(w http.ResponseWriter, userID uint, email string, emailVerified bool, redirect string) error {
  672. resUser := &SendUserExt{
  673. ID: userID,
  674. Email: email,
  675. EmailVerified: emailVerified,
  676. Redirect: redirect,
  677. }
  678. if err := json.NewEncoder(w).Encode(resUser); err != nil {
  679. return err
  680. }
  681. return nil
  682. }
  683. func (app *App) getUserIDFromRequest(r *http.Request) (uint, error) {
  684. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  685. if err != nil {
  686. return 0, err
  687. }
  688. // first, check for token
  689. tok := app.getTokenFromRequest(r)
  690. if tok != nil {
  691. return tok.IBy, nil
  692. }
  693. userID, _ := session.Values["user_id"].(uint)
  694. return userID, nil
  695. }