user.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. createdByCLI = "cli"
  17. )
  18. func init() {
  19. commands = append(commands, cmdUser)
  20. }
  21. var flagsUser = append(
  22. flagsDefault,
  23. &cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: defaultServerConfigFile, DefaultText: defaultServerConfigFile, Usage: "config file"},
  24. 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"}),
  25. 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"}),
  26. )
  27. var cmdUser = &cli.Command{
  28. Name: "user",
  29. Usage: "Manage/show users",
  30. UsageText: "ntfy user [list|add|remove|change-pass|change-role] ...",
  31. Flags: flagsUser,
  32. Before: initConfigFileInputSourceFunc("config", flagsUser, initLogFunc),
  33. Category: categoryServer,
  34. Subcommands: []*cli.Command{
  35. {
  36. Name: "add",
  37. Aliases: []string{"a"},
  38. Usage: "Adds a new user",
  39. UsageText: "ntfy user add [--role=admin|user] USERNAME\nNTFY_PASSWORD=... ntfy user add [--role=admin|user] USERNAME",
  40. Action: execUserAdd,
  41. Flags: []cli.Flag{
  42. &cli.StringFlag{Name: "role", Aliases: []string{"r"}, Value: string(user.RoleUser), Usage: "user role"},
  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 is a server-only command. It directly reads from the user.db as defined in the server config
  122. file server.yml. The command only works if 'auth-file' is properly defined.
  123. This command is an alias to calling 'ntfy access' (display access control list).
  124. `,
  125. },
  126. },
  127. Description: `Manage users of the ntfy server.
  128. This is a server-only command. It directly manages the user.db as defined in the server config
  129. file server.yml. The command only works if 'auth-file' is properly defined. Please also refer
  130. to the related command 'ntfy access'.
  131. The command allows you to add/remove/change users in the ntfy user database, as well as change
  132. passwords or roles.
  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 {
  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. return fmt.Errorf("user %s already exists", username)
  163. }
  164. if password == "" {
  165. p, err := readPasswordAndConfirm(c)
  166. if err != nil {
  167. return err
  168. }
  169. password = p
  170. }
  171. if err := manager.AddUser(username, password, role, createdByCLI); err != nil {
  172. return err
  173. }
  174. fmt.Fprintf(c.App.ErrWriter, "user %s added with role %s\n", username, role)
  175. return nil
  176. }
  177. func execUserDel(c *cli.Context) error {
  178. username := c.Args().Get(0)
  179. if username == "" {
  180. return errors.New("username expected, type 'ntfy user del --help' for help")
  181. } else if username == userEveryone {
  182. return errors.New("username not allowed")
  183. }
  184. manager, err := createUserManager(c)
  185. if err != nil {
  186. return err
  187. }
  188. if _, err := manager.User(username); err == user.ErrUserNotFound {
  189. return fmt.Errorf("user %s does not exist", username)
  190. }
  191. if err := manager.RemoveUser(username); err != nil {
  192. return err
  193. }
  194. fmt.Fprintf(c.App.ErrWriter, "user %s removed\n", username)
  195. return nil
  196. }
  197. func execUserChangePass(c *cli.Context) error {
  198. username := c.Args().Get(0)
  199. password := os.Getenv("NTFY_PASSWORD")
  200. if username == "" {
  201. return errors.New("username expected, type 'ntfy user change-pass --help' for help")
  202. } else if username == userEveryone {
  203. return errors.New("username not allowed")
  204. }
  205. manager, err := createUserManager(c)
  206. if err != nil {
  207. return err
  208. }
  209. if _, err := manager.User(username); err == user.ErrUserNotFound {
  210. return fmt.Errorf("user %s does not exist", username)
  211. }
  212. if password == "" {
  213. password, err = readPasswordAndConfirm(c)
  214. if err != nil {
  215. return err
  216. }
  217. }
  218. if err := manager.ChangePassword(username, password); err != nil {
  219. return err
  220. }
  221. fmt.Fprintf(c.App.ErrWriter, "changed password for user %s\n", username)
  222. return nil
  223. }
  224. func execUserChangeRole(c *cli.Context) error {
  225. username := c.Args().Get(0)
  226. role := user.Role(c.Args().Get(1))
  227. if username == "" || !user.AllowedRole(role) {
  228. return errors.New("username and new role expected, type 'ntfy user change-role --help' for help")
  229. } else if username == userEveryone {
  230. return errors.New("username not allowed")
  231. }
  232. manager, err := createUserManager(c)
  233. if err != nil {
  234. return err
  235. }
  236. if _, err := manager.User(username); err == user.ErrUserNotFound {
  237. return fmt.Errorf("user %s does not exist", username)
  238. }
  239. if err := manager.ChangeRole(username, role); err != nil {
  240. return err
  241. }
  242. fmt.Fprintf(c.App.ErrWriter, "changed role for user %s to %s\n", username, role)
  243. return nil
  244. }
  245. func execUserChangeTier(c *cli.Context) error {
  246. username := c.Args().Get(0)
  247. tier := c.Args().Get(1)
  248. if username == "" {
  249. return errors.New("username and new tier expected, type 'ntfy user change-tier --help' for help")
  250. } else if !user.AllowedTier(tier) && tier != tierReset {
  251. return errors.New("invalid tier, must be tier code, or - to reset")
  252. } else if username == userEveryone {
  253. return errors.New("username not allowed")
  254. }
  255. manager, err := createUserManager(c)
  256. if err != nil {
  257. return err
  258. }
  259. if _, err := manager.User(username); err == user.ErrUserNotFound {
  260. return fmt.Errorf("user %s does not exist", username)
  261. }
  262. if tier == tierReset {
  263. if err := manager.ResetTier(username); err != nil {
  264. return err
  265. }
  266. fmt.Fprintf(c.App.ErrWriter, "removed tier from user %s\n", username)
  267. } else {
  268. if err := manager.ChangeTier(username, tier); err != nil {
  269. return err
  270. }
  271. fmt.Fprintf(c.App.ErrWriter, "changed tier for user %s to %s\n", username, tier)
  272. }
  273. return nil
  274. }
  275. func execUserList(c *cli.Context) error {
  276. manager, err := createUserManager(c)
  277. if err != nil {
  278. return err
  279. }
  280. users, err := manager.Users()
  281. if err != nil {
  282. return err
  283. }
  284. return showUsers(c, manager, users)
  285. }
  286. func createUserManager(c *cli.Context) (*user.Manager, error) {
  287. authFile := c.String("auth-file")
  288. authStartupQueries := c.String("auth-startup-queries")
  289. authDefaultAccess := c.String("auth-default-access")
  290. if authFile == "" {
  291. return nil, errors.New("option auth-file not set; auth is unconfigured for this server")
  292. } else if !util.FileExists(authFile) {
  293. return nil, errors.New("auth-file does not exist; please start the server at least once to create it")
  294. }
  295. authDefault, err := user.ParsePermission(authDefaultAccess)
  296. if err != nil {
  297. return nil, errors.New("if set, auth-default-access must start set to 'read-write', 'read-only', 'write-only' or 'deny-all'")
  298. }
  299. return user.NewManager(authFile, authStartupQueries, authDefault)
  300. }
  301. func readPasswordAndConfirm(c *cli.Context) (string, error) {
  302. fmt.Fprint(c.App.ErrWriter, "password: ")
  303. password, err := util.ReadPassword(c.App.Reader)
  304. if err != nil {
  305. return "", err
  306. }
  307. fmt.Fprintf(c.App.ErrWriter, "\r%s\rconfirm: ", strings.Repeat(" ", 25))
  308. confirm, err := util.ReadPassword(c.App.Reader)
  309. if err != nil {
  310. return "", err
  311. }
  312. fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 25))
  313. if subtle.ConstantTimeCompare(confirm, password) != 1 {
  314. return "", errors.New("passwords do not match: try it again, but this time type slooowwwlly")
  315. }
  316. return string(password), nil
  317. }