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