user.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. //go:build !noserver
  2. package cmd
  3. import (
  4. "crypto/subtle"
  5. "errors"
  6. "fmt"
  7. "heckel.io/ntfy/user"
  8. "os"
  9. "strings"
  10. "github.com/urfave/cli/v2"
  11. "github.com/urfave/cli/v2/altsrc"
  12. "heckel.io/ntfy/util"
  13. )
  14. const (
  15. tierReset = "-"
  16. )
  17. func init() {
  18. commands = append(commands, cmdUser)
  19. }
  20. var flagsUser = append(
  21. append([]cli.Flag{}, flagsDefault...),
  22. &cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: defaultServerConfigFile, DefaultText: defaultServerConfigFile, Usage: "config file"},
  23. altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-file", Aliases: []string{"auth_file", "H"}, EnvVars: []string{"NTFY_AUTH_FILE"}, Usage: "auth database file used for access control"}),
  24. altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-default-access", Aliases: []string{"auth_default_access", "p"}, EnvVars: []string{"NTFY_AUTH_DEFAULT_ACCESS"}, Value: "read-write", Usage: "default permissions if no matching entries in the auth database are found"}),
  25. )
  26. var cmdUser = &cli.Command{
  27. Name: "user",
  28. Usage: "Manage/show users",
  29. UsageText: "ntfy user [list|add|remove|change-pass|change-role] ...",
  30. Flags: flagsUser,
  31. Before: initConfigFileInputSourceFunc("config", flagsUser, initLogFunc),
  32. Category: categoryServer,
  33. Subcommands: []*cli.Command{
  34. {
  35. Name: "add",
  36. Aliases: []string{"a"},
  37. Usage: "Adds a new user",
  38. UsageText: "ntfy user add [--role=admin|user] USERNAME\nNTFY_PASSWORD=... ntfy user add [--role=admin|user] USERNAME",
  39. Action: execUserAdd,
  40. Flags: []cli.Flag{
  41. &cli.StringFlag{Name: "role", Aliases: []string{"r"}, Value: string(user.RoleUser), Usage: "user role"},
  42. &cli.BoolFlag{Name: "ignore-exists", Usage: "if the user already exists, perform no action and exit"},
  43. },
  44. Description: `Add a new user to the ntfy user database.
  45. A user can be either a regular user, or an admin. A regular user has no read or write access (unless
  46. granted otherwise by the auth-default-access setting). An admin user has read and write access to all
  47. topics.
  48. Examples:
  49. ntfy user add phil # Add regular user phil
  50. ntfy user add --role=admin phil # Add admin user phil
  51. NTFY_PASSWORD=... ntfy user add phil # Add user, using env variable to set password (for scripts)
  52. You may set the NTFY_PASSWORD environment variable to pass the password. This is useful if
  53. you are creating users via scripts.
  54. `,
  55. },
  56. {
  57. Name: "remove",
  58. Aliases: []string{"del", "rm"},
  59. Usage: "Removes a user",
  60. UsageText: "ntfy user remove USERNAME",
  61. Action: execUserDel,
  62. Description: `Remove a user from the ntfy user database.
  63. Example:
  64. ntfy user del phil
  65. `,
  66. },
  67. {
  68. Name: "change-pass",
  69. Aliases: []string{"chp"},
  70. Usage: "Changes a user's password",
  71. UsageText: "ntfy user change-pass USERNAME\nNTFY_PASSWORD=... ntfy user change-pass USERNAME",
  72. Action: execUserChangePass,
  73. Description: `Change the password for the given user.
  74. The new password will be read from STDIN, and it'll be confirmed by typing
  75. it twice.
  76. Example:
  77. ntfy user change-pass phil
  78. NTFY_PASSWORD=.. ntfy user change-pass phil
  79. You may set the NTFY_PASSWORD environment variable to pass the new password. This is
  80. useful if you are updating users via scripts.
  81. `,
  82. },
  83. {
  84. Name: "change-role",
  85. Aliases: []string{"chr"},
  86. Usage: "Changes the role of a user",
  87. UsageText: "ntfy user change-role USERNAME ROLE",
  88. Action: execUserChangeRole,
  89. Description: `Change the role for the given user to admin or user.
  90. This command can be used to change the role of a user either from a regular user
  91. to an admin user, or the other way around:
  92. - admin: an admin has read/write access to all topics
  93. - user: a regular user only has access to what was explicitly granted via 'ntfy access'
  94. When changing the role of a user to "admin", all access control entries for that
  95. user are removed, since they are no longer necessary.
  96. Example:
  97. ntfy user change-role phil admin # Make user phil an admin
  98. ntfy user change-role phil user # Remove admin role from user phil
  99. `,
  100. },
  101. {
  102. Name: "change-tier",
  103. Aliases: []string{"cht"},
  104. Usage: "Changes the tier of a user",
  105. UsageText: "ntfy user change-tier USERNAME (TIER|-)",
  106. Action: execUserChangeTier,
  107. Description: `Change the tier for the given user.
  108. This command can be used to change the tier of a user. Tiers define usage limits, such
  109. as messages per day, attachment file sizes, etc.
  110. Example:
  111. ntfy user change-tier phil pro # Change tier to "pro" for user "phil"
  112. ntfy user change-tier phil - # Remove tier from user "phil" entirely
  113. `,
  114. },
  115. {
  116. Name: "list",
  117. Aliases: []string{"l"},
  118. Usage: "Shows a list of users",
  119. Action: execUserList,
  120. Description: `Shows a list of all configured users, including the everyone ('*') user.
  121. This command is an alias to calling 'ntfy access' (display access control list).
  122. This is a server-only command. It directly reads from user.db as defined in the server config
  123. file server.yml. The command only works if 'auth-file' is properly defined.
  124. `,
  125. },
  126. },
  127. Description: `Manage users of the ntfy server.
  128. The command allows you to add/remove/change users in the ntfy user database, as well as change
  129. passwords or roles.
  130. This is a server-only command. It directly manages the user.db as defined in the server config
  131. file server.yml. The command only works if 'auth-file' is properly defined. Please also refer
  132. to the related command 'ntfy access'.
  133. Examples:
  134. ntfy user list # Shows list of users (alias: 'ntfy access')
  135. ntfy user add phil # Add regular user phil
  136. NTFY_PASSWORD=... ntfy user add phil # As above, using env variable to set password (for scripts)
  137. ntfy user add --role=admin phil # Add admin user phil
  138. ntfy user del phil # Delete user phil
  139. ntfy user change-pass phil # Change password for user phil
  140. NTFY_PASSWORD=.. ntfy user change-pass phil # As above, using env variable to set password (for scripts)
  141. ntfy user change-role phil admin # Make user phil an admin
  142. For the 'ntfy user add' and 'ntfy user change-pass' commands, you may set the NTFY_PASSWORD environment
  143. variable to pass the new password. This is useful if you are creating/updating users via scripts.
  144. `,
  145. }
  146. func execUserAdd(c *cli.Context) error {
  147. username := c.Args().Get(0)
  148. role := user.Role(c.String("role"))
  149. password := os.Getenv("NTFY_PASSWORD")
  150. if username == "" {
  151. return errors.New("username expected, type 'ntfy user add --help' for help")
  152. } else if username == userEveryone || username == user.Everyone {
  153. return errors.New("username not allowed")
  154. } else if !user.AllowedRole(role) {
  155. return errors.New("role must be either 'user' or 'admin'")
  156. }
  157. manager, err := createUserManager(c)
  158. if err != nil {
  159. return err
  160. }
  161. if user, _ := manager.User(username); user != nil {
  162. if c.Bool("ignore-exists") {
  163. fmt.Fprintf(c.App.ErrWriter, "user %s already exists (exited successfully)\n", username)
  164. return nil
  165. }
  166. return fmt.Errorf("user %s already exists", username)
  167. }
  168. if password == "" {
  169. p, err := readPasswordAndConfirm(c)
  170. if err != nil {
  171. return err
  172. }
  173. password = p
  174. }
  175. if err := manager.AddUser(username, password, role); err != nil {
  176. return err
  177. }
  178. fmt.Fprintf(c.App.ErrWriter, "user %s added with role %s\n", username, role)
  179. return nil
  180. }
  181. func execUserDel(c *cli.Context) error {
  182. username := c.Args().Get(0)
  183. if username == "" {
  184. return errors.New("username expected, type 'ntfy user del --help' for help")
  185. } else if username == userEveryone || username == user.Everyone {
  186. return errors.New("username not allowed")
  187. }
  188. manager, err := createUserManager(c)
  189. if err != nil {
  190. return err
  191. }
  192. if _, err := manager.User(username); err == user.ErrUserNotFound {
  193. return fmt.Errorf("user %s does not exist", username)
  194. }
  195. if err := manager.RemoveUser(username); err != nil {
  196. return err
  197. }
  198. fmt.Fprintf(c.App.ErrWriter, "user %s removed\n", username)
  199. return nil
  200. }
  201. func execUserChangePass(c *cli.Context) error {
  202. username := c.Args().Get(0)
  203. password := os.Getenv("NTFY_PASSWORD")
  204. if username == "" {
  205. return errors.New("username expected, type 'ntfy user change-pass --help' for help")
  206. } else if username == userEveryone || username == user.Everyone {
  207. return errors.New("username not allowed")
  208. }
  209. manager, err := createUserManager(c)
  210. if err != nil {
  211. return err
  212. }
  213. if _, err := manager.User(username); err == user.ErrUserNotFound {
  214. return fmt.Errorf("user %s does not exist", username)
  215. }
  216. if password == "" {
  217. password, err = readPasswordAndConfirm(c)
  218. if err != nil {
  219. return err
  220. }
  221. }
  222. if err := manager.ChangePassword(username, password); err != nil {
  223. return err
  224. }
  225. fmt.Fprintf(c.App.ErrWriter, "changed password for user %s\n", username)
  226. return nil
  227. }
  228. func execUserChangeRole(c *cli.Context) error {
  229. username := c.Args().Get(0)
  230. role := user.Role(c.Args().Get(1))
  231. if username == "" || !user.AllowedRole(role) {
  232. return errors.New("username and new role expected, type 'ntfy user change-role --help' for help")
  233. } else if username == userEveryone || username == user.Everyone {
  234. return errors.New("username not allowed")
  235. }
  236. manager, err := createUserManager(c)
  237. if err != nil {
  238. return err
  239. }
  240. if _, err := manager.User(username); err == user.ErrUserNotFound {
  241. return fmt.Errorf("user %s does not exist", username)
  242. }
  243. if err := manager.ChangeRole(username, role); err != nil {
  244. return err
  245. }
  246. fmt.Fprintf(c.App.ErrWriter, "changed role for user %s to %s\n", username, role)
  247. return nil
  248. }
  249. func execUserChangeTier(c *cli.Context) error {
  250. username := c.Args().Get(0)
  251. tier := c.Args().Get(1)
  252. if username == "" {
  253. return errors.New("username and new tier expected, type 'ntfy user change-tier --help' for help")
  254. } else if !user.AllowedTier(tier) && tier != tierReset {
  255. return errors.New("invalid tier, must be tier code, or - to reset")
  256. } else if username == userEveryone || username == user.Everyone {
  257. return errors.New("username not allowed")
  258. }
  259. manager, err := createUserManager(c)
  260. if err != nil {
  261. return err
  262. }
  263. if _, err := manager.User(username); err == user.ErrUserNotFound {
  264. return fmt.Errorf("user %s does not exist", username)
  265. }
  266. if tier == tierReset {
  267. if err := manager.ResetTier(username); err != nil {
  268. return err
  269. }
  270. fmt.Fprintf(c.App.ErrWriter, "removed tier from user %s\n", username)
  271. } else {
  272. if err := manager.ChangeTier(username, tier); err != nil {
  273. return err
  274. }
  275. fmt.Fprintf(c.App.ErrWriter, "changed tier for user %s to %s\n", username, tier)
  276. }
  277. return nil
  278. }
  279. func execUserList(c *cli.Context) error {
  280. manager, err := createUserManager(c)
  281. if err != nil {
  282. return err
  283. }
  284. users, err := manager.Users()
  285. if err != nil {
  286. return err
  287. }
  288. return showUsers(c, manager, users)
  289. }
  290. func createUserManager(c *cli.Context) (*user.Manager, error) {
  291. authFile := c.String("auth-file")
  292. authStartupQueries := c.String("auth-startup-queries")
  293. authDefaultAccess := c.String("auth-default-access")
  294. if authFile == "" {
  295. return nil, errors.New("option auth-file not set; auth is unconfigured for this server")
  296. } else if !util.FileExists(authFile) {
  297. return nil, errors.New("auth-file does not exist; please start the server at least once to create it")
  298. }
  299. authDefault, err := user.ParsePermission(authDefaultAccess)
  300. if err != nil {
  301. return nil, errors.New("if set, auth-default-access must start set to 'read-write', 'read-only', 'write-only' or 'deny-all'")
  302. }
  303. return user.NewManager(authFile, authStartupQueries, authDefault, user.DefaultUserPasswordBcryptCost, user.DefaultUserStatsQueueWriterInterval)
  304. }
  305. func readPasswordAndConfirm(c *cli.Context) (string, error) {
  306. fmt.Fprint(c.App.ErrWriter, "password: ")
  307. password, err := util.ReadPassword(c.App.Reader)
  308. if err != nil {
  309. return "", err
  310. }
  311. fmt.Fprintf(c.App.ErrWriter, "\r%s\rconfirm: ", strings.Repeat(" ", 25))
  312. confirm, err := util.ReadPassword(c.App.Reader)
  313. if err != nil {
  314. return "", err
  315. }
  316. fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 25))
  317. if subtle.ConstantTimeCompare(confirm, password) != 1 {
  318. return "", errors.New("passwords do not match: try it again, but this time type slooowwwlly")
  319. }
  320. return string(password), nil
  321. }