server_account.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. package server
  2. import (
  3. "encoding/json"
  4. "heckel.io/ntfy/log"
  5. "heckel.io/ntfy/user"
  6. "heckel.io/ntfy/util"
  7. "net/http"
  8. "net/netip"
  9. "strings"
  10. "time"
  11. )
  12. const (
  13. syncTopicAccountSyncEvent = "sync"
  14. tokenExpiryDuration = 72 * time.Hour // Extend tokens by this much
  15. )
  16. func (s *Server) handleAccountCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  17. u := v.User()
  18. if !u.IsAdmin() { // u may be nil, but that's fine
  19. if !s.config.EnableSignup {
  20. return errHTTPBadRequestSignupNotEnabled
  21. } else if u != nil {
  22. return errHTTPUnauthorized // Cannot create account from user context
  23. }
  24. if !v.AccountCreationAllowed() {
  25. return errHTTPTooManyRequestsLimitAccountCreation
  26. }
  27. }
  28. newAccount, err := readJSONWithLimit[apiAccountCreateRequest](r.Body, jsonBodyBytesLimit, false)
  29. if err != nil {
  30. return err
  31. }
  32. if existingUser, _ := s.userManager.User(newAccount.Username); existingUser != nil {
  33. return errHTTPConflictUserExists
  34. }
  35. logvr(v, r).Tag(tagAccount).Field("user_name", newAccount.Username).Info("Creating user %s", newAccount.Username)
  36. if err := s.userManager.AddUser(newAccount.Username, newAccount.Password, user.RoleUser); err != nil {
  37. return err
  38. }
  39. v.AccountCreated()
  40. return s.writeJSON(w, newSuccessResponse())
  41. }
  42. func (s *Server) handleAccountGet(w http.ResponseWriter, r *http.Request, v *visitor) error {
  43. info, err := v.Info()
  44. if err != nil {
  45. return err
  46. }
  47. logvr(v, r).Tag(tagAccount).Fields(visitorExtendedInfoContext(info)).Debug("Retrieving account stats")
  48. limits, stats := info.Limits, info.Stats
  49. response := &apiAccountResponse{
  50. Limits: &apiAccountLimits{
  51. Basis: string(limits.Basis),
  52. Messages: limits.MessageLimit,
  53. MessagesExpiryDuration: int64(limits.MessageExpiryDuration.Seconds()),
  54. Emails: limits.EmailLimit,
  55. Calls: limits.CallLimit,
  56. Reservations: limits.ReservationsLimit,
  57. AttachmentTotalSize: limits.AttachmentTotalSizeLimit,
  58. AttachmentFileSize: limits.AttachmentFileSizeLimit,
  59. AttachmentExpiryDuration: int64(limits.AttachmentExpiryDuration.Seconds()),
  60. AttachmentBandwidth: limits.AttachmentBandwidthLimit,
  61. },
  62. Stats: &apiAccountStats{
  63. Messages: stats.Messages,
  64. MessagesRemaining: stats.MessagesRemaining,
  65. Emails: stats.Emails,
  66. EmailsRemaining: stats.EmailsRemaining,
  67. Calls: stats.Calls,
  68. CallsRemaining: stats.CallsRemaining,
  69. Reservations: stats.Reservations,
  70. ReservationsRemaining: stats.ReservationsRemaining,
  71. AttachmentTotalSize: stats.AttachmentTotalSize,
  72. AttachmentTotalSizeRemaining: stats.AttachmentTotalSizeRemaining,
  73. },
  74. }
  75. u := v.User()
  76. if u != nil {
  77. response.Username = u.Name
  78. response.Role = string(u.Role)
  79. response.SyncTopic = u.SyncTopic
  80. if u.Prefs != nil {
  81. if u.Prefs.Language != nil {
  82. response.Language = *u.Prefs.Language
  83. }
  84. if u.Prefs.Notification != nil {
  85. response.Notification = u.Prefs.Notification
  86. }
  87. if u.Prefs.Subscriptions != nil {
  88. response.Subscriptions = u.Prefs.Subscriptions
  89. }
  90. }
  91. if u.Tier != nil {
  92. response.Tier = &apiAccountTier{
  93. Code: u.Tier.Code,
  94. Name: u.Tier.Name,
  95. }
  96. }
  97. if u.Billing.StripeCustomerID != "" {
  98. response.Billing = &apiAccountBilling{
  99. Customer: true,
  100. Subscription: u.Billing.StripeSubscriptionID != "",
  101. Status: string(u.Billing.StripeSubscriptionStatus),
  102. Interval: string(u.Billing.StripeSubscriptionInterval),
  103. PaidUntil: u.Billing.StripeSubscriptionPaidUntil.Unix(),
  104. CancelAt: u.Billing.StripeSubscriptionCancelAt.Unix(),
  105. }
  106. }
  107. if s.config.EnableReservations {
  108. reservations, err := s.userManager.Reservations(u.Name)
  109. if err != nil {
  110. return err
  111. }
  112. if len(reservations) > 0 {
  113. response.Reservations = make([]*apiAccountReservation, 0)
  114. for _, r := range reservations {
  115. response.Reservations = append(response.Reservations, &apiAccountReservation{
  116. Topic: r.Topic,
  117. Everyone: r.Everyone.String(),
  118. })
  119. }
  120. }
  121. }
  122. tokens, err := s.userManager.Tokens(u.ID)
  123. if err != nil {
  124. return err
  125. }
  126. if len(tokens) > 0 {
  127. response.Tokens = make([]*apiAccountTokenResponse, 0)
  128. for _, t := range tokens {
  129. var lastOrigin string
  130. if t.LastOrigin != netip.IPv4Unspecified() {
  131. lastOrigin = t.LastOrigin.String()
  132. }
  133. response.Tokens = append(response.Tokens, &apiAccountTokenResponse{
  134. Token: t.Value,
  135. Label: t.Label,
  136. LastAccess: t.LastAccess.Unix(),
  137. LastOrigin: lastOrigin,
  138. Expires: t.Expires.Unix(),
  139. })
  140. }
  141. }
  142. if s.config.TwilioAccount != "" {
  143. phoneNumbers, err := s.userManager.PhoneNumbers(u.ID)
  144. if err != nil {
  145. return err
  146. }
  147. if len(phoneNumbers) > 0 {
  148. response.PhoneNumbers = phoneNumbers
  149. }
  150. }
  151. } else {
  152. response.Username = user.Everyone
  153. response.Role = string(user.RoleAnonymous)
  154. }
  155. return s.writeJSON(w, response)
  156. }
  157. func (s *Server) handleAccountDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  158. req, err := readJSONWithLimit[apiAccountDeleteRequest](r.Body, jsonBodyBytesLimit, false)
  159. if err != nil {
  160. return err
  161. } else if req.Password == "" {
  162. return errHTTPBadRequest
  163. }
  164. u := v.User()
  165. if _, err := s.userManager.Authenticate(u.Name, req.Password); err != nil {
  166. return errHTTPBadRequestIncorrectPasswordConfirmation
  167. }
  168. if u.Billing.StripeSubscriptionID != "" {
  169. logvr(v, r).Tag(tagStripe).Info("Canceling billing subscription for user %s", u.Name)
  170. if _, err := s.stripe.CancelSubscription(u.Billing.StripeSubscriptionID); err != nil {
  171. return err
  172. }
  173. }
  174. if err := s.maybeRemoveMessagesAndExcessReservations(r, v, u, 0); err != nil {
  175. return err
  176. }
  177. logvr(v, r).Tag(tagAccount).Info("Marking user %s as deleted", u.Name)
  178. if err := s.userManager.MarkUserRemoved(u); err != nil {
  179. return err
  180. }
  181. return s.writeJSON(w, newSuccessResponse())
  182. }
  183. func (s *Server) handleAccountPasswordChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  184. req, err := readJSONWithLimit[apiAccountPasswordChangeRequest](r.Body, jsonBodyBytesLimit, false)
  185. if err != nil {
  186. return err
  187. } else if req.Password == "" || req.NewPassword == "" {
  188. return errHTTPBadRequest
  189. }
  190. u := v.User()
  191. if _, err := s.userManager.Authenticate(u.Name, req.Password); err != nil {
  192. return errHTTPBadRequestIncorrectPasswordConfirmation
  193. }
  194. logvr(v, r).Tag(tagAccount).Debug("Changing password for user %s", u.Name)
  195. if err := s.userManager.ChangePassword(u.Name, req.NewPassword); err != nil {
  196. return err
  197. }
  198. return s.writeJSON(w, newSuccessResponse())
  199. }
  200. func (s *Server) handleAccountTokenCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  201. req, err := readJSONWithLimit[apiAccountTokenIssueRequest](r.Body, jsonBodyBytesLimit, true) // Allow empty body!
  202. if err != nil {
  203. return err
  204. }
  205. var label string
  206. if req.Label != nil {
  207. label = *req.Label
  208. }
  209. expires := time.Now().Add(tokenExpiryDuration)
  210. if req.Expires != nil {
  211. expires = time.Unix(*req.Expires, 0)
  212. }
  213. u := v.User()
  214. logvr(v, r).
  215. Tag(tagAccount).
  216. Fields(log.Context{
  217. "token_label": label,
  218. "token_expires": expires,
  219. }).
  220. Debug("Creating token for user %s", u.Name)
  221. token, err := s.userManager.CreateToken(u.ID, label, expires, v.IP())
  222. if err != nil {
  223. return err
  224. }
  225. response := &apiAccountTokenResponse{
  226. Token: token.Value,
  227. Label: token.Label,
  228. LastAccess: token.LastAccess.Unix(),
  229. LastOrigin: token.LastOrigin.String(),
  230. Expires: token.Expires.Unix(),
  231. }
  232. return s.writeJSON(w, response)
  233. }
  234. func (s *Server) handleAccountTokenUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  235. u := v.User()
  236. req, err := readJSONWithLimit[apiAccountTokenUpdateRequest](r.Body, jsonBodyBytesLimit, true) // Allow empty body!
  237. if err != nil {
  238. return err
  239. } else if req.Token == "" {
  240. req.Token = u.Token
  241. if req.Token == "" {
  242. return errHTTPBadRequestNoTokenProvided
  243. }
  244. }
  245. var expires *time.Time
  246. if req.Expires != nil {
  247. expires = util.Time(time.Unix(*req.Expires, 0))
  248. } else if req.Label == nil {
  249. expires = util.Time(time.Now().Add(tokenExpiryDuration)) // If label/expires not set, extend token by 72 hours
  250. }
  251. logvr(v, r).
  252. Tag(tagAccount).
  253. Fields(log.Context{
  254. "token_label": req.Label,
  255. "token_expires": expires,
  256. }).
  257. Debug("Updating token for user %s as deleted", u.Name)
  258. token, err := s.userManager.ChangeToken(u.ID, req.Token, req.Label, expires)
  259. if err != nil {
  260. return err
  261. }
  262. response := &apiAccountTokenResponse{
  263. Token: token.Value,
  264. Label: token.Label,
  265. LastAccess: token.LastAccess.Unix(),
  266. LastOrigin: token.LastOrigin.String(),
  267. Expires: token.Expires.Unix(),
  268. }
  269. return s.writeJSON(w, response)
  270. }
  271. func (s *Server) handleAccountTokenDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  272. u := v.User()
  273. token := readParam(r, "X-Token", "Token") // DELETEs cannot have a body, and we don't want it in the path
  274. if token == "" {
  275. token = u.Token
  276. if token == "" {
  277. return errHTTPBadRequestNoTokenProvided
  278. }
  279. }
  280. if err := s.userManager.RemoveToken(u.ID, token); err != nil {
  281. return err
  282. }
  283. logvr(v, r).
  284. Tag(tagAccount).
  285. Field("token", token).
  286. Debug("Deleted token for user %s", u.Name)
  287. return s.writeJSON(w, newSuccessResponse())
  288. }
  289. func (s *Server) handleAccountSettingsChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  290. newPrefs, err := readJSONWithLimit[user.Prefs](r.Body, jsonBodyBytesLimit, false)
  291. if err != nil {
  292. return err
  293. }
  294. u := v.User()
  295. if u.Prefs == nil {
  296. u.Prefs = &user.Prefs{}
  297. }
  298. prefs := u.Prefs
  299. if newPrefs.Language != nil {
  300. prefs.Language = newPrefs.Language
  301. }
  302. if newPrefs.Notification != nil {
  303. if prefs.Notification == nil {
  304. prefs.Notification = &user.NotificationPrefs{}
  305. }
  306. if newPrefs.Notification.DeleteAfter != nil {
  307. prefs.Notification.DeleteAfter = newPrefs.Notification.DeleteAfter
  308. }
  309. if newPrefs.Notification.Sound != nil {
  310. prefs.Notification.Sound = newPrefs.Notification.Sound
  311. }
  312. if newPrefs.Notification.MinPriority != nil {
  313. prefs.Notification.MinPriority = newPrefs.Notification.MinPriority
  314. }
  315. }
  316. logvr(v, r).Tag(tagAccount).Debug("Changing account settings for user %s", u.Name)
  317. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  318. return err
  319. }
  320. return s.writeJSON(w, newSuccessResponse())
  321. }
  322. func (s *Server) handleAccountSubscriptionAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  323. newSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit, false)
  324. if err != nil {
  325. return err
  326. }
  327. u := v.User()
  328. prefs := u.Prefs
  329. if prefs == nil {
  330. prefs = &user.Prefs{}
  331. }
  332. for _, subscription := range prefs.Subscriptions {
  333. if newSubscription.BaseURL == subscription.BaseURL && newSubscription.Topic == subscription.Topic {
  334. return errHTTPConflictSubscriptionExists
  335. }
  336. }
  337. prefs.Subscriptions = append(prefs.Subscriptions, newSubscription)
  338. logvr(v, r).Tag(tagAccount).With(newSubscription).Debug("Adding subscription for user %s", u.Name)
  339. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  340. return err
  341. }
  342. return s.writeJSON(w, newSubscription)
  343. }
  344. func (s *Server) handleAccountSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  345. updatedSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit, false)
  346. if err != nil {
  347. return err
  348. }
  349. u := v.User()
  350. prefs := u.Prefs
  351. if prefs == nil || prefs.Subscriptions == nil {
  352. return errHTTPNotFound
  353. }
  354. var subscription *user.Subscription
  355. for _, sub := range prefs.Subscriptions {
  356. if sub.BaseURL == updatedSubscription.BaseURL && sub.Topic == updatedSubscription.Topic {
  357. sub.DisplayName = updatedSubscription.DisplayName
  358. subscription = sub
  359. break
  360. }
  361. }
  362. if subscription == nil {
  363. return errHTTPNotFound
  364. }
  365. logvr(v, r).Tag(tagAccount).With(subscription).Debug("Changing subscription for user %s", u.Name)
  366. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  367. return err
  368. }
  369. return s.writeJSON(w, subscription)
  370. }
  371. func (s *Server) handleAccountSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  372. // DELETEs cannot have a body, and we don't want it in the path
  373. deleteBaseURL := readParam(r, "X-BaseURL", "BaseURL")
  374. deleteTopic := readParam(r, "X-Topic", "Topic")
  375. u := v.User()
  376. prefs := u.Prefs
  377. if prefs == nil || prefs.Subscriptions == nil {
  378. return nil
  379. }
  380. newSubscriptions := make([]*user.Subscription, 0)
  381. for _, sub := range u.Prefs.Subscriptions {
  382. if sub.BaseURL == deleteBaseURL && sub.Topic == deleteTopic {
  383. logvr(v, r).Tag(tagAccount).With(sub).Debug("Removing subscription for user %s", u.Name)
  384. } else {
  385. newSubscriptions = append(newSubscriptions, sub)
  386. }
  387. }
  388. if len(newSubscriptions) < len(prefs.Subscriptions) {
  389. prefs.Subscriptions = newSubscriptions
  390. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  391. return err
  392. }
  393. }
  394. return s.writeJSON(w, newSuccessResponse())
  395. }
  396. // handleAccountReservationAdd adds a topic reservation for the logged-in user, but only if the user has a tier
  397. // with enough remaining reservations left, or if the user is an admin. Admins can always reserve a topic, unless
  398. // it is already reserved by someone else.
  399. func (s *Server) handleAccountReservationAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  400. u := v.User()
  401. req, err := readJSONWithLimit[apiAccountReservationRequest](r.Body, jsonBodyBytesLimit, false)
  402. if err != nil {
  403. return err
  404. }
  405. if !topicRegex.MatchString(req.Topic) {
  406. return errHTTPBadRequestTopicInvalid
  407. }
  408. everyone, err := user.ParsePermission(req.Everyone)
  409. if err != nil {
  410. return errHTTPBadRequestPermissionInvalid
  411. }
  412. // Check if we are allowed to reserve this topic
  413. if u.IsUser() && u.Tier == nil {
  414. return errHTTPUnauthorized
  415. } else if err := s.userManager.AllowReservation(u.Name, req.Topic); err != nil {
  416. return errHTTPConflictTopicReserved
  417. } else if u.IsUser() {
  418. hasReservation, err := s.userManager.HasReservation(u.Name, req.Topic)
  419. if err != nil {
  420. return err
  421. }
  422. if !hasReservation {
  423. reservations, err := s.userManager.ReservationsCount(u.Name)
  424. if err != nil {
  425. return err
  426. } else if reservations >= u.Tier.ReservationLimit {
  427. return errHTTPTooManyRequestsLimitReservations
  428. }
  429. }
  430. }
  431. // Actually add the reservation
  432. logvr(v, r).
  433. Tag(tagAccount).
  434. Fields(log.Context{
  435. "topic": req.Topic,
  436. "everyone": everyone.String(),
  437. }).
  438. Debug("Adding topic reservation")
  439. if err := s.userManager.AddReservation(u.Name, req.Topic, everyone); err != nil {
  440. return err
  441. }
  442. // Kill existing subscribers
  443. t, err := s.topicFromID(req.Topic)
  444. if err != nil {
  445. return err
  446. }
  447. t.CancelSubscribersExceptUser(u.ID)
  448. return s.writeJSON(w, newSuccessResponse())
  449. }
  450. // handleAccountReservationDelete deletes a topic reservation if it is owned by the current user
  451. func (s *Server) handleAccountReservationDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  452. matches := apiAccountReservationSingleRegex.FindStringSubmatch(r.URL.Path)
  453. if len(matches) != 2 {
  454. return errHTTPInternalErrorInvalidPath
  455. }
  456. topic := matches[1]
  457. if !topicRegex.MatchString(topic) {
  458. return errHTTPBadRequestTopicInvalid
  459. }
  460. u := v.User()
  461. authorized, err := s.userManager.HasReservation(u.Name, topic)
  462. if err != nil {
  463. return err
  464. } else if !authorized {
  465. return errHTTPUnauthorized
  466. }
  467. deleteMessages := readBoolParam(r, false, "X-Delete-Messages", "Delete-Messages")
  468. logvr(v, r).
  469. Tag(tagAccount).
  470. Fields(log.Context{
  471. "topic": topic,
  472. "delete_messages": deleteMessages,
  473. }).
  474. Debug("Removing topic reservation")
  475. if err := s.userManager.RemoveReservations(u.Name, topic); err != nil {
  476. return err
  477. }
  478. if deleteMessages {
  479. if err := s.messageCache.ExpireMessages(topic); err != nil {
  480. return err
  481. }
  482. s.pruneMessages()
  483. }
  484. return s.writeJSON(w, newSuccessResponse())
  485. }
  486. // maybeRemoveMessagesAndExcessReservations deletes topic reservations for the given user (if too many for tier),
  487. // and marks associated messages for the topics as deleted. This also eventually deletes attachments.
  488. // The process relies on the manager to perform the actual deletions (see runManager).
  489. func (s *Server) maybeRemoveMessagesAndExcessReservations(r *http.Request, v *visitor, u *user.User, reservationsLimit int64) error {
  490. reservations, err := s.userManager.Reservations(u.Name)
  491. if err != nil {
  492. return err
  493. } else if int64(len(reservations)) <= reservationsLimit {
  494. logvr(v, r).Tag(tagAccount).Debug("No excess reservations to remove")
  495. return nil
  496. }
  497. topics := make([]string, 0)
  498. for i := int64(len(reservations)) - 1; i >= reservationsLimit; i-- {
  499. topics = append(topics, reservations[i].Topic)
  500. }
  501. logvr(v, r).Tag(tagAccount).Info("Removing excess reservations for topics %s", strings.Join(topics, ", "))
  502. if err := s.userManager.RemoveReservations(u.Name, topics...); err != nil {
  503. return err
  504. }
  505. if err := s.messageCache.ExpireMessages(topics...); err != nil {
  506. return err
  507. }
  508. go s.pruneMessages()
  509. return nil
  510. }
  511. func (s *Server) handleAccountPhoneNumberVerify(w http.ResponseWriter, r *http.Request, v *visitor) error {
  512. u := v.User()
  513. req, err := readJSONWithLimit[apiAccountPhoneNumberVerifyRequest](r.Body, jsonBodyBytesLimit, false)
  514. if err != nil {
  515. return err
  516. } else if !phoneNumberRegex.MatchString(req.Number) {
  517. return errHTTPBadRequestPhoneNumberInvalid
  518. } else if req.Channel != "sms" && req.Channel != "call" {
  519. return errHTTPBadRequestPhoneNumberVerifyChannelInvalid
  520. }
  521. // Check user is allowed to add phone numbers
  522. if u == nil || (u.IsUser() && u.Tier == nil) {
  523. return errHTTPUnauthorized
  524. } else if u.IsUser() && u.Tier.CallLimit == 0 {
  525. return errHTTPUnauthorized
  526. }
  527. // Check if phone number exists
  528. phoneNumbers, err := s.userManager.PhoneNumbers(u.ID)
  529. if err != nil {
  530. return err
  531. } else if util.Contains(phoneNumbers, req.Number) {
  532. return errHTTPConflictPhoneNumberExists
  533. }
  534. // Actually add the unverified number, and send verification
  535. logvr(v, r).Tag(tagAccount).Field("phone_number", req.Number).Debug("Sending phone number verification")
  536. if err := s.verifyPhoneNumber(v, r, req.Number, req.Channel); err != nil {
  537. return err
  538. }
  539. return s.writeJSON(w, newSuccessResponse())
  540. }
  541. func (s *Server) handleAccountPhoneNumberAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  542. u := v.User()
  543. req, err := readJSONWithLimit[apiAccountPhoneNumberAddRequest](r.Body, jsonBodyBytesLimit, false)
  544. if err != nil {
  545. return err
  546. }
  547. if !phoneNumberRegex.MatchString(req.Number) {
  548. return errHTTPBadRequestPhoneNumberInvalid
  549. }
  550. if err := s.verifyPhoneNumberCheck(v, r, req.Number, req.Code); err != nil {
  551. return err
  552. }
  553. logvr(v, r).Tag(tagAccount).Field("phone_number", req.Number).Debug("Adding phone number as verified")
  554. if err := s.userManager.AddPhoneNumber(u.ID, req.Number); err != nil {
  555. return err
  556. }
  557. return s.writeJSON(w, newSuccessResponse())
  558. }
  559. func (s *Server) handleAccountPhoneNumberDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  560. u := v.User()
  561. req, err := readJSONWithLimit[apiAccountPhoneNumberAddRequest](r.Body, jsonBodyBytesLimit, false)
  562. if err != nil {
  563. return err
  564. }
  565. if !phoneNumberRegex.MatchString(req.Number) {
  566. return errHTTPBadRequestPhoneNumberInvalid
  567. }
  568. logvr(v, r).Tag(tagAccount).Field("phone_number", req.Number).Debug("Deleting phone number")
  569. if err := s.userManager.RemovePhoneNumber(u.ID, req.Number); err != nil {
  570. return err
  571. }
  572. return s.writeJSON(w, newSuccessResponse())
  573. }
  574. // publishSyncEventAsync kicks of a Go routine to publish a sync message to the user's sync topic
  575. func (s *Server) publishSyncEventAsync(v *visitor) {
  576. go func() {
  577. if err := s.publishSyncEvent(v); err != nil {
  578. logv(v).Err(err).Trace("Error publishing to user's sync topic")
  579. }
  580. }()
  581. }
  582. // publishSyncEvent publishes a sync message to the user's sync topic
  583. func (s *Server) publishSyncEvent(v *visitor) error {
  584. u := v.User()
  585. if u == nil || u.SyncTopic == "" {
  586. return nil
  587. }
  588. logv(v).Field("sync_topic", u.SyncTopic).Trace("Publishing sync event to user's sync topic")
  589. syncTopic, err := s.topicFromID(u.SyncTopic)
  590. if err != nil {
  591. return err
  592. }
  593. messageBytes, err := json.Marshal(&apiAccountSyncTopicResponse{Event: syncTopicAccountSyncEvent})
  594. if err != nil {
  595. return err
  596. }
  597. m := newDefaultMessage(syncTopic.ID, string(messageBytes))
  598. if err := syncTopic.Publish(v, m); err != nil {
  599. return err
  600. }
  601. return nil
  602. }