user_handler.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  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. _, 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. // convert the form to a project model
  424. pwReset, rawToken, err := form.ToPWResetToken()
  425. if err != nil {
  426. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  427. return
  428. }
  429. // handle write to the database
  430. pwReset, err = app.Repo.PWResetToken.CreatePWResetToken(pwReset)
  431. if err != nil {
  432. app.handleErrorDataWrite(err, w)
  433. return
  434. }
  435. queryVals := url.Values{
  436. "token": []string{rawToken},
  437. "email": []string{form.Email},
  438. "token_id": []string{fmt.Sprintf("%d", pwReset.ID)},
  439. }
  440. sgClient := email.SendgridClient{
  441. APIKey: app.ServerConf.SendgridAPIKey,
  442. PWResetTemplateID: app.ServerConf.SendgridPWResetTemplateID,
  443. SenderEmail: app.ServerConf.SendgridSenderEmail,
  444. }
  445. err = sgClient.SendPWResetEmail(
  446. fmt.Sprintf("%s/password/reset/finalize?%s", app.ServerConf.ServerURL, queryVals.Encode()),
  447. form.Email,
  448. )
  449. if err != nil {
  450. app.handleErrorInternal(err, w)
  451. return
  452. }
  453. w.WriteHeader(http.StatusOK)
  454. return
  455. }
  456. // VerifyPWResetUser makes sure that the token is correct and still valid
  457. func (app *App) VerifyPWResetUser(w http.ResponseWriter, r *http.Request) {
  458. form := &forms.VerifyResetUserPasswordForm{}
  459. // decode from JSON to form value
  460. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  461. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  462. return
  463. }
  464. // validate the form
  465. if err := app.validator.Struct(form); err != nil {
  466. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  467. return
  468. }
  469. token, err := app.Repo.PWResetToken.ReadPWResetToken(form.PWResetTokenID)
  470. if err != nil {
  471. w.WriteHeader(http.StatusForbidden)
  472. return
  473. }
  474. // make sure the token is still valid and has not expired
  475. if !token.IsValid || token.IsExpired() {
  476. w.WriteHeader(http.StatusForbidden)
  477. return
  478. }
  479. // check that the email matches
  480. if token.Email != form.Email {
  481. w.WriteHeader(http.StatusForbidden)
  482. return
  483. }
  484. // make sure the token is correct
  485. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  486. w.WriteHeader(http.StatusForbidden)
  487. return
  488. }
  489. w.WriteHeader(http.StatusOK)
  490. return
  491. }
  492. // FinalizPWResetUser completes the password reset flow based on an email.
  493. func (app *App) FinalizPWResetUser(w http.ResponseWriter, r *http.Request) {
  494. form := &forms.FinalizeResetUserPasswordForm{}
  495. // decode from JSON to form value
  496. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  497. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  498. return
  499. }
  500. // validate the form
  501. if err := app.validator.Struct(form); err != nil {
  502. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  503. return
  504. }
  505. // verify the token is valid
  506. token, err := app.Repo.PWResetToken.ReadPWResetToken(form.PWResetTokenID)
  507. if err != nil {
  508. w.WriteHeader(http.StatusForbidden)
  509. return
  510. }
  511. // make sure the token is still valid and has not expired
  512. if !token.IsValid || token.IsExpired() {
  513. w.WriteHeader(http.StatusForbidden)
  514. return
  515. }
  516. // check that the email matches
  517. if token.Email != form.Email {
  518. w.WriteHeader(http.StatusForbidden)
  519. return
  520. }
  521. // make sure the token is correct
  522. if err := bcrypt.CompareHashAndPassword([]byte(token.Token), []byte(form.Token)); err != nil {
  523. w.WriteHeader(http.StatusForbidden)
  524. return
  525. }
  526. // check that the email exists
  527. user, err := app.Repo.User.ReadUserByEmail(form.Email)
  528. if err != nil {
  529. w.WriteHeader(http.StatusForbidden)
  530. return
  531. }
  532. hashedPW, err := bcrypt.GenerateFromPassword([]byte(form.NewPassword), 8)
  533. if err != nil {
  534. app.handleErrorDataWrite(err, w)
  535. return
  536. }
  537. user.Password = string(hashedPW)
  538. user, err = app.Repo.User.UpdateUser(user)
  539. if err != nil {
  540. app.handleErrorDataWrite(err, w)
  541. return
  542. }
  543. // invalidate the token
  544. token.IsValid = false
  545. _, err = app.Repo.PWResetToken.UpdatePWResetToken(token)
  546. if err != nil {
  547. app.handleErrorDataWrite(err, w)
  548. return
  549. }
  550. w.WriteHeader(http.StatusOK)
  551. return
  552. }
  553. // ------------------------ User handler helper functions ------------------------ //
  554. // writeUser will take a POST or PUT request to the /api/users endpoint and decode
  555. // the request into a forms.WriteUserForm model, convert it to a models.User, and
  556. // write to the database.
  557. func (app *App) writeUser(
  558. form forms.WriteUserForm,
  559. dbWrite repository.WriteUser,
  560. w http.ResponseWriter,
  561. r *http.Request,
  562. validators ...func(repo *repository.Repository, user *models.User) *HTTPError,
  563. ) (*models.User, error) {
  564. // decode from JSON to form value
  565. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  566. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  567. return nil, err
  568. }
  569. // validate the form
  570. if err := app.validator.Struct(form); err != nil {
  571. app.handleErrorFormValidation(err, ErrUserValidateFields, w)
  572. return nil, err
  573. }
  574. // convert the form to a user model -- WriteUserForm must implement ToUser
  575. userModel, err := form.ToUser(app.Repo.User)
  576. if err != nil {
  577. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  578. return nil, err
  579. }
  580. // Check any additional validators for any semantic errors
  581. // We have completed all syntax checks, so these will be sent
  582. // with http.StatusUnprocessableEntity (422), unless this is
  583. // an internal server error
  584. for _, validator := range validators {
  585. err := validator(app.Repo, userModel)
  586. if err != nil {
  587. goErr := errors.New(strings.Join(err.Errors, ", "))
  588. if err.Code == 500 {
  589. app.sendExternalError(
  590. goErr,
  591. http.StatusInternalServerError,
  592. *err,
  593. w,
  594. )
  595. } else {
  596. app.sendExternalError(
  597. goErr,
  598. http.StatusUnprocessableEntity,
  599. *err,
  600. w,
  601. )
  602. }
  603. return nil, goErr
  604. }
  605. }
  606. // handle write to the database
  607. user, err := dbWrite(userModel)
  608. if err != nil {
  609. app.handleErrorDataWrite(err, w)
  610. return nil, err
  611. }
  612. return user, nil
  613. }
  614. func (app *App) readUser(w http.ResponseWriter, r *http.Request) (*models.User, error) {
  615. id, err := strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  616. if err != nil || id == 0 {
  617. app.handleErrorFormDecoding(err, ErrUserDecode, w)
  618. return nil, err
  619. }
  620. user, err := app.Repo.User.ReadUser(uint(id))
  621. if err != nil {
  622. app.handleErrorRead(err, ErrUserDataRead, w)
  623. return nil, err
  624. }
  625. return user, nil
  626. }
  627. func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
  628. user, err := repo.User.ReadUserByEmail(user.Email)
  629. if user != nil && err == nil {
  630. return &HTTPError{
  631. Code: ErrUserValidateFields,
  632. Errors: []string{
  633. "email already taken",
  634. },
  635. }
  636. }
  637. if err != gorm.ErrRecordNotFound {
  638. return &ErrorDataRead
  639. }
  640. return nil
  641. }
  642. type SendUserExt struct {
  643. ID uint `json:"id"`
  644. Email string `json:"email"`
  645. EmailVerified bool `json:"email_verified"`
  646. Redirect string `json:"redirect,omitempty"`
  647. }
  648. func (app *App) sendUser(w http.ResponseWriter, userID uint, email string, emailVerified bool, redirect string) error {
  649. resUser := &SendUserExt{
  650. ID: userID,
  651. Email: email,
  652. EmailVerified: emailVerified,
  653. Redirect: redirect,
  654. }
  655. if err := json.NewEncoder(w).Encode(resUser); err != nil {
  656. return err
  657. }
  658. return nil
  659. }
  660. func (app *App) getUserIDFromRequest(r *http.Request) (uint, error) {
  661. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  662. if err != nil {
  663. return 0, err
  664. }
  665. // first, check for token
  666. tok := app.getTokenFromRequest(r)
  667. if tok != nil {
  668. return tok.IBy, nil
  669. }
  670. userID, _ := session.Values["user_id"].(uint)
  671. return userID, nil
  672. }