server_account.go 12 KB

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