server_account.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. package server
  2. import (
  3. "encoding/json"
  4. "heckel.io/ntfy/user"
  5. "heckel.io/ntfy/util"
  6. "net/http"
  7. )
  8. const (
  9. jsonBodyBytesLimit = 4096
  10. subscriptionIDLength = 16
  11. createdByAPI = "api"
  12. )
  13. func (s *Server) handleAccountCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  14. admin := v.user != nil && v.user.Role == user.RoleAdmin
  15. if !admin {
  16. if !s.config.EnableSignup {
  17. return errHTTPBadRequestSignupNotEnabled
  18. } else if v.user != nil {
  19. return errHTTPUnauthorized // Cannot create account from user context
  20. }
  21. }
  22. newAccount, err := readJSONWithLimit[apiAccountCreateRequest](r.Body, jsonBodyBytesLimit)
  23. if err != nil {
  24. return err
  25. }
  26. if existingUser, _ := s.userManager.User(newAccount.Username); existingUser != nil {
  27. return errHTTPConflictUserExists
  28. }
  29. if v.accountLimiter != nil && !v.accountLimiter.Allow() {
  30. return errHTTPTooManyRequestsLimitAccountCreation
  31. }
  32. if err := s.userManager.AddUser(newAccount.Username, newAccount.Password, user.RoleUser, createdByAPI); err != nil { // TODO this should return a User
  33. return err
  34. }
  35. w.Header().Set("Content-Type", "application/json")
  36. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  37. return nil
  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. Paid: v.user.Tier.Paid,
  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. w.Header().Set("Content-Type", "application/json")
  116. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  117. if err := json.NewEncoder(w).Encode(response); err != nil {
  118. return err
  119. }
  120. return nil
  121. }
  122. func (s *Server) handleAccountDelete(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  123. if err := s.userManager.RemoveUser(v.user.Name); err != nil {
  124. return err
  125. }
  126. w.Header().Set("Content-Type", "application/json")
  127. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  128. return nil
  129. }
  130. func (s *Server) handleAccountPasswordChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  131. newPassword, err := readJSONWithLimit[apiAccountPasswordChangeRequest](r.Body, jsonBodyBytesLimit)
  132. if err != nil {
  133. return err
  134. }
  135. if err := s.userManager.ChangePassword(v.user.Name, newPassword.Password); err != nil {
  136. return err
  137. }
  138. w.Header().Set("Content-Type", "application/json")
  139. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  140. return nil
  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. w.Header().Set("Content-Type", "application/json")
  149. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  150. response := &apiAccountTokenResponse{
  151. Token: token.Value,
  152. Expires: token.Expires.Unix(),
  153. }
  154. if err := json.NewEncoder(w).Encode(response); err != nil {
  155. return err
  156. }
  157. return nil
  158. }
  159. func (s *Server) handleAccountTokenExtend(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  160. // TODO rate limit
  161. if v.user == nil {
  162. return errHTTPUnauthorized
  163. } else if v.user.Token == "" {
  164. return errHTTPBadRequestNoTokenProvided
  165. }
  166. token, err := s.userManager.ExtendToken(v.user)
  167. if err != nil {
  168. return err
  169. }
  170. w.Header().Set("Content-Type", "application/json")
  171. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  172. response := &apiAccountTokenResponse{
  173. Token: token.Value,
  174. Expires: token.Expires.Unix(),
  175. }
  176. if err := json.NewEncoder(w).Encode(response); err != nil {
  177. return err
  178. }
  179. return nil
  180. }
  181. func (s *Server) handleAccountTokenDelete(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  182. // TODO rate limit
  183. if v.user.Token == "" {
  184. return errHTTPBadRequestNoTokenProvided
  185. }
  186. if err := s.userManager.RemoveToken(v.user); err != nil {
  187. return err
  188. }
  189. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  190. return nil
  191. }
  192. func (s *Server) handleAccountSettingsChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  193. newPrefs, err := readJSONWithLimit[user.Prefs](r.Body, jsonBodyBytesLimit)
  194. if err != nil {
  195. return err
  196. }
  197. if v.user.Prefs == nil {
  198. v.user.Prefs = &user.Prefs{}
  199. }
  200. prefs := v.user.Prefs
  201. if newPrefs.Language != "" {
  202. prefs.Language = newPrefs.Language
  203. }
  204. if newPrefs.Notification != nil {
  205. if prefs.Notification == nil {
  206. prefs.Notification = &user.NotificationPrefs{}
  207. }
  208. if newPrefs.Notification.DeleteAfter > 0 {
  209. prefs.Notification.DeleteAfter = newPrefs.Notification.DeleteAfter
  210. }
  211. if newPrefs.Notification.Sound != "" {
  212. prefs.Notification.Sound = newPrefs.Notification.Sound
  213. }
  214. if newPrefs.Notification.MinPriority > 0 {
  215. prefs.Notification.MinPriority = newPrefs.Notification.MinPriority
  216. }
  217. }
  218. if err := s.userManager.ChangeSettings(v.user); err != nil {
  219. return err
  220. }
  221. w.Header().Set("Content-Type", "application/json")
  222. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  223. return nil
  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. w.Header().Set("Content-Type", "application/json")
  248. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  249. if err := json.NewEncoder(w).Encode(newSubscription); err != nil {
  250. return err
  251. }
  252. return nil
  253. }
  254. func (s *Server) handleAccountSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  255. matches := accountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  256. if len(matches) != 2 {
  257. return errHTTPInternalErrorInvalidPath
  258. }
  259. subscriptionID := matches[1]
  260. updatedSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit)
  261. if err != nil {
  262. return err
  263. }
  264. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  265. return errHTTPNotFound
  266. }
  267. var subscription *user.Subscription
  268. for _, sub := range v.user.Prefs.Subscriptions {
  269. if sub.ID == subscriptionID {
  270. sub.DisplayName = updatedSubscription.DisplayName
  271. subscription = sub
  272. break
  273. }
  274. }
  275. if subscription == nil {
  276. return errHTTPNotFound
  277. }
  278. if err := s.userManager.ChangeSettings(v.user); err != nil {
  279. return err
  280. }
  281. w.Header().Set("Content-Type", "application/json")
  282. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  283. if err := json.NewEncoder(w).Encode(subscription); err != nil {
  284. return err
  285. }
  286. return nil
  287. }
  288. func (s *Server) handleAccountSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  289. matches := accountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  290. if len(matches) != 2 {
  291. return errHTTPInternalErrorInvalidPath
  292. }
  293. subscriptionID := matches[1]
  294. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  295. return nil
  296. }
  297. newSubscriptions := make([]*user.Subscription, 0)
  298. for _, subscription := range v.user.Prefs.Subscriptions {
  299. if subscription.ID != subscriptionID {
  300. newSubscriptions = append(newSubscriptions, subscription)
  301. }
  302. }
  303. if len(newSubscriptions) < len(v.user.Prefs.Subscriptions) {
  304. v.user.Prefs.Subscriptions = newSubscriptions
  305. if err := s.userManager.ChangeSettings(v.user); err != nil {
  306. return err
  307. }
  308. }
  309. w.Header().Set("Content-Type", "application/json")
  310. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  311. return nil
  312. }
  313. func (s *Server) handleAccountReservationAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  314. if v.user != nil && v.user.Role == user.RoleAdmin {
  315. return errHTTPBadRequestMakesNoSenseForAdmin
  316. }
  317. req, err := readJSONWithLimit[apiAccountReservationRequest](r.Body, jsonBodyBytesLimit)
  318. if err != nil {
  319. return err
  320. }
  321. if !topicRegex.MatchString(req.Topic) {
  322. return errHTTPBadRequestTopicInvalid
  323. }
  324. everyone, err := user.ParsePermission(req.Everyone)
  325. if err != nil {
  326. return errHTTPBadRequestPermissionInvalid
  327. }
  328. if v.user.Tier == nil {
  329. return errHTTPUnauthorized
  330. }
  331. if err := s.userManager.CheckAllowAccess(v.user.Name, req.Topic); err != nil {
  332. return errHTTPConflictTopicReserved
  333. }
  334. hasReservation, err := s.userManager.HasReservation(v.user.Name, req.Topic)
  335. if err != nil {
  336. return err
  337. }
  338. if !hasReservation {
  339. reservations, err := s.userManager.ReservationsCount(v.user.Name)
  340. if err != nil {
  341. return err
  342. } else if reservations >= v.user.Tier.ReservationsLimit {
  343. return errHTTPTooManyRequestsLimitReservations
  344. }
  345. }
  346. owner, username := v.user.Name, v.user.Name
  347. if err := s.userManager.AllowAccess(owner, username, req.Topic, true, true); err != nil {
  348. return err
  349. }
  350. if err := s.userManager.AllowAccess(owner, user.Everyone, req.Topic, everyone.IsRead(), everyone.IsWrite()); err != nil {
  351. return err
  352. }
  353. w.Header().Set("Content-Type", "application/json")
  354. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  355. return nil
  356. }
  357. func (s *Server) handleAccountReservationDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  358. matches := accountReservationSingleRegex.FindStringSubmatch(r.URL.Path)
  359. if len(matches) != 2 {
  360. return errHTTPInternalErrorInvalidPath
  361. }
  362. topic := matches[1]
  363. if !topicRegex.MatchString(topic) {
  364. return errHTTPBadRequestTopicInvalid
  365. }
  366. authorized, err := s.userManager.HasReservation(v.user.Name, topic)
  367. if err != nil {
  368. return err
  369. } else if !authorized {
  370. return errHTTPUnauthorized
  371. }
  372. if err := s.userManager.ResetAccess(v.user.Name, topic); err != nil {
  373. return err
  374. }
  375. if err := s.userManager.ResetAccess(user.Everyone, topic); err != nil {
  376. return err
  377. }
  378. w.Header().Set("Content-Type", "application/json")
  379. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  380. return nil
  381. }