server_account.go 9.3 KB

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