token.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. //go:build !noserver
  2. package cmd
  3. import (
  4. "errors"
  5. "fmt"
  6. "github.com/urfave/cli/v2"
  7. "heckel.io/ntfy/user"
  8. "heckel.io/ntfy/util"
  9. "net/netip"
  10. "time"
  11. )
  12. func init() {
  13. commands = append(commands, cmdToken)
  14. }
  15. var flagsToken = append([]cli.Flag{}, flagsUser...)
  16. var cmdToken = &cli.Command{
  17. Name: "token",
  18. Usage: "Create, list or delete user tokens",
  19. UsageText: "ntfy token [list|add|remove] ...",
  20. Flags: flagsToken,
  21. Before: initConfigFileInputSourceFunc("config", flagsToken, initLogFunc),
  22. Category: categoryServer,
  23. Subcommands: []*cli.Command{
  24. {
  25. Name: "add",
  26. Aliases: []string{"a"},
  27. Usage: "Create a new token",
  28. UsageText: "ntfy token add [--expires=<duration>] [--label=..] USERNAME",
  29. Action: execTokenAdd,
  30. Flags: []cli.Flag{
  31. &cli.StringFlag{Name: "expires", Aliases: []string{"e"}, Value: "", Usage: "token expires after"},
  32. &cli.StringFlag{Name: "label", Aliases: []string{"l"}, Value: "", Usage: "token label"},
  33. },
  34. Description: `Create a new user access token.
  35. User access tokens can be used to publish, subscribe, or perform any other user-specific tasks.
  36. Tokens have full access, and can perform any task a user can do. They are meant to be used to
  37. avoid spreading the password to various places.
  38. This is a server-only command. It directly reads from user.db as defined in the server config
  39. file server.yml. The command only works if 'auth-file' is properly defined.
  40. Examples:
  41. ntfy token add phil # Create token for user phil which never expires
  42. ntfy token add --expires=2d phil # Create token for user phil which expires in 2 days
  43. ntfy token add -e "tuesday, 8pm" phil # Create token for user phil which expires next Tuesday
  44. ntfy token add -l backups phil # Create token for user phil with label "backups"`,
  45. },
  46. {
  47. Name: "remove",
  48. Aliases: []string{"del", "rm"},
  49. Usage: "Removes a token",
  50. UsageText: "ntfy token remove USERNAME TOKEN",
  51. Action: execTokenDel,
  52. Description: `Remove a token from the ntfy user database.
  53. Example:
  54. ntfy token del phil tk_th2srHVlxrANQHAso5t0HuQ1J1TjN`,
  55. },
  56. {
  57. Name: "list",
  58. Aliases: []string{"l"},
  59. Usage: "Shows a list of tokens",
  60. Action: execTokenList,
  61. Description: `Shows a list of all tokens.
  62. This is a server-only command. It directly reads from user.db as defined in the server config
  63. file server.yml. The command only works if 'auth-file' is properly defined.`,
  64. },
  65. },
  66. Description: `Manage access tokens for individual users.
  67. User access tokens can be used to publish, subscribe, or perform any other user-specific tasks.
  68. Tokens have full access, and can perform any task a user can do. They are meant to be used to
  69. avoid spreading the password to various places.
  70. This is a server-only command. It directly manages the user.db as defined in the server config
  71. file server.yml. The command only works if 'auth-file' is properly defined.
  72. Examples:
  73. ntfy token list # Shows list of tokens for all users
  74. ntfy token list phil # Shows list of tokens for user phil
  75. ntfy token add phil # Create token for user phil which never expires
  76. ntfy token add --expires=2d phil # Create token for user phil which expires in 2 days
  77. ntfy token remove phil tk_th2srHVlxr... # Delete token`,
  78. }
  79. func execTokenAdd(c *cli.Context) error {
  80. username := c.Args().Get(0)
  81. expiresStr := c.String("expires")
  82. label := c.String("label")
  83. if username == "" {
  84. return errors.New("username expected, type 'ntfy token add --help' for help")
  85. } else if username == userEveryone || username == user.Everyone {
  86. return errors.New("username not allowed")
  87. }
  88. expires := time.Unix(0, 0)
  89. if expiresStr != "" {
  90. var err error
  91. expires, err = util.ParseFutureTime(expiresStr, time.Now())
  92. if err != nil {
  93. return err
  94. }
  95. }
  96. manager, err := createUserManager(c)
  97. if err != nil {
  98. return err
  99. }
  100. u, err := manager.User(username)
  101. if err == user.ErrUserNotFound {
  102. return fmt.Errorf("user %s does not exist", username)
  103. } else if err != nil {
  104. return err
  105. }
  106. token, err := manager.CreateToken(u.ID, label, expires, netip.IPv4Unspecified())
  107. if err != nil {
  108. return err
  109. }
  110. if expires.Unix() == 0 {
  111. fmt.Fprintf(c.App.ErrWriter, "token %s created for user %s, never expires\n", token.Value, u.Name)
  112. } else {
  113. fmt.Fprintf(c.App.ErrWriter, "token %s created for user %s, expires %v\n", token.Value, u.Name, expires.Format(time.UnixDate))
  114. }
  115. return nil
  116. }
  117. func execTokenDel(c *cli.Context) error {
  118. username, token := c.Args().Get(0), c.Args().Get(1)
  119. if username == "" || token == "" {
  120. return errors.New("username and token expected, type 'ntfy token remove --help' for help")
  121. } else if username == userEveryone || username == user.Everyone {
  122. return errors.New("username not allowed")
  123. }
  124. manager, err := createUserManager(c)
  125. if err != nil {
  126. return err
  127. }
  128. u, err := manager.User(username)
  129. if err == user.ErrUserNotFound {
  130. return fmt.Errorf("user %s does not exist", username)
  131. } else if err != nil {
  132. return err
  133. }
  134. if err := manager.RemoveToken(u.ID, token); err != nil {
  135. return err
  136. }
  137. fmt.Fprintf(c.App.ErrWriter, "token %s for user %s removed\n", token, username)
  138. return nil
  139. }
  140. func execTokenList(c *cli.Context) error {
  141. username := c.Args().Get(0)
  142. if username == userEveryone || username == user.Everyone {
  143. return errors.New("username not allowed")
  144. }
  145. manager, err := createUserManager(c)
  146. if err != nil {
  147. return err
  148. }
  149. var users []*user.User
  150. if username != "" {
  151. u, err := manager.User(username)
  152. if err == user.ErrUserNotFound {
  153. return fmt.Errorf("user %s does not exist", username)
  154. } else if err != nil {
  155. return err
  156. }
  157. users = append(users, u)
  158. } else {
  159. users, err = manager.Users()
  160. if err != nil {
  161. return err
  162. }
  163. }
  164. usersWithTokens := 0
  165. for _, u := range users {
  166. tokens, err := manager.Tokens(u.ID)
  167. if err != nil {
  168. return err
  169. } else if len(tokens) == 0 && username != "" {
  170. fmt.Fprintf(c.App.ErrWriter, "user %s has no access tokens\n", username)
  171. return nil
  172. } else if len(tokens) == 0 {
  173. continue
  174. }
  175. usersWithTokens++
  176. fmt.Fprintf(c.App.ErrWriter, "user %s\n", u.Name)
  177. for _, t := range tokens {
  178. var label, expires string
  179. if t.Label != "" {
  180. label = fmt.Sprintf(" (%s)", t.Label)
  181. }
  182. if t.Expires.Unix() == 0 {
  183. expires = "never expires"
  184. } else {
  185. expires = fmt.Sprintf("expires %s", t.Expires.Format(time.RFC822))
  186. }
  187. fmt.Fprintf(c.App.ErrWriter, "- %s%s, %s, accessed from %s at %s\n", t.Value, label, expires, t.LastOrigin.String(), t.LastAccess.Format(time.RFC822))
  188. }
  189. }
  190. if usersWithTokens == 0 {
  191. fmt.Fprintf(c.App.ErrWriter, "no users with tokens\n")
  192. }
  193. return nil
  194. }