server_account.go 12 KB

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