user.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. package cmd
  2. import (
  3. "crypto/subtle"
  4. "errors"
  5. "fmt"
  6. "github.com/urfave/cli/v2"
  7. "github.com/urfave/cli/v2/altsrc"
  8. "heckel.io/ntfy/auth"
  9. "heckel.io/ntfy/util"
  10. "strings"
  11. )
  12. var flagsUser = userCommandFlags()
  13. var cmdUser = &cli.Command{
  14. Name: "user",
  15. Usage: "Manage/show users",
  16. UsageText: "ntfy user [list|add|remove|change-pass|change-role] ...",
  17. Flags: flagsUser,
  18. Before: initConfigFileInputSource("config", flagsUser),
  19. Category: categoryServer,
  20. Subcommands: []*cli.Command{
  21. {
  22. Name: "add",
  23. Aliases: []string{"a"},
  24. Usage: "Adds a new user",
  25. UsageText: "ntfy user add [--role=admin|user] USERNAME",
  26. Action: execUserAdd,
  27. Flags: []cli.Flag{
  28. &cli.StringFlag{Name: "role", Aliases: []string{"r"}, Value: string(auth.RoleUser), Usage: "user role"},
  29. },
  30. Description: `Add a new user to the ntfy user database.
  31. A user can be either a regular user, or an admin. A regular user has no read or write access (unless
  32. granted otherwise by the auth-default-access setting). An admin user has read and write access to all
  33. topics.
  34. Examples:
  35. ntfy user add phil # Add regular user phil
  36. ntfy user add --role=admin phil # Add admin user phil
  37. `,
  38. },
  39. {
  40. Name: "remove",
  41. Aliases: []string{"del", "rm"},
  42. Usage: "Removes a user",
  43. UsageText: "ntfy user remove USERNAME",
  44. Action: execUserDel,
  45. Description: `Remove a user from the ntfy user database.
  46. Example:
  47. ntfy user del phil
  48. `,
  49. },
  50. {
  51. Name: "change-pass",
  52. Aliases: []string{"chp"},
  53. Usage: "Changes a user's password",
  54. UsageText: "ntfy user change-pass USERNAME",
  55. Action: execUserChangePass,
  56. Description: `Change the password for the given user.
  57. The new password will be read from STDIN, and it'll be confirmed by typing
  58. it twice.
  59. Example:
  60. ntfy user change-pass phil
  61. `,
  62. },
  63. {
  64. Name: "change-role",
  65. Aliases: []string{"chr"},
  66. Usage: "Changes the role of a user",
  67. UsageText: "ntfy user change-role USERNAME ROLE",
  68. Action: execUserChangeRole,
  69. Description: `Change the role for the given user to admin or user.
  70. This command can be used to change the role of a user either from a regular user
  71. to an admin user, or the other way around:
  72. - admin: an admin has read/write access to all topics
  73. - user: a regular user only has access to what was explicitly granted via 'ntfy access'
  74. When changing the role of a user to "admin", all access control entries for that
  75. user are removed, since they are no longer necessary.
  76. Example:
  77. ntfy user change-role phil admin # Make user phil an admin
  78. ntfy user change-role phil user # Remove admin role from user phil
  79. `,
  80. },
  81. {
  82. Name: "list",
  83. Aliases: []string{"l"},
  84. Usage: "Shows a list of users",
  85. Action: execUserList,
  86. Description: `Shows a list of all configured users, including the everyone ('*') user.
  87. This is a server-only command. It directly reads from the user.db as defined in the server config
  88. file server.yml. The command only works if 'auth-file' is properly defined.
  89. This command is an alias to calling 'ntfy access' (display access control list).
  90. `,
  91. },
  92. },
  93. Description: `Manage users of the ntfy server.
  94. This is a server-only command. It directly manages the user.db as defined in the server config
  95. file server.yml. The command only works if 'auth-file' is properly defined. Please also refer
  96. to the related command 'ntfy access'.
  97. The command allows you to add/remove/change users in the ntfy user database, as well as change
  98. passwords or roles.
  99. Examples:
  100. ntfy user list # Shows list of users (alias: 'ntfy access')
  101. ntfy user add phil # Add regular user phil
  102. ntfy user add --role=admin phil # Add admin user phil
  103. ntfy user del phil # Delete user phil
  104. ntfy user change-pass phil # Change password for user phil
  105. ntfy user change-role phil admin # Make user phil an admin
  106. `,
  107. }
  108. func execUserAdd(c *cli.Context) error {
  109. username := c.Args().Get(0)
  110. role := auth.Role(c.String("role"))
  111. if username == "" {
  112. return errors.New("username expected, type 'ntfy user add --help' for help")
  113. } else if username == userEveryone {
  114. return errors.New("username not allowed")
  115. } else if !auth.AllowedRole(role) {
  116. return errors.New("role must be either 'user' or 'admin'")
  117. }
  118. manager, err := createAuthManager(c)
  119. if err != nil {
  120. return err
  121. }
  122. if user, _ := manager.User(username); user != nil {
  123. return fmt.Errorf("user %s already exists", username)
  124. }
  125. password, err := readPasswordAndConfirm(c)
  126. if err != nil {
  127. return err
  128. }
  129. if err := manager.AddUser(username, password, role); err != nil {
  130. return err
  131. }
  132. fmt.Fprintf(c.App.ErrWriter, "user %s added with role %s\n", username, role)
  133. return nil
  134. }
  135. func execUserDel(c *cli.Context) error {
  136. username := c.Args().Get(0)
  137. if username == "" {
  138. return errors.New("username expected, type 'ntfy user del --help' for help")
  139. } else if username == userEveryone {
  140. return errors.New("username not allowed")
  141. }
  142. manager, err := createAuthManager(c)
  143. if err != nil {
  144. return err
  145. }
  146. if _, err := manager.User(username); err == auth.ErrNotFound {
  147. return fmt.Errorf("user %s does not exist", username)
  148. }
  149. if err := manager.RemoveUser(username); err != nil {
  150. return err
  151. }
  152. fmt.Fprintf(c.App.ErrWriter, "user %s removed\n", username)
  153. return nil
  154. }
  155. func execUserChangePass(c *cli.Context) error {
  156. username := c.Args().Get(0)
  157. if username == "" {
  158. return errors.New("username expected, type 'ntfy user change-pass --help' for help")
  159. } else if username == userEveryone {
  160. return errors.New("username not allowed")
  161. }
  162. manager, err := createAuthManager(c)
  163. if err != nil {
  164. return err
  165. }
  166. if _, err := manager.User(username); err == auth.ErrNotFound {
  167. return fmt.Errorf("user %s does not exist", username)
  168. }
  169. password, err := readPasswordAndConfirm(c)
  170. if err != nil {
  171. return err
  172. }
  173. if err := manager.ChangePassword(username, password); err != nil {
  174. return err
  175. }
  176. fmt.Fprintf(c.App.ErrWriter, "changed password for user %s\n", username)
  177. return nil
  178. }
  179. func execUserChangeRole(c *cli.Context) error {
  180. username := c.Args().Get(0)
  181. role := auth.Role(c.Args().Get(1))
  182. if username == "" || !auth.AllowedRole(role) {
  183. return errors.New("username and new role expected, type 'ntfy user change-role --help' for help")
  184. } else if username == userEveryone {
  185. return errors.New("username not allowed")
  186. }
  187. manager, err := createAuthManager(c)
  188. if err != nil {
  189. return err
  190. }
  191. if _, err := manager.User(username); err == auth.ErrNotFound {
  192. return fmt.Errorf("user %s does not exist", username)
  193. }
  194. if err := manager.ChangeRole(username, role); err != nil {
  195. return err
  196. }
  197. fmt.Fprintf(c.App.ErrWriter, "changed role for user %s to %s\n", username, role)
  198. return nil
  199. }
  200. func execUserList(c *cli.Context) error {
  201. manager, err := createAuthManager(c)
  202. if err != nil {
  203. return err
  204. }
  205. users, err := manager.Users()
  206. if err != nil {
  207. return err
  208. }
  209. return showUsers(c, manager, users)
  210. }
  211. func createAuthManager(c *cli.Context) (auth.Manager, error) {
  212. authFile := c.String("auth-file")
  213. authDefaultAccess := c.String("auth-default-access")
  214. if authFile == "" {
  215. return nil, errors.New("option auth-file not set; auth is unconfigured for this server")
  216. } else if !util.FileExists(authFile) {
  217. return nil, errors.New("auth-file does not exist; please start the server at least once to create it")
  218. } else if !util.InStringList([]string{"read-write", "read-only", "write-only", "deny-all"}, authDefaultAccess) {
  219. return nil, errors.New("if set, auth-default-access must start set to 'read-write', 'read-only' or 'deny-all'")
  220. }
  221. authDefaultRead := authDefaultAccess == "read-write" || authDefaultAccess == "read-only"
  222. authDefaultWrite := authDefaultAccess == "read-write" || authDefaultAccess == "write-only"
  223. return auth.NewSQLiteAuth(authFile, authDefaultRead, authDefaultWrite)
  224. }
  225. func readPasswordAndConfirm(c *cli.Context) (string, error) {
  226. fmt.Fprint(c.App.ErrWriter, "password: ")
  227. password, err := util.ReadPassword(c.App.Reader)
  228. if err != nil {
  229. return "", err
  230. }
  231. fmt.Fprintf(c.App.ErrWriter, "\r%s\rconfirm: ", strings.Repeat(" ", 25))
  232. confirm, err := util.ReadPassword(c.App.Reader)
  233. if err != nil {
  234. return "", err
  235. }
  236. fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 25))
  237. if subtle.ConstantTimeCompare(confirm, password) != 1 {
  238. return "", errors.New("passwords do not match: try it again, but this time type slooowwwlly")
  239. }
  240. return string(password), nil
  241. }
  242. func userCommandFlags() []cli.Flag {
  243. return []cli.Flag{
  244. &cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: "/etc/ntfy/server.yml", DefaultText: "/etc/ntfy/server.yml", Usage: "config file"},
  245. altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-file", Aliases: []string{"H"}, EnvVars: []string{"NTFY_AUTH_FILE"}, Usage: "auth database file used for access control"}),
  246. altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-default-access", Aliases: []string{"p"}, EnvVars: []string{"NTFY_AUTH_DEFAULT_ACCESS"}, Value: "read-write", Usage: "default permissions if no matching entries in the auth database are found"}),
  247. }
  248. }