user_handler.go 22 KB

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