server_account.go 12 KB

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