server_account.go 14 KB

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