server_account.go 12 KB

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