server_account.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. "strings"
  9. )
  10. const (
  11. subscriptionIDLength = 16
  12. subscriptionIDPrefix = "su_"
  13. syncTopicAccountSyncEvent = "sync"
  14. )
  15. func (s *Server) handleAccountCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  16. admin := v.user != nil && v.user.Role == user.RoleAdmin
  17. if !admin {
  18. if !s.config.EnableSignup {
  19. return errHTTPBadRequestSignupNotEnabled
  20. } else if v.user != nil {
  21. return errHTTPUnauthorized // Cannot create account from user context
  22. }
  23. if err := v.AccountCreationAllowed(); err != nil {
  24. return errHTTPTooManyRequestsLimitAccountCreation
  25. }
  26. }
  27. newAccount, err := readJSONWithLimit[apiAccountCreateRequest](r.Body, jsonBodyBytesLimit)
  28. if err != nil {
  29. return err
  30. }
  31. if existingUser, _ := s.userManager.User(newAccount.Username); existingUser != nil {
  32. return errHTTPConflictUserExists
  33. }
  34. if err := s.userManager.AddUser(newAccount.Username, newAccount.Password, user.RoleUser); err != nil { // TODO this should return a User
  35. return err
  36. }
  37. return s.writeJSON(w, newSuccessResponse())
  38. }
  39. func (s *Server) handleAccountGet(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  40. info, err := v.Info()
  41. if err != nil {
  42. return err
  43. }
  44. limits, stats := info.Limits, info.Stats
  45. response := &apiAccountResponse{
  46. Limits: &apiAccountLimits{
  47. Basis: string(limits.Basis),
  48. Messages: limits.MessageLimit,
  49. MessagesExpiryDuration: int64(limits.MessageExpiryDuration.Seconds()),
  50. Emails: limits.EmailLimit,
  51. Reservations: limits.ReservationsLimit,
  52. AttachmentTotalSize: limits.AttachmentTotalSizeLimit,
  53. AttachmentFileSize: limits.AttachmentFileSizeLimit,
  54. AttachmentExpiryDuration: int64(limits.AttachmentExpiryDuration.Seconds()),
  55. AttachmentBandwidth: limits.AttachmentBandwidthLimit,
  56. },
  57. Stats: &apiAccountStats{
  58. Messages: stats.Messages,
  59. MessagesRemaining: stats.MessagesRemaining,
  60. Emails: stats.Emails,
  61. EmailsRemaining: stats.EmailsRemaining,
  62. Reservations: stats.Reservations,
  63. ReservationsRemaining: stats.ReservationsRemaining,
  64. AttachmentTotalSize: stats.AttachmentTotalSize,
  65. AttachmentTotalSizeRemaining: stats.AttachmentTotalSizeRemaining,
  66. },
  67. }
  68. if v.user != nil {
  69. response.Username = v.user.Name
  70. response.Role = string(v.user.Role)
  71. response.SyncTopic = v.user.SyncTopic
  72. if v.user.Prefs != nil {
  73. if v.user.Prefs.Language != nil {
  74. response.Language = *v.user.Prefs.Language
  75. }
  76. if v.user.Prefs.Notification != nil {
  77. response.Notification = v.user.Prefs.Notification
  78. }
  79. if v.user.Prefs.Subscriptions != nil {
  80. response.Subscriptions = v.user.Prefs.Subscriptions
  81. }
  82. }
  83. if v.user.Tier != nil {
  84. response.Tier = &apiAccountTier{
  85. Code: v.user.Tier.Code,
  86. Name: v.user.Tier.Name,
  87. }
  88. }
  89. if v.user.Billing.StripeCustomerID != "" {
  90. response.Billing = &apiAccountBilling{
  91. Customer: true,
  92. Subscription: v.user.Billing.StripeSubscriptionID != "",
  93. Status: string(v.user.Billing.StripeSubscriptionStatus),
  94. PaidUntil: v.user.Billing.StripeSubscriptionPaidUntil.Unix(),
  95. CancelAt: v.user.Billing.StripeSubscriptionCancelAt.Unix(),
  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. return s.writeJSON(w, response)
  116. }
  117. func (s *Server) handleAccountDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  118. req, err := readJSONWithLimit[apiAccountDeleteRequest](r.Body, jsonBodyBytesLimit)
  119. if err != nil {
  120. return err
  121. } else if req.Password == "" {
  122. return errHTTPBadRequest
  123. }
  124. if _, err := s.userManager.Authenticate(v.user.Name, req.Password); err != nil {
  125. return errHTTPBadRequestIncorrectPasswordConfirmation
  126. }
  127. if v.user.Billing.StripeSubscriptionID != "" {
  128. log.Info("%s Canceling billing subscription %s", logHTTPPrefix(v, r), v.user.Billing.StripeSubscriptionID)
  129. if _, err := s.stripe.CancelSubscription(v.user.Billing.StripeSubscriptionID); err != nil {
  130. return err
  131. }
  132. }
  133. if err := s.maybeRemoveMessagesAndExcessReservations(logHTTPPrefix(v, r), v.user, 0); err != nil {
  134. return err
  135. }
  136. log.Info("%s Marking user %s as deleted", logHTTPPrefix(v, r), v.user.Name)
  137. if err := s.userManager.MarkUserRemoved(v.user); err != nil {
  138. return err
  139. }
  140. return s.writeJSON(w, newSuccessResponse())
  141. }
  142. func (s *Server) handleAccountPasswordChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  143. req, err := readJSONWithLimit[apiAccountPasswordChangeRequest](r.Body, jsonBodyBytesLimit)
  144. if err != nil {
  145. return err
  146. } else if req.Password == "" || req.NewPassword == "" {
  147. return errHTTPBadRequest
  148. }
  149. if _, err := s.userManager.Authenticate(v.user.Name, req.Password); err != nil {
  150. return errHTTPBadRequestIncorrectPasswordConfirmation
  151. }
  152. if err := s.userManager.ChangePassword(v.user.Name, req.NewPassword); err != nil {
  153. return err
  154. }
  155. return s.writeJSON(w, newSuccessResponse())
  156. }
  157. func (s *Server) handleAccountTokenIssue(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  158. // TODO rate limit
  159. token, err := s.userManager.CreateToken(v.user)
  160. if err != nil {
  161. return err
  162. }
  163. response := &apiAccountTokenResponse{
  164. Token: token.Value,
  165. Expires: token.Expires.Unix(),
  166. }
  167. return s.writeJSON(w, response)
  168. }
  169. func (s *Server) handleAccountTokenExtend(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  170. // TODO rate limit
  171. if v.user == nil {
  172. return errHTTPUnauthorized
  173. } else if v.user.Token == "" {
  174. return errHTTPBadRequestNoTokenProvided
  175. }
  176. token, err := s.userManager.ExtendToken(v.user)
  177. if err != nil {
  178. return err
  179. }
  180. response := &apiAccountTokenResponse{
  181. Token: token.Value,
  182. Expires: token.Expires.Unix(),
  183. }
  184. return s.writeJSON(w, response)
  185. }
  186. func (s *Server) handleAccountTokenDelete(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  187. // TODO rate limit
  188. if v.user.Token == "" {
  189. return errHTTPBadRequestNoTokenProvided
  190. }
  191. if err := s.userManager.RemoveToken(v.user); err != nil {
  192. return err
  193. }
  194. return s.writeJSON(w, newSuccessResponse())
  195. }
  196. func (s *Server) handleAccountSettingsChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  197. newPrefs, err := readJSONWithLimit[user.Prefs](r.Body, jsonBodyBytesLimit)
  198. if err != nil {
  199. return err
  200. }
  201. if v.user.Prefs == nil {
  202. v.user.Prefs = &user.Prefs{}
  203. }
  204. prefs := v.user.Prefs
  205. if newPrefs.Language != nil {
  206. prefs.Language = newPrefs.Language
  207. }
  208. if newPrefs.Notification != nil {
  209. if prefs.Notification == nil {
  210. prefs.Notification = &user.NotificationPrefs{}
  211. }
  212. if newPrefs.Notification.DeleteAfter != nil {
  213. prefs.Notification.DeleteAfter = newPrefs.Notification.DeleteAfter
  214. }
  215. if newPrefs.Notification.Sound != nil {
  216. prefs.Notification.Sound = newPrefs.Notification.Sound
  217. }
  218. if newPrefs.Notification.MinPriority != nil {
  219. prefs.Notification.MinPriority = newPrefs.Notification.MinPriority
  220. }
  221. }
  222. if err := s.userManager.ChangeSettings(v.user); err != nil {
  223. return err
  224. }
  225. return s.writeJSON(w, newSuccessResponse())
  226. }
  227. func (s *Server) handleAccountSubscriptionAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  228. newSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit)
  229. if err != nil {
  230. return err
  231. }
  232. if v.user.Prefs == nil {
  233. v.user.Prefs = &user.Prefs{}
  234. }
  235. newSubscription.ID = "" // Client cannot set ID
  236. for _, subscription := range v.user.Prefs.Subscriptions {
  237. if newSubscription.BaseURL == subscription.BaseURL && newSubscription.Topic == subscription.Topic {
  238. newSubscription = subscription
  239. break
  240. }
  241. }
  242. if newSubscription.ID == "" {
  243. newSubscription.ID = util.RandomStringPrefix(subscriptionIDPrefix, subscriptionIDLength)
  244. v.user.Prefs.Subscriptions = append(v.user.Prefs.Subscriptions, newSubscription)
  245. if err := s.userManager.ChangeSettings(v.user); err != nil {
  246. return err
  247. }
  248. }
  249. return s.writeJSON(w, newSubscription)
  250. }
  251. func (s *Server) handleAccountSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  252. matches := apiAccountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  253. if len(matches) != 2 {
  254. return errHTTPInternalErrorInvalidPath
  255. }
  256. subscriptionID := matches[1]
  257. updatedSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit)
  258. if err != nil {
  259. return err
  260. }
  261. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  262. return errHTTPNotFound
  263. }
  264. var subscription *user.Subscription
  265. for _, sub := range v.user.Prefs.Subscriptions {
  266. if sub.ID == subscriptionID {
  267. sub.DisplayName = updatedSubscription.DisplayName
  268. subscription = sub
  269. break
  270. }
  271. }
  272. if subscription == nil {
  273. return errHTTPNotFound
  274. }
  275. if err := s.userManager.ChangeSettings(v.user); err != nil {
  276. return err
  277. }
  278. return s.writeJSON(w, subscription)
  279. }
  280. func (s *Server) handleAccountSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  281. matches := apiAccountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  282. if len(matches) != 2 {
  283. return errHTTPInternalErrorInvalidPath
  284. }
  285. subscriptionID := matches[1]
  286. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  287. return nil
  288. }
  289. newSubscriptions := make([]*user.Subscription, 0)
  290. for _, subscription := range v.user.Prefs.Subscriptions {
  291. if subscription.ID != subscriptionID {
  292. newSubscriptions = append(newSubscriptions, subscription)
  293. }
  294. }
  295. if len(newSubscriptions) < len(v.user.Prefs.Subscriptions) {
  296. v.user.Prefs.Subscriptions = newSubscriptions
  297. if err := s.userManager.ChangeSettings(v.user); err != nil {
  298. return err
  299. }
  300. }
  301. return s.writeJSON(w, newSuccessResponse())
  302. }
  303. func (s *Server) handleAccountReservationAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  304. if v.user != nil && v.user.Role == user.RoleAdmin {
  305. return errHTTPBadRequestMakesNoSenseForAdmin
  306. }
  307. req, err := readJSONWithLimit[apiAccountReservationRequest](r.Body, jsonBodyBytesLimit)
  308. if err != nil {
  309. return err
  310. }
  311. if !topicRegex.MatchString(req.Topic) {
  312. return errHTTPBadRequestTopicInvalid
  313. }
  314. everyone, err := user.ParsePermission(req.Everyone)
  315. if err != nil {
  316. return errHTTPBadRequestPermissionInvalid
  317. }
  318. if v.user.Tier == nil {
  319. return errHTTPUnauthorized
  320. }
  321. // CHeck if we are allowed to reserve this topic
  322. if err := s.userManager.CheckAllowAccess(v.user.Name, req.Topic); err != nil {
  323. return errHTTPConflictTopicReserved
  324. }
  325. hasReservation, err := s.userManager.HasReservation(v.user.Name, req.Topic)
  326. if err != nil {
  327. return err
  328. }
  329. if !hasReservation {
  330. reservations, err := s.userManager.ReservationsCount(v.user.Name)
  331. if err != nil {
  332. return err
  333. } else if reservations >= v.user.Tier.ReservationLimit {
  334. return errHTTPTooManyRequestsLimitReservations
  335. }
  336. }
  337. // Actually add the reservation
  338. if err := s.userManager.AddReservation(v.user.Name, req.Topic, everyone); err != nil {
  339. return err
  340. }
  341. // Kill existing subscribers
  342. t, err := s.topicFromID(req.Topic)
  343. if err != nil {
  344. return err
  345. }
  346. t.CancelSubscribers(v.user.ID)
  347. return s.writeJSON(w, newSuccessResponse())
  348. }
  349. func (s *Server) handleAccountReservationDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  350. matches := apiAccountReservationSingleRegex.FindStringSubmatch(r.URL.Path)
  351. if len(matches) != 2 {
  352. return errHTTPInternalErrorInvalidPath
  353. }
  354. topic := matches[1]
  355. if !topicRegex.MatchString(topic) {
  356. return errHTTPBadRequestTopicInvalid
  357. }
  358. authorized, err := s.userManager.HasReservation(v.user.Name, topic)
  359. if err != nil {
  360. return err
  361. } else if !authorized {
  362. return errHTTPUnauthorized
  363. }
  364. if err := s.userManager.RemoveReservations(v.user.Name, topic); err != nil {
  365. return err
  366. }
  367. return s.writeJSON(w, newSuccessResponse())
  368. }
  369. // maybeRemoveMessagesAndExcessReservations deletes topic reservations for the given user (if too many for tier),
  370. // and marks associated messages for the topics as deleted. This also eventually deletes attachments.
  371. // The process relies on the manager to perform the actual deletions (see runManager).
  372. func (s *Server) maybeRemoveMessagesAndExcessReservations(logPrefix string, u *user.User, reservationsLimit int64) error {
  373. reservations, err := s.userManager.Reservations(u.Name)
  374. if err != nil {
  375. return err
  376. } else if int64(len(reservations)) <= reservationsLimit {
  377. return nil
  378. }
  379. topics := make([]string, 0)
  380. for i := int64(len(reservations)) - 1; i >= reservationsLimit; i-- {
  381. topics = append(topics, reservations[i].Topic)
  382. }
  383. log.Info("%s Removing excess reservations for topics %s", logPrefix, strings.Join(topics, ", "))
  384. if err := s.userManager.RemoveReservations(u.Name, topics...); err != nil {
  385. return err
  386. }
  387. if err := s.messageCache.ExpireMessages(topics...); err != nil {
  388. return err
  389. }
  390. return nil
  391. }
  392. func (s *Server) publishSyncEvent(v *visitor) error {
  393. if v.user == nil || v.user.SyncTopic == "" {
  394. return nil
  395. }
  396. log.Trace("Publishing sync event to user %s's sync topic %s", v.user.Name, v.user.SyncTopic)
  397. syncTopic, err := s.topicFromID(v.user.SyncTopic)
  398. if err != nil {
  399. return err
  400. }
  401. messageBytes, err := json.Marshal(&apiAccountSyncTopicResponse{Event: syncTopicAccountSyncEvent})
  402. if err != nil {
  403. return err
  404. }
  405. m := newDefaultMessage(syncTopic.ID, string(messageBytes))
  406. if err := syncTopic.Publish(v, m); err != nil {
  407. return err
  408. }
  409. return nil
  410. }
  411. func (s *Server) publishSyncEventAsync(v *visitor) {
  412. go func() {
  413. if v.user == nil || v.user.SyncTopic == "" {
  414. return
  415. }
  416. if err := s.publishSyncEvent(v); err != nil {
  417. log.Trace("Error publishing to user %s's sync topic %s: %s", v.user.Name, v.user.SyncTopic, err.Error())
  418. }
  419. }()
  420. }