server_account.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. package server
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "heckel.io/ntfy/log"
  6. "heckel.io/ntfy/user"
  7. "heckel.io/ntfy/util"
  8. "net/http"
  9. )
  10. const (
  11. subscriptionIDLength = 16
  12. createdByAPI = "api"
  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. }
  24. newAccount, err := readJSONWithLimit[apiAccountCreateRequest](r.Body, jsonBodyBytesLimit)
  25. if err != nil {
  26. return err
  27. }
  28. if existingUser, _ := s.userManager.User(newAccount.Username); existingUser != nil {
  29. return errHTTPConflictUserExists
  30. }
  31. if v.accountLimiter != nil && !v.accountLimiter.Allow() {
  32. return errHTTPTooManyRequestsLimitAccountCreation
  33. }
  34. if err := s.userManager.AddUser(newAccount.Username, newAccount.Password, user.RoleUser, createdByAPI); 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.MessagesLimit,
  49. MessagesExpiryDuration: int64(limits.MessagesExpiryDuration.Seconds()),
  50. Emails: limits.EmailsLimit,
  51. Reservations: limits.ReservationsLimit,
  52. AttachmentTotalSize: limits.AttachmentTotalSizeLimit,
  53. AttachmentFileSize: limits.AttachmentFileSizeLimit,
  54. AttachmentExpiryDuration: int64(limits.AttachmentExpiryDuration.Seconds()),
  55. },
  56. Stats: &apiAccountStats{
  57. Messages: stats.Messages,
  58. MessagesRemaining: stats.MessagesRemaining,
  59. Emails: stats.Emails,
  60. EmailsRemaining: stats.EmailsRemaining,
  61. Reservations: stats.Reservations,
  62. ReservationsRemaining: stats.ReservationsRemaining,
  63. AttachmentTotalSize: stats.AttachmentTotalSize,
  64. AttachmentTotalSizeRemaining: stats.AttachmentTotalSizeRemaining,
  65. },
  66. }
  67. if v.user != nil {
  68. response.Username = v.user.Name
  69. response.Role = string(v.user.Role)
  70. response.SyncTopic = v.user.SyncTopic
  71. if v.user.Prefs != nil {
  72. if v.user.Prefs.Language != "" {
  73. response.Language = v.user.Prefs.Language
  74. }
  75. if v.user.Prefs.Notification != nil {
  76. response.Notification = v.user.Prefs.Notification
  77. }
  78. if v.user.Prefs.Subscriptions != nil {
  79. response.Subscriptions = v.user.Prefs.Subscriptions
  80. }
  81. }
  82. if v.user.Tier != nil {
  83. response.Tier = &apiAccountTier{
  84. Code: v.user.Tier.Code,
  85. Name: v.user.Tier.Name,
  86. }
  87. }
  88. if v.user.Billing.StripeCustomerID != "" {
  89. response.Billing = &apiAccountBilling{
  90. Customer: true,
  91. Subscription: v.user.Billing.StripeSubscriptionID != "",
  92. Status: string(v.user.Billing.StripeSubscriptionStatus),
  93. PaidUntil: v.user.Billing.StripeSubscriptionPaidUntil.Unix(),
  94. CancelAt: v.user.Billing.StripeSubscriptionCancelAt.Unix(),
  95. }
  96. }
  97. reservations, err := s.userManager.Reservations(v.user.Name)
  98. if err != nil {
  99. return err
  100. }
  101. if len(reservations) > 0 {
  102. response.Reservations = make([]*apiAccountReservation, 0)
  103. for _, r := range reservations {
  104. response.Reservations = append(response.Reservations, &apiAccountReservation{
  105. Topic: r.Topic,
  106. Everyone: r.Everyone.String(),
  107. })
  108. }
  109. }
  110. } else {
  111. response.Username = user.Everyone
  112. response.Role = string(user.RoleAnonymous)
  113. }
  114. return s.writeJSON(w, response)
  115. }
  116. func (s *Server) handleAccountDelete(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  117. if v.user.Billing.StripeSubscriptionID != "" {
  118. log.Info("Deleting user %s (billing customer: %s, billing subscription: %s)", v.user.Name, v.user.Billing.StripeCustomerID, v.user.Billing.StripeSubscriptionID)
  119. if v.user.Billing.StripeSubscriptionID != "" {
  120. if _, err := s.stripe.CancelSubscription(v.user.Billing.StripeSubscriptionID); err != nil {
  121. return err
  122. }
  123. }
  124. } else {
  125. log.Info("Deleting user %s", v.user.Name)
  126. }
  127. if err := s.userManager.RemoveUser(v.user.Name); err != nil {
  128. return err
  129. }
  130. return s.writeJSON(w, newSuccessResponse())
  131. }
  132. func (s *Server) handleAccountPasswordChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  133. newPassword, err := readJSONWithLimit[apiAccountPasswordChangeRequest](r.Body, jsonBodyBytesLimit)
  134. if err != nil {
  135. return err
  136. }
  137. if err := s.userManager.ChangePassword(v.user.Name, newPassword.Password); err != nil {
  138. return err
  139. }
  140. return s.writeJSON(w, newSuccessResponse())
  141. }
  142. func (s *Server) handleAccountTokenIssue(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  143. // TODO rate limit
  144. token, err := s.userManager.CreateToken(v.user)
  145. if err != nil {
  146. return err
  147. }
  148. response := &apiAccountTokenResponse{
  149. Token: token.Value,
  150. Expires: token.Expires.Unix(),
  151. }
  152. return s.writeJSON(w, response)
  153. }
  154. func (s *Server) handleAccountTokenExtend(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  155. // TODO rate limit
  156. if v.user == nil {
  157. return errHTTPUnauthorized
  158. } else if v.user.Token == "" {
  159. return errHTTPBadRequestNoTokenProvided
  160. }
  161. token, err := s.userManager.ExtendToken(v.user)
  162. if err != nil {
  163. return err
  164. }
  165. response := &apiAccountTokenResponse{
  166. Token: token.Value,
  167. Expires: token.Expires.Unix(),
  168. }
  169. return s.writeJSON(w, response)
  170. }
  171. func (s *Server) handleAccountTokenDelete(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  172. // TODO rate limit
  173. if v.user.Token == "" {
  174. return errHTTPBadRequestNoTokenProvided
  175. }
  176. if err := s.userManager.RemoveToken(v.user); err != nil {
  177. return err
  178. }
  179. return s.writeJSON(w, newSuccessResponse())
  180. }
  181. func (s *Server) handleAccountSettingsChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  182. newPrefs, err := readJSONWithLimit[user.Prefs](r.Body, jsonBodyBytesLimit)
  183. if err != nil {
  184. return err
  185. }
  186. if v.user.Prefs == nil {
  187. v.user.Prefs = &user.Prefs{}
  188. }
  189. prefs := v.user.Prefs
  190. if newPrefs.Language != "" {
  191. prefs.Language = newPrefs.Language
  192. }
  193. if newPrefs.Notification != nil {
  194. if prefs.Notification == nil {
  195. prefs.Notification = &user.NotificationPrefs{}
  196. }
  197. if newPrefs.Notification.DeleteAfter > 0 {
  198. prefs.Notification.DeleteAfter = newPrefs.Notification.DeleteAfter
  199. }
  200. if newPrefs.Notification.Sound != "" {
  201. prefs.Notification.Sound = newPrefs.Notification.Sound
  202. }
  203. if newPrefs.Notification.MinPriority > 0 {
  204. prefs.Notification.MinPriority = newPrefs.Notification.MinPriority
  205. }
  206. }
  207. if err := s.userManager.ChangeSettings(v.user); err != nil {
  208. return err
  209. }
  210. return s.writeJSON(w, newSuccessResponse())
  211. }
  212. func (s *Server) handleAccountSubscriptionAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  213. newSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit)
  214. if err != nil {
  215. return err
  216. }
  217. if v.user.Prefs == nil {
  218. v.user.Prefs = &user.Prefs{}
  219. }
  220. newSubscription.ID = "" // Client cannot set ID
  221. for _, subscription := range v.user.Prefs.Subscriptions {
  222. if newSubscription.BaseURL == subscription.BaseURL && newSubscription.Topic == subscription.Topic {
  223. newSubscription = subscription
  224. break
  225. }
  226. }
  227. if newSubscription.ID == "" {
  228. newSubscription.ID = util.RandomString(subscriptionIDLength)
  229. v.user.Prefs.Subscriptions = append(v.user.Prefs.Subscriptions, newSubscription)
  230. if err := s.userManager.ChangeSettings(v.user); err != nil {
  231. return err
  232. }
  233. }
  234. return s.writeJSON(w, newSubscription)
  235. }
  236. func (s *Server) handleAccountSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  237. matches := apiAccountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  238. if len(matches) != 2 {
  239. return errHTTPInternalErrorInvalidPath
  240. }
  241. subscriptionID := matches[1]
  242. updatedSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit)
  243. if err != nil {
  244. return err
  245. }
  246. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  247. return errHTTPNotFound
  248. }
  249. var subscription *user.Subscription
  250. for _, sub := range v.user.Prefs.Subscriptions {
  251. if sub.ID == subscriptionID {
  252. sub.DisplayName = updatedSubscription.DisplayName
  253. subscription = sub
  254. break
  255. }
  256. }
  257. if subscription == nil {
  258. return errHTTPNotFound
  259. }
  260. if err := s.userManager.ChangeSettings(v.user); err != nil {
  261. return err
  262. }
  263. return s.writeJSON(w, subscription)
  264. }
  265. func (s *Server) handleAccountSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  266. matches := apiAccountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  267. if len(matches) != 2 {
  268. return errHTTPInternalErrorInvalidPath
  269. }
  270. subscriptionID := matches[1]
  271. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  272. return nil
  273. }
  274. newSubscriptions := make([]*user.Subscription, 0)
  275. for _, subscription := range v.user.Prefs.Subscriptions {
  276. if subscription.ID != subscriptionID {
  277. newSubscriptions = append(newSubscriptions, subscription)
  278. }
  279. }
  280. if len(newSubscriptions) < len(v.user.Prefs.Subscriptions) {
  281. v.user.Prefs.Subscriptions = newSubscriptions
  282. if err := s.userManager.ChangeSettings(v.user); err != nil {
  283. return err
  284. }
  285. }
  286. return s.writeJSON(w, newSuccessResponse())
  287. }
  288. func (s *Server) handleAccountReservationAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  289. if v.user != nil && v.user.Role == user.RoleAdmin {
  290. return errHTTPBadRequestMakesNoSenseForAdmin
  291. }
  292. req, err := readJSONWithLimit[apiAccountReservationRequest](r.Body, jsonBodyBytesLimit)
  293. if err != nil {
  294. return err
  295. }
  296. if !topicRegex.MatchString(req.Topic) {
  297. return errHTTPBadRequestTopicInvalid
  298. }
  299. everyone, err := user.ParsePermission(req.Everyone)
  300. if err != nil {
  301. return errHTTPBadRequestPermissionInvalid
  302. }
  303. if v.user.Tier == nil {
  304. return errHTTPUnauthorized
  305. }
  306. if err := s.userManager.CheckAllowAccess(v.user.Name, req.Topic); err != nil {
  307. return errHTTPConflictTopicReserved
  308. }
  309. hasReservation, err := s.userManager.HasReservation(v.user.Name, req.Topic)
  310. if err != nil {
  311. return err
  312. }
  313. if !hasReservation {
  314. reservations, err := s.userManager.ReservationsCount(v.user.Name)
  315. if err != nil {
  316. return err
  317. } else if reservations >= v.user.Tier.ReservationsLimit {
  318. return errHTTPTooManyRequestsLimitReservations
  319. }
  320. }
  321. if err := s.userManager.ReserveAccess(v.user.Name, req.Topic, everyone); err != nil {
  322. return err
  323. }
  324. return s.writeJSON(w, newSuccessResponse())
  325. }
  326. func (s *Server) handleAccountReservationDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  327. matches := apiAccountReservationSingleRegex.FindStringSubmatch(r.URL.Path)
  328. if len(matches) != 2 {
  329. return errHTTPInternalErrorInvalidPath
  330. }
  331. topic := matches[1]
  332. if !topicRegex.MatchString(topic) {
  333. return errHTTPBadRequestTopicInvalid
  334. }
  335. authorized, err := s.userManager.HasReservation(v.user.Name, topic)
  336. if err != nil {
  337. return err
  338. } else if !authorized {
  339. return errHTTPUnauthorized
  340. }
  341. if err := s.userManager.RemoveReservations(v.user.Name, topic); err != nil {
  342. return err
  343. }
  344. return s.writeJSON(w, newSuccessResponse())
  345. }
  346. func (s *Server) publishSyncEvent(v *visitor) error {
  347. if v.user == nil || v.user.SyncTopic == "" {
  348. return nil
  349. }
  350. log.Trace("Publishing sync event to user %s's sync topic %s", v.user.Name, v.user.SyncTopic)
  351. topics, err := s.topicsFromIDs(v.user.SyncTopic)
  352. if err != nil {
  353. return err
  354. } else if len(topics) == 0 {
  355. return errors.New("cannot retrieve sync topic")
  356. }
  357. syncTopic := topics[0]
  358. messageBytes, err := json.Marshal(&apiAccountSyncTopicResponse{Event: syncTopicAccountSyncEvent})
  359. if err != nil {
  360. return err
  361. }
  362. m := newDefaultMessage(syncTopic.ID, string(messageBytes))
  363. if err := syncTopic.Publish(v, m); err != nil {
  364. return err
  365. }
  366. return nil
  367. }
  368. func (s *Server) publishSyncEventAsync(v *visitor) {
  369. go func() {
  370. if v.user == nil || v.user.SyncTopic == "" {
  371. return
  372. }
  373. if err := s.publishSyncEvent(v); err != nil {
  374. log.Trace("Error publishing to user %s's sync topic %s: %s", v.user.Name, v.user.SyncTopic, err.Error())
  375. }
  376. }()
  377. }