user.go 9.1 KB

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