server_account.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. package server
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "github.com/stripe/stripe-go/v74"
  6. portalsession "github.com/stripe/stripe-go/v74/billingportal/session"
  7. "github.com/stripe/stripe-go/v74/checkout/session"
  8. "github.com/stripe/stripe-go/v74/subscription"
  9. "github.com/stripe/stripe-go/v74/webhook"
  10. "github.com/tidwall/gjson"
  11. "heckel.io/ntfy/log"
  12. "heckel.io/ntfy/user"
  13. "heckel.io/ntfy/util"
  14. "net/http"
  15. )
  16. const (
  17. jsonBodyBytesLimit = 4096
  18. stripeBodyBytesLimit = 16384
  19. subscriptionIDLength = 16
  20. createdByAPI = "api"
  21. )
  22. func (s *Server) handleAccountCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  23. admin := v.user != nil && v.user.Role == user.RoleAdmin
  24. if !admin {
  25. if !s.config.EnableSignup {
  26. return errHTTPBadRequestSignupNotEnabled
  27. } else if v.user != nil {
  28. return errHTTPUnauthorized // Cannot create account from user context
  29. }
  30. }
  31. newAccount, err := readJSONWithLimit[apiAccountCreateRequest](r.Body, jsonBodyBytesLimit)
  32. if err != nil {
  33. return err
  34. }
  35. if existingUser, _ := s.userManager.User(newAccount.Username); existingUser != nil {
  36. return errHTTPConflictUserExists
  37. }
  38. if v.accountLimiter != nil && !v.accountLimiter.Allow() {
  39. return errHTTPTooManyRequestsLimitAccountCreation
  40. }
  41. if err := s.userManager.AddUser(newAccount.Username, newAccount.Password, user.RoleUser, createdByAPI); err != nil { // TODO this should return a User
  42. return err
  43. }
  44. w.Header().Set("Content-Type", "application/json")
  45. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  46. return nil
  47. }
  48. func (s *Server) handleAccountGet(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  49. info, err := v.Info()
  50. if err != nil {
  51. return err
  52. }
  53. limits, stats := info.Limits, info.Stats
  54. response := &apiAccountResponse{
  55. Limits: &apiAccountLimits{
  56. Basis: string(limits.Basis),
  57. Messages: limits.MessagesLimit,
  58. MessagesExpiryDuration: int64(limits.MessagesExpiryDuration.Seconds()),
  59. Emails: limits.EmailsLimit,
  60. Reservations: limits.ReservationsLimit,
  61. AttachmentTotalSize: limits.AttachmentTotalSizeLimit,
  62. AttachmentFileSize: limits.AttachmentFileSizeLimit,
  63. AttachmentExpiryDuration: int64(limits.AttachmentExpiryDuration.Seconds()),
  64. },
  65. Stats: &apiAccountStats{
  66. Messages: stats.Messages,
  67. MessagesRemaining: stats.MessagesRemaining,
  68. Emails: stats.Emails,
  69. EmailsRemaining: stats.EmailsRemaining,
  70. Reservations: stats.Reservations,
  71. ReservationsRemaining: stats.ReservationsRemaining,
  72. AttachmentTotalSize: stats.AttachmentTotalSize,
  73. AttachmentTotalSizeRemaining: stats.AttachmentTotalSizeRemaining,
  74. },
  75. }
  76. if v.user != nil {
  77. response.Username = v.user.Name
  78. response.Role = string(v.user.Role)
  79. response.SyncTopic = v.user.SyncTopic
  80. if v.user.Prefs != nil {
  81. if v.user.Prefs.Language != "" {
  82. response.Language = v.user.Prefs.Language
  83. }
  84. if v.user.Prefs.Notification != nil {
  85. response.Notification = v.user.Prefs.Notification
  86. }
  87. if v.user.Prefs.Subscriptions != nil {
  88. response.Subscriptions = v.user.Prefs.Subscriptions
  89. }
  90. }
  91. if v.user.Tier != nil {
  92. response.Tier = &apiAccountTier{
  93. Code: v.user.Tier.Code,
  94. Name: v.user.Tier.Name,
  95. Paid: v.user.Tier.Paid,
  96. }
  97. }
  98. reservations, err := s.userManager.Reservations(v.user.Name)
  99. if err != nil {
  100. return err
  101. }
  102. if len(reservations) > 0 {
  103. response.Reservations = make([]*apiAccountReservation, 0)
  104. for _, r := range reservations {
  105. response.Reservations = append(response.Reservations, &apiAccountReservation{
  106. Topic: r.Topic,
  107. Everyone: r.Everyone.String(),
  108. })
  109. }
  110. }
  111. } else {
  112. response.Username = user.Everyone
  113. response.Role = string(user.RoleAnonymous)
  114. }
  115. w.Header().Set("Content-Type", "application/json")
  116. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  117. if err := json.NewEncoder(w).Encode(response); err != nil {
  118. return err
  119. }
  120. return nil
  121. }
  122. func (s *Server) handleAccountDelete(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  123. if err := s.userManager.RemoveUser(v.user.Name); err != nil {
  124. return err
  125. }
  126. w.Header().Set("Content-Type", "application/json")
  127. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  128. return nil
  129. }
  130. func (s *Server) handleAccountPasswordChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  131. newPassword, err := readJSONWithLimit[apiAccountPasswordChangeRequest](r.Body, jsonBodyBytesLimit)
  132. if err != nil {
  133. return err
  134. }
  135. if err := s.userManager.ChangePassword(v.user.Name, newPassword.Password); err != nil {
  136. return err
  137. }
  138. w.Header().Set("Content-Type", "application/json")
  139. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  140. return nil
  141. }
  142. func (s *Server) handleAccountTokenIssue(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  143. // TODO rate limit
  144. token, err := s.userManager.CreateToken(v.user)
  145. if err != nil {
  146. return err
  147. }
  148. w.Header().Set("Content-Type", "application/json")
  149. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  150. response := &apiAccountTokenResponse{
  151. Token: token.Value,
  152. Expires: token.Expires.Unix(),
  153. }
  154. if err := json.NewEncoder(w).Encode(response); err != nil {
  155. return err
  156. }
  157. return nil
  158. }
  159. func (s *Server) handleAccountTokenExtend(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  160. // TODO rate limit
  161. if v.user == nil {
  162. return errHTTPUnauthorized
  163. } else if v.user.Token == "" {
  164. return errHTTPBadRequestNoTokenProvided
  165. }
  166. token, err := s.userManager.ExtendToken(v.user)
  167. if err != nil {
  168. return err
  169. }
  170. w.Header().Set("Content-Type", "application/json")
  171. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  172. response := &apiAccountTokenResponse{
  173. Token: token.Value,
  174. Expires: token.Expires.Unix(),
  175. }
  176. if err := json.NewEncoder(w).Encode(response); err != nil {
  177. return err
  178. }
  179. return nil
  180. }
  181. func (s *Server) handleAccountTokenDelete(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  182. // TODO rate limit
  183. if v.user.Token == "" {
  184. return errHTTPBadRequestNoTokenProvided
  185. }
  186. if err := s.userManager.RemoveToken(v.user); err != nil {
  187. return err
  188. }
  189. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  190. return nil
  191. }
  192. func (s *Server) handleAccountSettingsChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  193. newPrefs, err := readJSONWithLimit[user.Prefs](r.Body, jsonBodyBytesLimit)
  194. if err != nil {
  195. return err
  196. }
  197. if v.user.Prefs == nil {
  198. v.user.Prefs = &user.Prefs{}
  199. }
  200. prefs := v.user.Prefs
  201. if newPrefs.Language != "" {
  202. prefs.Language = newPrefs.Language
  203. }
  204. if newPrefs.Notification != nil {
  205. if prefs.Notification == nil {
  206. prefs.Notification = &user.NotificationPrefs{}
  207. }
  208. if newPrefs.Notification.DeleteAfter > 0 {
  209. prefs.Notification.DeleteAfter = newPrefs.Notification.DeleteAfter
  210. }
  211. if newPrefs.Notification.Sound != "" {
  212. prefs.Notification.Sound = newPrefs.Notification.Sound
  213. }
  214. if newPrefs.Notification.MinPriority > 0 {
  215. prefs.Notification.MinPriority = newPrefs.Notification.MinPriority
  216. }
  217. }
  218. if err := s.userManager.ChangeSettings(v.user); err != nil {
  219. return err
  220. }
  221. w.Header().Set("Content-Type", "application/json")
  222. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  223. return nil
  224. }
  225. func (s *Server) handleAccountSubscriptionAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  226. newSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit)
  227. if err != nil {
  228. return err
  229. }
  230. if v.user.Prefs == nil {
  231. v.user.Prefs = &user.Prefs{}
  232. }
  233. newSubscription.ID = "" // Client cannot set ID
  234. for _, subscription := range v.user.Prefs.Subscriptions {
  235. if newSubscription.BaseURL == subscription.BaseURL && newSubscription.Topic == subscription.Topic {
  236. newSubscription = subscription
  237. break
  238. }
  239. }
  240. if newSubscription.ID == "" {
  241. newSubscription.ID = util.RandomString(subscriptionIDLength)
  242. v.user.Prefs.Subscriptions = append(v.user.Prefs.Subscriptions, newSubscription)
  243. if err := s.userManager.ChangeSettings(v.user); err != nil {
  244. return err
  245. }
  246. }
  247. w.Header().Set("Content-Type", "application/json")
  248. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  249. if err := json.NewEncoder(w).Encode(newSubscription); err != nil {
  250. return err
  251. }
  252. return nil
  253. }
  254. func (s *Server) handleAccountSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  255. matches := accountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  256. if len(matches) != 2 {
  257. return errHTTPInternalErrorInvalidPath
  258. }
  259. subscriptionID := matches[1]
  260. updatedSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit)
  261. if err != nil {
  262. return err
  263. }
  264. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  265. return errHTTPNotFound
  266. }
  267. var subscription *user.Subscription
  268. for _, sub := range v.user.Prefs.Subscriptions {
  269. if sub.ID == subscriptionID {
  270. sub.DisplayName = updatedSubscription.DisplayName
  271. subscription = sub
  272. break
  273. }
  274. }
  275. if subscription == nil {
  276. return errHTTPNotFound
  277. }
  278. if err := s.userManager.ChangeSettings(v.user); err != nil {
  279. return err
  280. }
  281. w.Header().Set("Content-Type", "application/json")
  282. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  283. if err := json.NewEncoder(w).Encode(subscription); err != nil {
  284. return err
  285. }
  286. return nil
  287. }
  288. func (s *Server) handleAccountSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  289. matches := accountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  290. if len(matches) != 2 {
  291. return errHTTPInternalErrorInvalidPath
  292. }
  293. subscriptionID := matches[1]
  294. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  295. return nil
  296. }
  297. newSubscriptions := make([]*user.Subscription, 0)
  298. for _, subscription := range v.user.Prefs.Subscriptions {
  299. if subscription.ID != subscriptionID {
  300. newSubscriptions = append(newSubscriptions, subscription)
  301. }
  302. }
  303. if len(newSubscriptions) < len(v.user.Prefs.Subscriptions) {
  304. v.user.Prefs.Subscriptions = newSubscriptions
  305. if err := s.userManager.ChangeSettings(v.user); err != nil {
  306. return err
  307. }
  308. }
  309. w.Header().Set("Content-Type", "application/json")
  310. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  311. return nil
  312. }
  313. func (s *Server) handleAccountReservationAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  314. if v.user != nil && v.user.Role == user.RoleAdmin {
  315. return errHTTPBadRequestMakesNoSenseForAdmin
  316. }
  317. req, err := readJSONWithLimit[apiAccountReservationRequest](r.Body, jsonBodyBytesLimit)
  318. if err != nil {
  319. return err
  320. }
  321. if !topicRegex.MatchString(req.Topic) {
  322. return errHTTPBadRequestTopicInvalid
  323. }
  324. everyone, err := user.ParsePermission(req.Everyone)
  325. if err != nil {
  326. return errHTTPBadRequestPermissionInvalid
  327. }
  328. if v.user.Tier == nil {
  329. return errHTTPUnauthorized
  330. }
  331. if err := s.userManager.CheckAllowAccess(v.user.Name, req.Topic); err != nil {
  332. return errHTTPConflictTopicReserved
  333. }
  334. hasReservation, err := s.userManager.HasReservation(v.user.Name, req.Topic)
  335. if err != nil {
  336. return err
  337. }
  338. if !hasReservation {
  339. reservations, err := s.userManager.ReservationsCount(v.user.Name)
  340. if err != nil {
  341. return err
  342. } else if reservations >= v.user.Tier.ReservationsLimit {
  343. return errHTTPTooManyRequestsLimitReservations
  344. }
  345. }
  346. owner, username := v.user.Name, v.user.Name
  347. if err := s.userManager.AllowAccess(owner, username, req.Topic, true, true); err != nil {
  348. return err
  349. }
  350. if err := s.userManager.AllowAccess(owner, user.Everyone, req.Topic, everyone.IsRead(), everyone.IsWrite()); err != nil {
  351. return err
  352. }
  353. w.Header().Set("Content-Type", "application/json")
  354. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  355. return nil
  356. }
  357. func (s *Server) handleAccountReservationDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  358. matches := accountReservationSingleRegex.FindStringSubmatch(r.URL.Path)
  359. if len(matches) != 2 {
  360. return errHTTPInternalErrorInvalidPath
  361. }
  362. topic := matches[1]
  363. if !topicRegex.MatchString(topic) {
  364. return errHTTPBadRequestTopicInvalid
  365. }
  366. authorized, err := s.userManager.HasReservation(v.user.Name, topic)
  367. if err != nil {
  368. return err
  369. } else if !authorized {
  370. return errHTTPUnauthorized
  371. }
  372. if err := s.userManager.ResetAccess(v.user.Name, topic); err != nil {
  373. return err
  374. }
  375. if err := s.userManager.ResetAccess(user.Everyone, topic); err != nil {
  376. return err
  377. }
  378. w.Header().Set("Content-Type", "application/json")
  379. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  380. return nil
  381. }
  382. func (s *Server) handleAccountCheckoutSessionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  383. req, err := readJSONWithLimit[apiAccountTierChangeRequest](r.Body, jsonBodyBytesLimit)
  384. if err != nil {
  385. return err
  386. }
  387. tier, err := s.userManager.Tier(req.Tier)
  388. if err != nil {
  389. return err
  390. }
  391. if tier.StripePriceID == "" {
  392. log.Info("Checkout: Downgrading to no tier")
  393. return errors.New("not a paid tier")
  394. } else if v.user.Billing != nil && v.user.Billing.StripeSubscriptionID != "" {
  395. log.Info("Checkout: Changing tier and subscription to %s", tier.Code)
  396. // Upgrade/downgrade tier
  397. sub, err := subscription.Get(v.user.Billing.StripeSubscriptionID, nil)
  398. if err != nil {
  399. return err
  400. }
  401. params := &stripe.SubscriptionParams{
  402. CancelAtPeriodEnd: stripe.Bool(false),
  403. ProrationBehavior: stripe.String(string(stripe.SubscriptionSchedulePhaseProrationBehaviorCreateProrations)),
  404. Items: []*stripe.SubscriptionItemsParams{
  405. {
  406. ID: stripe.String(sub.Items.Data[0].ID),
  407. Price: stripe.String(tier.StripePriceID),
  408. },
  409. },
  410. }
  411. _, err = subscription.Update(sub.ID, params)
  412. if err != nil {
  413. return err
  414. }
  415. response := &apiAccountCheckoutResponse{}
  416. w.Header().Set("Content-Type", "application/json")
  417. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  418. if err := json.NewEncoder(w).Encode(response); err != nil {
  419. return err
  420. }
  421. return nil
  422. } else {
  423. // Checkout flow
  424. log.Info("Checkout: No existing subscription, creating checkout flow")
  425. }
  426. successURL := s.config.BaseURL + accountCheckoutSuccessTemplate
  427. var stripeCustomerID *string
  428. if v.user.Billing != nil {
  429. stripeCustomerID = &v.user.Billing.StripeCustomerID
  430. }
  431. params := &stripe.CheckoutSessionParams{
  432. ClientReferenceID: &v.user.Name, // FIXME Should be user ID
  433. Customer: stripeCustomerID,
  434. SuccessURL: &successURL,
  435. Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
  436. LineItems: []*stripe.CheckoutSessionLineItemParams{
  437. {
  438. Price: stripe.String(tier.StripePriceID),
  439. Quantity: stripe.Int64(1),
  440. },
  441. },
  442. }
  443. sess, err := session.New(params)
  444. if err != nil {
  445. return err
  446. }
  447. response := &apiAccountCheckoutResponse{
  448. RedirectURL: sess.URL,
  449. }
  450. w.Header().Set("Content-Type", "application/json")
  451. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  452. if err := json.NewEncoder(w).Encode(response); err != nil {
  453. return err
  454. }
  455. return nil
  456. }
  457. func (s *Server) handleAccountCheckoutSessionSuccessGet(w http.ResponseWriter, r *http.Request, v *visitor) error {
  458. // We don't have a v.user in this endpoint, only a userManager!
  459. matches := accountCheckoutSuccessRegex.FindStringSubmatch(r.URL.Path)
  460. if len(matches) != 2 {
  461. return errHTTPInternalErrorInvalidPath
  462. }
  463. sessionID := matches[1]
  464. // FIXME how do I rate limit this?
  465. sess, err := session.Get(sessionID, nil)
  466. if err != nil {
  467. log.Warn("Stripe: %s", err)
  468. return errHTTPBadRequestInvalidStripeRequest
  469. } else if sess.Customer == nil || sess.Subscription == nil || sess.ClientReferenceID == "" {
  470. log.Warn("Stripe: Unexpected session, customer or subscription not found")
  471. return errHTTPBadRequestInvalidStripeRequest
  472. }
  473. sub, err := subscription.Get(sess.Subscription.ID, nil)
  474. if err != nil {
  475. return err
  476. } else if sub.Items == nil || len(sub.Items.Data) != 1 || sub.Items.Data[0].Price == nil {
  477. log.Error("Stripe: Unexpected subscription, expected exactly one line item")
  478. return errHTTPBadRequestInvalidStripeRequest
  479. }
  480. priceID := sub.Items.Data[0].Price.ID
  481. tier, err := s.userManager.TierByStripePrice(priceID)
  482. if err != nil {
  483. return err
  484. }
  485. u, err := s.userManager.User(sess.ClientReferenceID)
  486. if err != nil {
  487. return err
  488. }
  489. if u.Billing == nil {
  490. u.Billing = &user.Billing{}
  491. }
  492. u.Billing.StripeCustomerID = sess.Customer.ID
  493. u.Billing.StripeSubscriptionID = sess.Subscription.ID
  494. if err := s.userManager.ChangeBilling(u); err != nil {
  495. return err
  496. }
  497. if err := s.userManager.ChangeTier(u.Name, tier.Code); err != nil {
  498. return err
  499. }
  500. accountURL := s.config.BaseURL + "/account" // FIXME
  501. http.Redirect(w, r, accountURL, http.StatusSeeOther)
  502. return nil
  503. }
  504. func (s *Server) handleAccountBillingPortalSessionCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  505. if v.user.Billing == nil {
  506. return errHTTPBadRequestNotAPaidUser
  507. }
  508. params := &stripe.BillingPortalSessionParams{
  509. Customer: stripe.String(v.user.Billing.StripeCustomerID),
  510. ReturnURL: stripe.String(s.config.BaseURL),
  511. }
  512. ps, err := portalsession.New(params)
  513. if err != nil {
  514. return err
  515. }
  516. response := &apiAccountBillingPortalRedirectResponse{
  517. RedirectURL: ps.URL,
  518. }
  519. w.Header().Set("Content-Type", "application/json")
  520. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  521. if err := json.NewEncoder(w).Encode(response); err != nil {
  522. return err
  523. }
  524. return nil
  525. }
  526. func (s *Server) handleAccountBillingWebhookTrigger(w http.ResponseWriter, r *http.Request, v *visitor) error {
  527. // We don't have a v.user in this endpoint, only a userManager!
  528. stripeSignature := r.Header.Get("Stripe-Signature")
  529. if stripeSignature == "" {
  530. return errHTTPBadRequestInvalidStripeRequest
  531. }
  532. body, err := util.Peek(r.Body, stripeBodyBytesLimit)
  533. if err != nil {
  534. return err
  535. } else if body.LimitReached {
  536. return errHTTPEntityTooLargeJSONBody
  537. }
  538. event, err := webhook.ConstructEvent(body.PeekedBytes, stripeSignature, s.config.StripeWebhookKey)
  539. if err != nil {
  540. log.Warn("Stripe: invalid request: %s", err.Error())
  541. return errHTTPBadRequestInvalidStripeRequest
  542. } else if event.Data == nil || event.Data.Raw == nil {
  543. log.Warn("Stripe: invalid request, data is nil")
  544. return errHTTPBadRequestInvalidStripeRequest
  545. }
  546. log.Info("Stripe: webhook event %s received", event.Type)
  547. stripeCustomerID := gjson.GetBytes(event.Data.Raw, "customer")
  548. if !stripeCustomerID.Exists() {
  549. return errHTTPBadRequestInvalidStripeRequest
  550. }
  551. switch event.Type {
  552. case "checkout.session.completed":
  553. // Payment is successful and the subscription is created.
  554. // Provision the subscription, save the customer ID.
  555. return s.handleAccountBillingWebhookCheckoutCompleted(stripeCustomerID.String(), event.Data.Raw)
  556. case "customer.subscription.updated":
  557. return s.handleAccountBillingWebhookSubscriptionUpdated(stripeCustomerID.String(), event.Data.Raw)
  558. case "invoice.paid":
  559. // Continue to provision the subscription as payments continue to be made.
  560. // Store the status in your database and check when a user accesses your service.
  561. // This approach helps you avoid hitting rate limits.
  562. return nil // FIXME
  563. case "invoice.payment_failed":
  564. // The payment failed or the customer does not have a valid payment method.
  565. // The subscription becomes past_due. Notify your customer and send them to the
  566. // customer portal to update their payment information.
  567. return nil // FIXME
  568. default:
  569. log.Warn("Stripe: unhandled webhook %s", event.Type)
  570. return nil
  571. }
  572. }
  573. func (s *Server) handleAccountBillingWebhookCheckoutCompleted(stripeCustomerID string, event json.RawMessage) error {
  574. log.Info("Stripe: checkout completed for customer %s", stripeCustomerID)
  575. return nil
  576. }
  577. func (s *Server) handleAccountBillingWebhookSubscriptionUpdated(stripeCustomerID string, event json.RawMessage) error {
  578. status := gjson.GetBytes(event, "status")
  579. priceID := gjson.GetBytes(event, "items.data.0.price.id")
  580. if !status.Exists() || !priceID.Exists() {
  581. return errHTTPBadRequestInvalidStripeRequest
  582. }
  583. log.Info("Stripe: customer %s: subscription updated to %s, with price %s", stripeCustomerID, status, priceID)
  584. u, err := s.userManager.UserByStripeCustomer(stripeCustomerID)
  585. if err != nil {
  586. return err
  587. }
  588. tier, err := s.userManager.TierByStripePrice(priceID.String())
  589. if err != nil {
  590. return err
  591. }
  592. if err := s.userManager.ChangeTier(u.Name, tier.Code); err != nil {
  593. return err
  594. }
  595. return nil
  596. }