user_handler.go 21 KB

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