user.go 9.3 KB

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