server_account.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. 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. if v.user.Billing.StripeSubscriptionID != "" {
  117. log.Info("%s Canceling billing subscription %s", logHTTPPrefix(v, r), v.user.Billing.StripeSubscriptionID)
  118. if v.user.Billing.StripeSubscriptionID != "" {
  119. if _, err := s.stripe.CancelSubscription(v.user.Billing.StripeSubscriptionID); err != nil {
  120. return err
  121. }
  122. }
  123. if err := s.maybeRemoveExcessReservations(logHTTPPrefix(v, r), v.user, 0); err != nil {
  124. return err
  125. }
  126. }
  127. log.Info("%s Marking user %s as deleted", logHTTPPrefix(v, r), v.user.Name)
  128. if err := s.userManager.MarkUserRemoved(v.user); err != nil {
  129. return err
  130. }
  131. return s.writeJSON(w, newSuccessResponse())
  132. }
  133. func (s *Server) handleAccountPasswordChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  134. req, err := readJSONWithLimit[apiAccountPasswordChangeRequest](r.Body, jsonBodyBytesLimit)
  135. if err != nil {
  136. return err
  137. } else if req.Password == "" || req.NewPassword == "" {
  138. return errHTTPBadRequest
  139. }
  140. if _, err := s.userManager.Authenticate(v.user.Name, req.Password); err != nil {
  141. return errHTTPBadRequestCurrentPasswordWrong
  142. }
  143. if err := s.userManager.ChangePassword(v.user.Name, req.NewPassword); err != nil {
  144. return err
  145. }
  146. return s.writeJSON(w, newSuccessResponse())
  147. }
  148. func (s *Server) handleAccountTokenIssue(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  149. // TODO rate limit
  150. token, err := s.userManager.CreateToken(v.user)
  151. if err != nil {
  152. return err
  153. }
  154. response := &apiAccountTokenResponse{
  155. Token: token.Value,
  156. Expires: token.Expires.Unix(),
  157. }
  158. return s.writeJSON(w, response)
  159. }
  160. func (s *Server) handleAccountTokenExtend(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  161. // TODO rate limit
  162. if v.user == nil {
  163. return errHTTPUnauthorized
  164. } else if v.user.Token == "" {
  165. return errHTTPBadRequestNoTokenProvided
  166. }
  167. token, err := s.userManager.ExtendToken(v.user)
  168. if err != nil {
  169. return err
  170. }
  171. response := &apiAccountTokenResponse{
  172. Token: token.Value,
  173. Expires: token.Expires.Unix(),
  174. }
  175. return s.writeJSON(w, response)
  176. }
  177. func (s *Server) handleAccountTokenDelete(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  178. // TODO rate limit
  179. if v.user.Token == "" {
  180. return errHTTPBadRequestNoTokenProvided
  181. }
  182. if err := s.userManager.RemoveToken(v.user); err != nil {
  183. return err
  184. }
  185. return s.writeJSON(w, newSuccessResponse())
  186. }
  187. func (s *Server) handleAccountSettingsChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  188. newPrefs, err := readJSONWithLimit[user.Prefs](r.Body, jsonBodyBytesLimit)
  189. if err != nil {
  190. return err
  191. }
  192. if v.user.Prefs == nil {
  193. v.user.Prefs = &user.Prefs{}
  194. }
  195. prefs := v.user.Prefs
  196. if newPrefs.Language != "" {
  197. prefs.Language = newPrefs.Language
  198. }
  199. if newPrefs.Notification != nil {
  200. if prefs.Notification == nil {
  201. prefs.Notification = &user.NotificationPrefs{}
  202. }
  203. if newPrefs.Notification.DeleteAfter > 0 {
  204. prefs.Notification.DeleteAfter = newPrefs.Notification.DeleteAfter
  205. }
  206. if newPrefs.Notification.Sound != "" {
  207. prefs.Notification.Sound = newPrefs.Notification.Sound
  208. }
  209. if newPrefs.Notification.MinPriority > 0 {
  210. prefs.Notification.MinPriority = newPrefs.Notification.MinPriority
  211. }
  212. }
  213. if err := s.userManager.ChangeSettings(v.user); err != nil {
  214. return err
  215. }
  216. return s.writeJSON(w, newSuccessResponse())
  217. }
  218. func (s *Server) handleAccountSubscriptionAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  219. newSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit)
  220. if err != nil {
  221. return err
  222. }
  223. if v.user.Prefs == nil {
  224. v.user.Prefs = &user.Prefs{}
  225. }
  226. newSubscription.ID = "" // Client cannot set ID
  227. for _, subscription := range v.user.Prefs.Subscriptions {
  228. if newSubscription.BaseURL == subscription.BaseURL && newSubscription.Topic == subscription.Topic {
  229. newSubscription = subscription
  230. break
  231. }
  232. }
  233. if newSubscription.ID == "" {
  234. newSubscription.ID = util.RandomString(subscriptionIDLength)
  235. v.user.Prefs.Subscriptions = append(v.user.Prefs.Subscriptions, newSubscription)
  236. if err := s.userManager.ChangeSettings(v.user); err != nil {
  237. return err
  238. }
  239. }
  240. return s.writeJSON(w, newSubscription)
  241. }
  242. func (s *Server) handleAccountSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  243. matches := apiAccountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  244. if len(matches) != 2 {
  245. return errHTTPInternalErrorInvalidPath
  246. }
  247. subscriptionID := matches[1]
  248. updatedSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit)
  249. if err != nil {
  250. return err
  251. }
  252. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  253. return errHTTPNotFound
  254. }
  255. var subscription *user.Subscription
  256. for _, sub := range v.user.Prefs.Subscriptions {
  257. if sub.ID == subscriptionID {
  258. sub.DisplayName = updatedSubscription.DisplayName
  259. subscription = sub
  260. break
  261. }
  262. }
  263. if subscription == nil {
  264. return errHTTPNotFound
  265. }
  266. if err := s.userManager.ChangeSettings(v.user); err != nil {
  267. return err
  268. }
  269. return s.writeJSON(w, subscription)
  270. }
  271. func (s *Server) handleAccountSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  272. matches := apiAccountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  273. if len(matches) != 2 {
  274. return errHTTPInternalErrorInvalidPath
  275. }
  276. subscriptionID := matches[1]
  277. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  278. return nil
  279. }
  280. newSubscriptions := make([]*user.Subscription, 0)
  281. for _, subscription := range v.user.Prefs.Subscriptions {
  282. if subscription.ID != subscriptionID {
  283. newSubscriptions = append(newSubscriptions, subscription)
  284. }
  285. }
  286. if len(newSubscriptions) < len(v.user.Prefs.Subscriptions) {
  287. v.user.Prefs.Subscriptions = newSubscriptions
  288. if err := s.userManager.ChangeSettings(v.user); err != nil {
  289. return err
  290. }
  291. }
  292. return s.writeJSON(w, newSuccessResponse())
  293. }
  294. func (s *Server) handleAccountReservationAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  295. if v.user != nil && v.user.Role == user.RoleAdmin {
  296. return errHTTPBadRequestMakesNoSenseForAdmin
  297. }
  298. req, err := readJSONWithLimit[apiAccountReservationRequest](r.Body, jsonBodyBytesLimit)
  299. if err != nil {
  300. return err
  301. }
  302. if !topicRegex.MatchString(req.Topic) {
  303. return errHTTPBadRequestTopicInvalid
  304. }
  305. everyone, err := user.ParsePermission(req.Everyone)
  306. if err != nil {
  307. return errHTTPBadRequestPermissionInvalid
  308. }
  309. if v.user.Tier == nil {
  310. return errHTTPUnauthorized
  311. }
  312. if err := s.userManager.CheckAllowAccess(v.user.Name, req.Topic); err != nil {
  313. return errHTTPConflictTopicReserved
  314. }
  315. hasReservation, err := s.userManager.HasReservation(v.user.Name, req.Topic)
  316. if err != nil {
  317. return err
  318. }
  319. if !hasReservation {
  320. reservations, err := s.userManager.ReservationsCount(v.user.Name)
  321. if err != nil {
  322. return err
  323. } else if reservations >= v.user.Tier.ReservationsLimit {
  324. return errHTTPTooManyRequestsLimitReservations
  325. }
  326. }
  327. if err := s.userManager.AddReservation(v.user.Name, req.Topic, everyone); err != nil {
  328. return err
  329. }
  330. return s.writeJSON(w, newSuccessResponse())
  331. }
  332. func (s *Server) handleAccountReservationDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  333. matches := apiAccountReservationSingleRegex.FindStringSubmatch(r.URL.Path)
  334. if len(matches) != 2 {
  335. return errHTTPInternalErrorInvalidPath
  336. }
  337. topic := matches[1]
  338. if !topicRegex.MatchString(topic) {
  339. return errHTTPBadRequestTopicInvalid
  340. }
  341. authorized, err := s.userManager.HasReservation(v.user.Name, topic)
  342. if err != nil {
  343. return err
  344. } else if !authorized {
  345. return errHTTPUnauthorized
  346. }
  347. if err := s.userManager.RemoveReservations(v.user.Name, topic); err != nil {
  348. return err
  349. }
  350. return s.writeJSON(w, newSuccessResponse())
  351. }
  352. func (s *Server) publishSyncEvent(v *visitor) error {
  353. if v.user == nil || v.user.SyncTopic == "" {
  354. return nil
  355. }
  356. log.Trace("Publishing sync event to user %s's sync topic %s", v.user.Name, v.user.SyncTopic)
  357. topics, err := s.topicsFromIDs(v.user.SyncTopic)
  358. if err != nil {
  359. return err
  360. } else if len(topics) == 0 {
  361. return errors.New("cannot retrieve sync topic")
  362. }
  363. syncTopic := topics[0]
  364. messageBytes, err := json.Marshal(&apiAccountSyncTopicResponse{Event: syncTopicAccountSyncEvent})
  365. if err != nil {
  366. return err
  367. }
  368. m := newDefaultMessage(syncTopic.ID, string(messageBytes))
  369. if err := syncTopic.Publish(v, m); err != nil {
  370. return err
  371. }
  372. return nil
  373. }
  374. func (s *Server) publishSyncEventAsync(v *visitor) {
  375. go func() {
  376. if v.user == nil || v.user.SyncTopic == "" {
  377. return
  378. }
  379. if err := s.publishSyncEvent(v); err != nil {
  380. log.Trace("Error publishing to user %s's sync topic %s: %s", v.user.Name, v.user.SyncTopic, err.Error())
  381. }
  382. }()
  383. }