server_account.go 12 KB

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