server_account.go 12 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. )
  12. func (s *Server) handleAccountCreate(w http.ResponseWriter, r *http.Request, v *visitor) error {
  13. admin := v.user != nil && v.user.Role == user.RoleAdmin
  14. if !admin {
  15. if !s.config.EnableSignup {
  16. return errHTTPBadRequestSignupNotEnabled
  17. } else if v.user != nil {
  18. return errHTTPUnauthorized // Cannot create account from user context
  19. }
  20. }
  21. newAccount, err := readJSONWithLimit[apiAccountCreateRequest](r.Body, jsonBodyBytesLimit)
  22. if err != nil {
  23. return err
  24. }
  25. if existingUser, _ := s.userManager.User(newAccount.Username); existingUser != nil {
  26. return errHTTPConflictUserExists
  27. }
  28. if v.accountLimiter != nil && !v.accountLimiter.Allow() {
  29. return errHTTPTooManyRequestsLimitAccountCreation
  30. }
  31. if err := s.userManager.AddUser(newAccount.Username, newAccount.Password, user.RoleUser); err != nil { // TODO this should return a User
  32. return err
  33. }
  34. w.Header().Set("Content-Type", "application/json")
  35. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  36. return nil
  37. }
  38. func (s *Server) handleAccountGet(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  39. stats, err := v.Info()
  40. if err != nil {
  41. return err
  42. }
  43. response := &apiAccountResponse{
  44. Stats: &apiAccountStats{
  45. Messages: stats.Messages,
  46. MessagesRemaining: stats.MessagesRemaining,
  47. Emails: stats.Emails,
  48. EmailsRemaining: stats.EmailsRemaining,
  49. Reservations: stats.Reservations,
  50. ReservationsRemaining: stats.ReservationsRemaining,
  51. AttachmentTotalSize: stats.AttachmentTotalSize,
  52. AttachmentTotalSizeRemaining: stats.AttachmentTotalSizeRemaining,
  53. },
  54. Limits: &apiAccountLimits{
  55. Basis: stats.Basis,
  56. Messages: stats.MessagesLimit,
  57. MessagesExpiryDuration: stats.MessagesExpiryDuration,
  58. Emails: stats.EmailsLimit,
  59. Reservations: stats.ReservationsLimit,
  60. AttachmentTotalSize: stats.AttachmentTotalSizeLimit,
  61. AttachmentFileSize: stats.AttachmentFileSizeLimit,
  62. AttachmentExpiryDuration: stats.AttachmentExpiryDuration,
  63. },
  64. }
  65. if v.user != nil {
  66. response.Username = v.user.Name
  67. response.Role = string(v.user.Role)
  68. if v.user.Prefs != nil {
  69. if v.user.Prefs.Language != "" {
  70. response.Language = v.user.Prefs.Language
  71. }
  72. if v.user.Prefs.Notification != nil {
  73. response.Notification = v.user.Prefs.Notification
  74. }
  75. if v.user.Prefs.Subscriptions != nil {
  76. response.Subscriptions = v.user.Prefs.Subscriptions
  77. }
  78. }
  79. if v.user.Tier != nil {
  80. response.Tier = &apiAccountTier{
  81. Code: v.user.Tier.Code,
  82. Upgradeable: v.user.Tier.Upgradeable,
  83. }
  84. } else if v.user.Role == user.RoleAdmin {
  85. response.Tier = &apiAccountTier{
  86. Code: string(user.TierUnlimited),
  87. Upgradeable: false,
  88. }
  89. } else {
  90. response.Tier = &apiAccountTier{
  91. Code: string(user.TierDefault),
  92. Upgradeable: true,
  93. }
  94. }
  95. reservations, err := s.userManager.Reservations(v.user.Name)
  96. if err != nil {
  97. return err
  98. }
  99. if len(reservations) > 0 {
  100. response.Reservations = make([]*apiAccountReservation, 0)
  101. for _, r := range reservations {
  102. response.Reservations = append(response.Reservations, &apiAccountReservation{
  103. Topic: r.Topic,
  104. Everyone: r.Everyone.String(),
  105. })
  106. }
  107. }
  108. } else {
  109. response.Username = user.Everyone
  110. response.Role = string(user.RoleAnonymous)
  111. response.Tier = &apiAccountTier{
  112. Code: string(user.TierNone),
  113. Upgradeable: true,
  114. }
  115. }
  116. w.Header().Set("Content-Type", "application/json")
  117. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  118. if err := json.NewEncoder(w).Encode(response); err != nil {
  119. return err
  120. }
  121. return nil
  122. }
  123. func (s *Server) handleAccountDelete(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  124. if err := s.userManager.RemoveUser(v.user.Name); err != nil {
  125. return err
  126. }
  127. w.Header().Set("Content-Type", "application/json")
  128. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  129. return nil
  130. }
  131. func (s *Server) handleAccountPasswordChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  132. newPassword, err := readJSONWithLimit[apiAccountPasswordChangeRequest](r.Body, jsonBodyBytesLimit)
  133. if err != nil {
  134. return err
  135. }
  136. if err := s.userManager.ChangePassword(v.user.Name, newPassword.Password); 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. return nil
  142. }
  143. func (s *Server) handleAccountTokenIssue(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  144. // TODO rate limit
  145. token, err := s.userManager.CreateToken(v.user)
  146. if err != nil {
  147. return err
  148. }
  149. w.Header().Set("Content-Type", "application/json")
  150. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  151. response := &apiAccountTokenResponse{
  152. Token: token.Value,
  153. Expires: token.Expires.Unix(),
  154. }
  155. if err := json.NewEncoder(w).Encode(response); err != nil {
  156. return err
  157. }
  158. return nil
  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. w.Header().Set("Content-Type", "application/json")
  172. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  173. response := &apiAccountTokenResponse{
  174. Token: token.Value,
  175. Expires: token.Expires.Unix(),
  176. }
  177. if err := json.NewEncoder(w).Encode(response); err != nil {
  178. return err
  179. }
  180. return nil
  181. }
  182. func (s *Server) handleAccountTokenDelete(w http.ResponseWriter, _ *http.Request, v *visitor) error {
  183. // TODO rate limit
  184. if v.user.Token == "" {
  185. return errHTTPBadRequestNoTokenProvided
  186. }
  187. if err := s.userManager.RemoveToken(v.user); err != nil {
  188. return err
  189. }
  190. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  191. return nil
  192. }
  193. func (s *Server) handleAccountSettingsChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  194. newPrefs, err := readJSONWithLimit[user.Prefs](r.Body, jsonBodyBytesLimit)
  195. if err != nil {
  196. return err
  197. }
  198. if v.user.Prefs == nil {
  199. v.user.Prefs = &user.Prefs{}
  200. }
  201. prefs := v.user.Prefs
  202. if newPrefs.Language != "" {
  203. prefs.Language = newPrefs.Language
  204. }
  205. if newPrefs.Notification != nil {
  206. if prefs.Notification == nil {
  207. prefs.Notification = &user.NotificationPrefs{}
  208. }
  209. if newPrefs.Notification.DeleteAfter > 0 {
  210. prefs.Notification.DeleteAfter = newPrefs.Notification.DeleteAfter
  211. }
  212. if newPrefs.Notification.Sound != "" {
  213. prefs.Notification.Sound = newPrefs.Notification.Sound
  214. }
  215. if newPrefs.Notification.MinPriority > 0 {
  216. prefs.Notification.MinPriority = newPrefs.Notification.MinPriority
  217. }
  218. }
  219. if err := s.userManager.ChangeSettings(v.user); err != nil {
  220. return err
  221. }
  222. w.Header().Set("Content-Type", "application/json")
  223. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  224. return nil
  225. }
  226. func (s *Server) handleAccountSubscriptionAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  227. newSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit)
  228. if err != nil {
  229. return err
  230. }
  231. if v.user.Prefs == nil {
  232. v.user.Prefs = &user.Prefs{}
  233. }
  234. newSubscription.ID = "" // Client cannot set ID
  235. for _, subscription := range v.user.Prefs.Subscriptions {
  236. if newSubscription.BaseURL == subscription.BaseURL && newSubscription.Topic == subscription.Topic {
  237. newSubscription = subscription
  238. break
  239. }
  240. }
  241. if newSubscription.ID == "" {
  242. newSubscription.ID = util.RandomString(subscriptionIDLength)
  243. v.user.Prefs.Subscriptions = append(v.user.Prefs.Subscriptions, newSubscription)
  244. if err := s.userManager.ChangeSettings(v.user); err != nil {
  245. return err
  246. }
  247. }
  248. w.Header().Set("Content-Type", "application/json")
  249. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  250. if err := json.NewEncoder(w).Encode(newSubscription); err != nil {
  251. return err
  252. }
  253. return nil
  254. }
  255. func (s *Server) handleAccountSubscriptionChange(w http.ResponseWriter, r *http.Request, v *visitor) error {
  256. matches := accountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  257. if len(matches) != 2 {
  258. return errHTTPInternalErrorInvalidPath
  259. }
  260. subscriptionID := matches[1]
  261. updatedSubscription, err := readJSONWithLimit[user.Subscription](r.Body, jsonBodyBytesLimit)
  262. if err != nil {
  263. return err
  264. }
  265. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  266. return errHTTPNotFound
  267. }
  268. var subscription *user.Subscription
  269. for _, sub := range v.user.Prefs.Subscriptions {
  270. if sub.ID == subscriptionID {
  271. sub.DisplayName = updatedSubscription.DisplayName
  272. subscription = sub
  273. break
  274. }
  275. }
  276. if subscription == nil {
  277. return errHTTPNotFound
  278. }
  279. if err := s.userManager.ChangeSettings(v.user); err != nil {
  280. return err
  281. }
  282. w.Header().Set("Content-Type", "application/json")
  283. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  284. if err := json.NewEncoder(w).Encode(subscription); err != nil {
  285. return err
  286. }
  287. return nil
  288. }
  289. func (s *Server) handleAccountSubscriptionDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  290. matches := accountSubscriptionSingleRegex.FindStringSubmatch(r.URL.Path)
  291. if len(matches) != 2 {
  292. return errHTTPInternalErrorInvalidPath
  293. }
  294. subscriptionID := matches[1]
  295. if v.user.Prefs == nil || v.user.Prefs.Subscriptions == nil {
  296. return nil
  297. }
  298. newSubscriptions := make([]*user.Subscription, 0)
  299. for _, subscription := range v.user.Prefs.Subscriptions {
  300. if subscription.ID != subscriptionID {
  301. newSubscriptions = append(newSubscriptions, subscription)
  302. }
  303. }
  304. if len(newSubscriptions) < len(v.user.Prefs.Subscriptions) {
  305. v.user.Prefs.Subscriptions = newSubscriptions
  306. if err := s.userManager.ChangeSettings(v.user); err != nil {
  307. return err
  308. }
  309. }
  310. w.Header().Set("Content-Type", "application/json")
  311. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  312. return nil
  313. }
  314. func (s *Server) handleAccountAccessAdd(w http.ResponseWriter, r *http.Request, v *visitor) error {
  315. if v.user != nil && v.user.Role == user.RoleAdmin {
  316. return errHTTPBadRequestMakesNoSenseForAdmin
  317. }
  318. req, err := readJSONWithLimit[apiAccountAccessRequest](r.Body, jsonBodyBytesLimit)
  319. if err != nil {
  320. return err
  321. }
  322. if !topicRegex.MatchString(req.Topic) {
  323. return errHTTPBadRequestTopicInvalid
  324. }
  325. everyone, err := user.ParsePermission(req.Everyone)
  326. if err != nil {
  327. return errHTTPBadRequestPermissionInvalid
  328. }
  329. if v.user.Tier == nil {
  330. return errHTTPUnauthorized // FIXME there should always be a plan!
  331. }
  332. if err := s.userManager.CheckAllowAccess(v.user.Name, req.Topic); err != nil {
  333. return errHTTPConflictTopicReserved
  334. }
  335. hasReservation, err := s.userManager.HasReservation(v.user.Name, req.Topic)
  336. if err != nil {
  337. return err
  338. }
  339. if !hasReservation {
  340. reservations, err := s.userManager.ReservationsCount(v.user.Name)
  341. if err != nil {
  342. return err
  343. } else if reservations >= v.user.Tier.ReservationsLimit {
  344. return errHTTPTooManyRequestsLimitReservations
  345. }
  346. }
  347. owner, username := v.user.Name, v.user.Name
  348. if err := s.userManager.AllowAccess(owner, username, req.Topic, true, true); err != nil {
  349. return err
  350. }
  351. if err := s.userManager.AllowAccess(owner, user.Everyone, req.Topic, everyone.IsRead(), everyone.IsWrite()); err != nil {
  352. return err
  353. }
  354. w.Header().Set("Content-Type", "application/json")
  355. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  356. return nil
  357. }
  358. func (s *Server) handleAccountAccessDelete(w http.ResponseWriter, r *http.Request, v *visitor) error {
  359. matches := accountAccessSingleRegex.FindStringSubmatch(r.URL.Path)
  360. if len(matches) != 2 {
  361. return errHTTPInternalErrorInvalidPath
  362. }
  363. topic := matches[1]
  364. if !topicRegex.MatchString(topic) {
  365. return errHTTPBadRequestTopicInvalid
  366. }
  367. authorized, err := s.userManager.HasReservation(v.user.Name, topic)
  368. if err != nil {
  369. return err
  370. } else if !authorized {
  371. return errHTTPUnauthorized
  372. }
  373. if err := s.userManager.ResetAccess(v.user.Name, topic); err != nil {
  374. return err
  375. }
  376. if err := s.userManager.ResetAccess(user.Everyone, topic); err != nil {
  377. return err
  378. }
  379. w.Header().Set("Content-Type", "application/json")
  380. w.Header().Set("Access-Control-Allow-Origin", "*") // FIXME remove this
  381. return nil
  382. }