user.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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: "user", Aliases: []string{"u"}, EnvVars: []string{"NTFY_USER"}, Usage: "username[:password] used to auth against the server"},
  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. var username string
  120. var password string
  121. userAndPass := c.String("user")
  122. role := auth.Role(c.String("role"))
  123. if userAndPass != "" {
  124. parts := strings.SplitN(userAndPass, ":", 2)
  125. if len(parts) == 2 {
  126. username = parts[0]
  127. password = parts[1]
  128. } else {
  129. p, err := readPasswordAndConfirm(c)
  130. if err != nil {
  131. return err
  132. }
  133. username = userAndPass
  134. password = p
  135. }
  136. } else {
  137. username = c.Args().Get(0)
  138. if username == "" {
  139. return errors.New("username expected, type 'ntfy user add --help' for help")
  140. } else if username == userEveryone {
  141. return errors.New("username not allowed")
  142. } else if !auth.AllowedRole(role) {
  143. return errors.New("role must be either 'user' or 'admin'")
  144. }
  145. p, err := readPasswordAndConfirm(c)
  146. if err != nil {
  147. return err
  148. }
  149. password = p
  150. }
  151. manager, err := createAuthManager(c)
  152. if err != nil {
  153. return err
  154. }
  155. if user, _ := manager.User(username); user != nil {
  156. return fmt.Errorf("user %s already exists", username)
  157. }
  158. if err := manager.AddUser(username, password, role); err != nil {
  159. return err
  160. }
  161. fmt.Fprintf(c.App.ErrWriter, "user %s added with role %s\n", username, role)
  162. return nil
  163. }
  164. func execUserDel(c *cli.Context) error {
  165. username := c.Args().Get(0)
  166. if username == "" {
  167. return errors.New("username expected, type 'ntfy user del --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. if err := manager.RemoveUser(username); err != nil {
  179. return err
  180. }
  181. fmt.Fprintf(c.App.ErrWriter, "user %s removed\n", username)
  182. return nil
  183. }
  184. func execUserChangePass(c *cli.Context) error {
  185. username := c.Args().Get(0)
  186. if username == "" {
  187. return errors.New("username expected, type 'ntfy user change-pass --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. password, err := readPasswordAndConfirm(c)
  199. if err != nil {
  200. return err
  201. }
  202. if err := manager.ChangePassword(username, password); err != nil {
  203. return err
  204. }
  205. fmt.Fprintf(c.App.ErrWriter, "changed password for user %s\n", username)
  206. return nil
  207. }
  208. func execUserChangeRole(c *cli.Context) error {
  209. username := c.Args().Get(0)
  210. role := auth.Role(c.Args().Get(1))
  211. if username == "" || !auth.AllowedRole(role) {
  212. return errors.New("username and new role expected, type 'ntfy user change-role --help' for help")
  213. } else if username == userEveryone {
  214. return errors.New("username not allowed")
  215. }
  216. manager, err := createAuthManager(c)
  217. if err != nil {
  218. return err
  219. }
  220. if _, err := manager.User(username); err == auth.ErrNotFound {
  221. return fmt.Errorf("user %s does not exist", username)
  222. }
  223. if err := manager.ChangeRole(username, role); err != nil {
  224. return err
  225. }
  226. fmt.Fprintf(c.App.ErrWriter, "changed role for user %s to %s\n", username, role)
  227. return nil
  228. }
  229. func execUserList(c *cli.Context) error {
  230. manager, err := createAuthManager(c)
  231. if err != nil {
  232. return err
  233. }
  234. users, err := manager.Users()
  235. if err != nil {
  236. return err
  237. }
  238. return showUsers(c, manager, users)
  239. }
  240. func createAuthManager(c *cli.Context) (auth.Manager, error) {
  241. authFile := c.String("auth-file")
  242. authDefaultAccess := c.String("auth-default-access")
  243. if authFile == "" {
  244. return nil, errors.New("option auth-file not set; auth is unconfigured for this server")
  245. } else if !util.FileExists(authFile) {
  246. return nil, errors.New("auth-file does not exist; please start the server at least once to create it")
  247. } else if !util.InStringList([]string{"read-write", "read-only", "write-only", "deny-all"}, authDefaultAccess) {
  248. return nil, errors.New("if set, auth-default-access must start set to 'read-write', 'read-only' or 'deny-all'")
  249. }
  250. authDefaultRead := authDefaultAccess == "read-write" || authDefaultAccess == "read-only"
  251. authDefaultWrite := authDefaultAccess == "read-write" || authDefaultAccess == "write-only"
  252. return auth.NewSQLiteAuth(authFile, authDefaultRead, authDefaultWrite)
  253. }
  254. func readPasswordAndConfirm(c *cli.Context) (string, error) {
  255. fmt.Fprint(c.App.ErrWriter, "password: ")
  256. password, err := util.ReadPassword(c.App.Reader)
  257. if err != nil {
  258. return "", err
  259. }
  260. fmt.Fprintf(c.App.ErrWriter, "\r%s\rconfirm: ", strings.Repeat(" ", 25))
  261. confirm, err := util.ReadPassword(c.App.Reader)
  262. if err != nil {
  263. return "", err
  264. }
  265. fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 25))
  266. if subtle.ConstantTimeCompare(confirm, password) != 1 {
  267. return "", errors.New("passwords do not match: try it again, but this time type slooowwwlly")
  268. }
  269. return string(password), nil
  270. }