user.go 12 KB

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