server_account.go 10 KB

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