server_account.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. package server
  2. import (
  3. "encoding/json"
  4. "heckel.io/ntfy/v2/log"
  5. "heckel.io/ntfy/v2/user"
  6. "heckel.io/ntfy/v2/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 s.webPush != nil && u.ID != "" {
  169. if err := s.webPush.RemoveSubscriptionsByUserID(u.ID); err != nil {
  170. logvr(v, r).Err(err).Warn("Error removing web push subscriptions for %s", u.Name)
  171. }
  172. }
  173. if u.Billing.StripeSubscriptionID != "" {
  174. logvr(v, r).Tag(tagStripe).Info("Canceling billing subscription for user %s", u.Name)
  175. if _, err := s.stripe.CancelSubscription(u.Billing.StripeSubscriptionID); err != nil {
  176. return err
  177. }
  178. }
  179. if err := s.maybeRemoveMessagesAndExcessReservations(r, v, u, 0); err != nil {
  180. return err
  181. }
  182. logvr(v, r).Tag(tagAccount).Info("Marking user %s as deleted", u.Name)
  183. if err := s.userManager.MarkUserRemoved(u); err != nil {
  184. return err
  185. }
  186. return s.writeJSON(w, newSuccessResponse())
  187. }
  188. func (s *Server) handleAccountPasswordChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  189. req, err := readJSONWithLimit[apiAccountPasswordChangeRequest](r.Body, jsonBodyBytesLimit, false)
  190. if err != nil {
  191. return err
  192. } else if req.Password == "" || req.NewPassword == "" {
  193. return errHTTPBadRequest
  194. }
  195. u := v.User()
  196. if _, err := s.userManager.Authenticate(u.Name, req.Password); err != nil {
  197. return errHTTPBadRequestIncorrectPasswordConfirmation
  198. }
  199. logvr(v, r).Tag(tagAccount).Debug("Changing password for user %s", u.Name)
  200. if err := s.userManager.ChangePassword(u.Name, req.NewPassword); err != nil {
  201. return err
  202. }
  203. return s.writeJSON(w, newSuccessResponse())
  204. }
  205. func (s *Server) handleAccountTokenCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  206. req, err := readJSONWithLimit[apiAccountTokenIssueRequest](r.Body, jsonBodyBytesLimit, true) // Allow empty body!
  207. if err != nil {
  208. return err
  209. }
  210. var label string
  211. if req.Label != nil {
  212. label = *req.Label
  213. }
  214. expires := time.Now().Add(tokenExpiryDuration)
  215. if req.Expires != nil {
  216. expires = time.Unix(*req.Expires, 0)
  217. }
  218. u := v.User()
  219. logvr(v, r).
  220. Tag(tagAccount).
  221. Fields(log.Context{
  222. "token_label": label,
  223. "token_expires": expires,
  224. }).
  225. Debug("Creating token for user %s", u.Name)
  226. token, err := s.userManager.CreateToken(u.ID, label, expires, v.IP())
  227. if err != nil {
  228. return err
  229. }
  230. response := &apiAccountTokenResponse{
  231. Token: token.Value,
  232. Label: token.Label,
  233. LastAccess: token.LastAccess.Unix(),
  234. LastOrigin: token.LastOrigin.String(),
  235. Expires: token.Expires.Unix(),
  236. }
  237. return s.writeJSON(w, response)
  238. }
  239. func (s *Server) handleAccountTokenUpdate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  240. u := v.User()
  241. req, err := readJSONWithLimit[apiAccountTokenUpdateRequest](r.Body, jsonBodyBytesLimit, true) // Allow empty body!
  242. if err != nil {
  243. return err
  244. } else if req.Token == "" {
  245. req.Token = u.Token
  246. if req.Token == "" {
  247. return errHTTPBadRequestNoTokenProvided
  248. }
  249. }
  250. var expires *time.Time
  251. if req.Expires != nil {
  252. expires = util.Time(time.Unix(*req.Expires, 0))
  253. } else if req.Label == nil {
  254. expires = util.Time(time.Now().Add(tokenExpiryDuration)) // If label/expires not set, extend token by 72 hours
  255. }
  256. logvr(v, r).
  257. Tag(tagAccount).
  258. Fields(log.Context{
  259. "token_label": req.Label,
  260. "token_expires": expires,
  261. }).
  262. Debug("Updating token for user %s as deleted", u.Name)
  263. token, err := s.userManager.ChangeToken(u.ID, req.Token, req.Label, expires)
  264. if err != nil {
  265. return err
  266. }
  267. response := &apiAccountTokenResponse{
  268. Token: token.Value,
  269. Label: token.Label,
  270. LastAccess: token.LastAccess.Unix(),
  271. LastOrigin: token.LastOrigin.String(),
  272. Expires: token.Expires.Unix(),
  273. }
  274. return s.writeJSON(w, response)
  275. }
  276. func (s *Server) handleAccountTokenDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  277. u := v.User()
  278. token := readParam(r, "X-Token", "Token") // DELETEs cannot have a body, and we don't want it in the path
  279. if token == "" {
  280. token = u.Token
  281. if token == "" {
  282. return errHTTPBadRequestNoTokenProvided
  283. }
  284. }
  285. if err := s.userManager.RemoveToken(u.ID, token); err != nil {
  286. return err
  287. }
  288. logvr(v, r).
  289. Tag(tagAccount).
  290. Field("token", token).
  291. Debug("Deleted token for user %s", u.Name)
  292. return s.writeJSON(w, newSuccessResponse())
  293. }
  294. func (s *Server) handleAccountSettingsChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  295. newPrefs, err := readJSONWithLimit[user.Prefs](r.Body, jsonBodyBytesLimit, false)
  296. if err != nil {
  297. return err
  298. }
  299. u := v.User()
  300. if u.Prefs == nil {
  301. u.Prefs = &user.Prefs{}
  302. }
  303. prefs := u.Prefs
  304. if newPrefs.Language != nil {
  305. prefs.Language = newPrefs.Language
  306. }
  307. if newPrefs.Notification != nil {
  308. if prefs.Notification == nil {
  309. prefs.Notification = &user.NotificationPrefs{}
  310. }
  311. if newPrefs.Notification.DeleteAfter != nil {
  312. prefs.Notification.DeleteAfter = newPrefs.Notification.DeleteAfter
  313. }
  314. if newPrefs.Notification.Sound != nil {
  315. prefs.Notification.Sound = newPrefs.Notification.Sound
  316. }
  317. if newPrefs.Notification.MinPriority != nil {
  318. prefs.Notification.MinPriority = newPrefs.Notification.MinPriority
  319. }
  320. }
  321. logvr(v, r).Tag(tagAccount).Debug("Changing account settings for user %s", u.Name)
  322. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  323. return err
  324. }
  325. return s.writeJSON(w, newSuccessResponse())
  326. }
  327. func (s *Server) handleAccountSubscriptionAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  328. newSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit, false)
  329. if err != nil {
  330. return err
  331. }
  332. u := v.User()
  333. prefs := u.Prefs
  334. if prefs == nil {
  335. prefs = &user.Prefs{}
  336. }
  337. for _, subscription := range prefs.Subscriptions {
  338. if newSubscription.BaseURL == subscription.BaseURL && newSubscription.Topic == subscription.Topic {
  339. return errHTTPConflictSubscriptionExists
  340. }
  341. }
  342. prefs.Subscriptions = append(prefs.Subscriptions, newSubscription)
  343. logvr(v, r).Tag(tagAccount).With(newSubscription).Debug("Adding subscription for user %s", u.Name)
  344. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  345. return err
  346. }
  347. return s.writeJSON(w, newSubscription)
  348. }
  349. func (s *Server) handleAccountSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  350. updatedSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit, false)
  351. if err != nil {
  352. return err
  353. }
  354. u := v.User()
  355. prefs := u.Prefs
  356. if prefs == nil || prefs.Subscriptions == nil {
  357. return errHTTPNotFound
  358. }
  359. var subscription *user.Subscription
  360. for _, sub := range prefs.Subscriptions {
  361. if sub.BaseURL == updatedSubscription.BaseURL && sub.Topic == updatedSubscription.Topic {
  362. sub.DisplayName = updatedSubscription.DisplayName
  363. subscription = sub
  364. break
  365. }
  366. }
  367. if subscription == nil {
  368. return errHTTPNotFound
  369. }
  370. logvr(v, r).Tag(tagAccount).With(subscription).Debug("Changing subscription for user %s", u.Name)
  371. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  372. return err
  373. }
  374. return s.writeJSON(w, subscription)
  375. }
  376. func (s *Server) handleAccountSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  377. // DELETEs cannot have a body, and we don't want it in the path
  378. deleteBaseURL := readParam(r, "X-BaseURL", "BaseURL")
  379. deleteTopic := readParam(r, "X-Topic", "Topic")
  380. u := v.User()
  381. prefs := u.Prefs
  382. if prefs == nil || prefs.Subscriptions == nil {
  383. return nil
  384. }
  385. newSubscriptions := make([]*user.Subscription, 0)
  386. for _, sub := range u.Prefs.Subscriptions {
  387. if sub.BaseURL == deleteBaseURL && sub.Topic == deleteTopic {
  388. logvr(v, r).Tag(tagAccount).With(sub).Debug("Removing subscription for user %s", u.Name)
  389. } else {
  390. newSubscriptions = append(newSubscriptions, sub)
  391. }
  392. }
  393. if len(newSubscriptions) < len(prefs.Subscriptions) {
  394. prefs.Subscriptions = newSubscriptions
  395. if err := s.userManager.ChangeSettings(u.ID, prefs); err != nil {
  396. return err
  397. }
  398. }
  399. return s.writeJSON(w, newSuccessResponse())
  400. }
  401. // handleAccountReservationAdd adds a topic reservation for the logged-in user, but only if the user has a tier
  402. // with enough remaining reservations left, or if the user is an admin. Admins can always reserve a topic, unless
  403. // it is already reserved by someone else.
  404. func (s *Server) handleAccountReservationAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  405. u := v.User()
  406. req, err := readJSONWithLimit[apiAccountReservationRequest](r.Body, jsonBodyBytesLimit, false)
  407. if err != nil {
  408. return err
  409. }
  410. if !topicRegex.MatchString(req.Topic) {
  411. return errHTTPBadRequestTopicInvalid
  412. }
  413. everyone, err := user.ParsePermission(req.Everyone)
  414. if err != nil {
  415. return errHTTPBadRequestPermissionInvalid
  416. }
  417. // Check if we are allowed to reserve this topic
  418. if u.IsUser() && u.Tier == nil {
  419. return errHTTPUnauthorized
  420. } else if err := s.userManager.AllowReservation(u.Name, req.Topic); err != nil {
  421. return errHTTPConflictTopicReserved
  422. } else if u.IsUser() {
  423. hasReservation, err := s.userManager.HasReservation(u.Name, req.Topic)
  424. if err != nil {
  425. return err
  426. }
  427. if !hasReservation {
  428. reservations, err := s.userManager.ReservationsCount(u.Name)
  429. if err != nil {
  430. return err
  431. } else if reservations >= u.Tier.ReservationLimit {
  432. return errHTTPTooManyRequestsLimitReservations
  433. }
  434. }
  435. }
  436. // Actually add the reservation
  437. logvr(v, r).
  438. Tag(tagAccount).
  439. Fields(log.Context{
  440. "topic": req.Topic,
  441. "everyone": everyone.String(),
  442. }).
  443. Debug("Adding topic reservation")
  444. if err := s.userManager.AddReservation(u.Name, req.Topic, everyone); err != nil {
  445. return err
  446. }
  447. // Kill existing subscribers
  448. t, err := s.topicFromID(req.Topic)
  449. if err != nil {
  450. return err
  451. }
  452. t.CancelSubscribersExceptUser(u.ID)
  453. return s.writeJSON(w, newSuccessResponse())
  454. }
  455. // handleAccountReservationDelete deletes a topic reservation if it is owned by the current user
  456. func (s *Server) handleAccountReservationDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  457. matches := apiAccountReservationSingleRegex.FindStringSubmatch(r.URL.Path)
  458. if len(matches) != 2 {
  459. return errHTTPInternalErrorInvalidPath
  460. }
  461. topic := matches[1]
  462. if !topicRegex.MatchString(topic) {
  463. return errHTTPBadRequestTopicInvalid
  464. }
  465. u := v.User()
  466. authorized, err := s.userManager.HasReservation(u.Name, topic)
  467. if err != nil {
  468. return err
  469. } else if !authorized {
  470. return errHTTPUnauthorized
  471. }
  472. deleteMessages := readBoolParam(r, false, "X-Delete-Messages", "Delete-Messages")
  473. logvr(v, r).
  474. Tag(tagAccount).
  475. Fields(log.Context{
  476. "topic": topic,
  477. "delete_messages": deleteMessages,
  478. }).
  479. Debug("Removing topic reservation")
  480. if err := s.userManager.RemoveReservations(u.Name, topic); err != nil {
  481. return err
  482. }
  483. if deleteMessages {
  484. if err := s.messageCache.ExpireMessages(topic); err != nil {
  485. return err
  486. }
  487. s.pruneMessages()
  488. }
  489. return s.writeJSON(w, newSuccessResponse())
  490. }
  491. // maybeRemoveMessagesAndExcessReservations deletes topic reservations for the given user (if too many for tier),
  492. // and marks associated messages for the topics as deleted. This also eventually deletes attachments.
  493. // The process relies on the manager to perform the actual deletions (see runManager).
  494. func (s *Server) maybeRemoveMessagesAndExcessReservations(r *http.Request, v *visitor, u *user.User, reservationsLimit int64) error {
  495. reservations, err := s.userManager.Reservations(u.Name)
  496. if err != nil {
  497. return err
  498. } else if int64(len(reservations)) <= reservationsLimit {
  499. logvr(v, r).Tag(tagAccount).Debug("No excess reservations to remove")
  500. return nil
  501. }
  502. topics := make([]string, 0)
  503. for i := int64(len(reservations)) - 1; i >= reservationsLimit; i-- {
  504. topics = append(topics, reservations[i].Topic)
  505. }
  506. logvr(v, r).Tag(tagAccount).Info("Removing excess reservations for topics %s", strings.Join(topics, ", "))
  507. if err := s.userManager.RemoveReservations(u.Name, topics...); err != nil {
  508. return err
  509. }
  510. if err := s.messageCache.ExpireMessages(topics...); err != nil {
  511. return err
  512. }
  513. go s.pruneMessages()
  514. return nil
  515. }
  516. func (s *Server) handleAccountPhoneNumberVerify(w http.ResponseWriter, r *http.Request, v *visitor) error {
  517. u := v.User()
  518. req, err := readJSONWithLimit[apiAccountPhoneNumberVerifyRequest](r.Body, jsonBodyBytesLimit, false)
  519. if err != nil {
  520. return err
  521. } else if !phoneNumberRegex.MatchString(req.Number) {
  522. return errHTTPBadRequestPhoneNumberInvalid
  523. } else if req.Channel != "sms" && req.Channel != "call" {
  524. return errHTTPBadRequestPhoneNumberVerifyChannelInvalid
  525. }
  526. // Check user is allowed to add phone numbers
  527. if u == nil || (u.IsUser() && u.Tier == nil) {
  528. return errHTTPUnauthorized
  529. } else if u.IsUser() && u.Tier.CallLimit == 0 {
  530. return errHTTPUnauthorized
  531. }
  532. // Check if phone number exists
  533. phoneNumbers, err := s.userManager.PhoneNumbers(u.ID)
  534. if err != nil {
  535. return err
  536. } else if util.Contains(phoneNumbers, req.Number) {
  537. return errHTTPConflictPhoneNumberExists
  538. }
  539. // Actually add the unverified number, and send verification
  540. logvr(v, r).Tag(tagAccount).Field("phone_number", req.Number).Debug("Sending phone number verification")
  541. if err := s.verifyPhoneNumber(v, r, req.Number, req.Channel); err != nil {
  542. return err
  543. }
  544. return s.writeJSON(w, newSuccessResponse())
  545. }
  546. func (s *Server) handleAccountPhoneNumberAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  547. u := v.User()
  548. req, err := readJSONWithLimit[apiAccountPhoneNumberAddRequest](r.Body, jsonBodyBytesLimit, false)
  549. if err != nil {
  550. return err
  551. }
  552. if !phoneNumberRegex.MatchString(req.Number) {
  553. return errHTTPBadRequestPhoneNumberInvalid
  554. }
  555. if err := s.verifyPhoneNumberCheck(v, r, req.Number, req.Code); err != nil {
  556. return err
  557. }
  558. logvr(v, r).Tag(tagAccount).Field("phone_number", req.Number).Debug("Adding phone number as verified")
  559. if err := s.userManager.AddPhoneNumber(u.ID, req.Number); err != nil {
  560. return err
  561. }
  562. return s.writeJSON(w, newSuccessResponse())
  563. }
  564. func (s *Server) handleAccountPhoneNumberDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  565. u := v.User()
  566. req, err := readJSONWithLimit[apiAccountPhoneNumberAddRequest](r.Body, jsonBodyBytesLimit, false)
  567. if err != nil {
  568. return err
  569. }
  570. if !phoneNumberRegex.MatchString(req.Number) {
  571. return errHTTPBadRequestPhoneNumberInvalid
  572. }
  573. logvr(v, r).Tag(tagAccount).Field("phone_number", req.Number).Debug("Deleting phone number")
  574. if err := s.userManager.RemovePhoneNumber(u.ID, req.Number); err != nil {
  575. return err
  576. }
  577. return s.writeJSON(w, newSuccessResponse())
  578. }
  579. // publishSyncEventAsync kicks of a Go routine to publish a sync message to the user's sync topic
  580. func (s *Server) publishSyncEventAsync(v *visitor) {
  581. go func() {
  582. if err := s.publishSyncEvent(v); err != nil {
  583. logv(v).Err(err).Trace("Error publishing to user's sync topic")
  584. }
  585. }()
  586. }
  587. // publishSyncEvent publishes a sync message to the user's sync topic
  588. func (s *Server) publishSyncEvent(v *visitor) error {
  589. u := v.User()
  590. if u == nil || u.SyncTopic == "" {
  591. return nil
  592. }
  593. logv(v).Field("sync_topic", u.SyncTopic).Trace("Publishing sync event to user's sync topic")
  594. syncTopic, err := s.topicFromID(u.SyncTopic)
  595. if err != nil {
  596. return err
  597. }
  598. messageBytes, err := json.Marshal(&apiAccountSyncTopicResponse{Event: syncTopicAccountSyncEvent})
  599. if err != nil {
  600. return err
  601. }
  602. m := newDefaultMessage(syncTopic.ID, string(messageBytes))
  603. if err := syncTopic.Publish(v, m); err != nil {
  604. return err
  605. }
  606. return nil
  607. }