server_account.go 20 KB

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