user_handler.go 22 KB

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