user.go 9.1 KB

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