types.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package user
  2. import (
  3. "errors"
  4. "github.com/stripe/stripe-go/v74"
  5. "heckel.io/ntfy/log"
  6. "net/netip"
  7. "regexp"
  8. "time"
  9. )
  10. // User is a struct that represents a user
  11. type User struct {
  12. ID string
  13. Name string
  14. Hash string // password hash (bcrypt)
  15. Token string // Only set if token was used to log in
  16. Role Role
  17. Prefs *Prefs
  18. Tier *Tier
  19. Stats *Stats
  20. Billing *Billing
  21. SyncTopic string
  22. Deleted bool
  23. }
  24. // TierID returns the ID of the User.Tier, or an empty string if the user has no tier,
  25. // or if the user itself is nil.
  26. func (u *User) TierID() string {
  27. if u == nil || u.Tier == nil {
  28. return ""
  29. }
  30. return u.Tier.ID
  31. }
  32. // IsAdmin returns true if the user is an admin
  33. func (u *User) IsAdmin() bool {
  34. return u != nil && u.Role == RoleAdmin
  35. }
  36. // IsUser returns true if the user is a regular user, not an admin
  37. func (u *User) IsUser() bool {
  38. return u != nil && u.Role == RoleUser
  39. }
  40. // Auther is an interface for authentication and authorization
  41. type Auther interface {
  42. // Authenticate checks username and password and returns a user if correct. The method
  43. // returns in constant-ish time, regardless of whether the user exists or the password is
  44. // correct or incorrect.
  45. Authenticate(username, password string) (*User, error)
  46. // Authorize returns nil if the given user has access to the given topic using the desired
  47. // permission. The user param may be nil to signal an anonymous user.
  48. Authorize(user *User, topic string, perm Permission) error
  49. }
  50. // Token represents a user token, including expiry date
  51. type Token struct {
  52. Value string
  53. Label string
  54. LastAccess time.Time
  55. LastOrigin netip.Addr
  56. Expires time.Time
  57. }
  58. // TokenUpdate holds information about the last access time and origin IP address of a token
  59. type TokenUpdate struct {
  60. LastAccess time.Time
  61. LastOrigin netip.Addr
  62. }
  63. // Prefs represents a user's configuration settings
  64. type Prefs struct {
  65. Language *string `json:"language,omitempty"`
  66. Notification *NotificationPrefs `json:"notification,omitempty"`
  67. Subscriptions []*Subscription `json:"subscriptions,omitempty"`
  68. }
  69. // Tier represents a user's account type, including its account limits
  70. type Tier struct {
  71. ID string // Tier identifier (ti_...)
  72. Code string // Code of the tier
  73. Name string // Name of the tier
  74. MessageLimit int64 // Daily message limit
  75. MessageExpiryDuration time.Duration // Cache duration for messages
  76. EmailLimit int64 // Daily email limit
  77. ReservationLimit int64 // Number of topic reservations allowed by user
  78. AttachmentFileSizeLimit int64 // Max file size per file (bytes)
  79. AttachmentTotalSizeLimit int64 // Total file size for all files of this user (bytes)
  80. AttachmentExpiryDuration time.Duration // Duration after which attachments will be deleted
  81. AttachmentBandwidthLimit int64 // Daily bandwidth limit for the user
  82. StripePriceID string // Price ID for paid tiers (price_...)
  83. }
  84. // Context returns fields for the log
  85. func (t *Tier) Context() log.Context {
  86. return log.Context{
  87. "tier_id": t.ID,
  88. "tier_name": t.Name,
  89. "stripe_price_id": t.StripePriceID,
  90. }
  91. }
  92. // Subscription represents a user's topic subscription
  93. type Subscription struct {
  94. ID string `json:"id"`
  95. BaseURL string `json:"base_url"`
  96. Topic string `json:"topic"`
  97. DisplayName *string `json:"display_name"`
  98. }
  99. // NotificationPrefs represents the user's notification settings
  100. type NotificationPrefs struct {
  101. Sound *string `json:"sound,omitempty"`
  102. MinPriority *int `json:"min_priority,omitempty"`
  103. DeleteAfter *int `json:"delete_after,omitempty"`
  104. }
  105. // Stats is a struct holding daily user statistics
  106. type Stats struct {
  107. Messages int64
  108. Emails int64
  109. }
  110. // Billing is a struct holding a user's billing information
  111. type Billing struct {
  112. StripeCustomerID string
  113. StripeSubscriptionID string
  114. StripeSubscriptionStatus stripe.SubscriptionStatus
  115. StripeSubscriptionPaidUntil time.Time
  116. StripeSubscriptionCancelAt time.Time
  117. }
  118. // Grant is a struct that represents an access control entry to a topic by a user
  119. type Grant struct {
  120. TopicPattern string // May include wildcard (*)
  121. Allow Permission
  122. }
  123. // Reservation is a struct that represents the ownership over a topic by a user
  124. type Reservation struct {
  125. Topic string
  126. Owner Permission
  127. Everyone Permission
  128. }
  129. // Permission represents a read or write permission to a topic
  130. type Permission uint8
  131. // Permissions to a topic
  132. const (
  133. PermissionDenyAll Permission = iota
  134. PermissionRead
  135. PermissionWrite
  136. PermissionReadWrite // 3!
  137. )
  138. // NewPermission is a helper to create a Permission based on read/write bool values
  139. func NewPermission(read, write bool) Permission {
  140. p := uint8(0)
  141. if read {
  142. p |= uint8(PermissionRead)
  143. }
  144. if write {
  145. p |= uint8(PermissionWrite)
  146. }
  147. return Permission(p)
  148. }
  149. // ParsePermission parses the string representation and returns a Permission
  150. func ParsePermission(s string) (Permission, error) {
  151. switch s {
  152. case "read-write", "rw":
  153. return NewPermission(true, true), nil
  154. case "read-only", "read", "ro":
  155. return NewPermission(true, false), nil
  156. case "write-only", "write", "wo":
  157. return NewPermission(false, true), nil
  158. case "deny-all", "deny", "none":
  159. return NewPermission(false, false), nil
  160. default:
  161. return NewPermission(false, false), errors.New("invalid permission")
  162. }
  163. }
  164. // IsRead returns true if readable
  165. func (p Permission) IsRead() bool {
  166. return p&PermissionRead != 0
  167. }
  168. // IsWrite returns true if writable
  169. func (p Permission) IsWrite() bool {
  170. return p&PermissionWrite != 0
  171. }
  172. // IsReadWrite returns true if readable and writable
  173. func (p Permission) IsReadWrite() bool {
  174. return p.IsRead() && p.IsWrite()
  175. }
  176. // String returns a string representation of the permission
  177. func (p Permission) String() string {
  178. if p.IsReadWrite() {
  179. return "read-write"
  180. } else if p.IsRead() {
  181. return "read-only"
  182. } else if p.IsWrite() {
  183. return "write-only"
  184. }
  185. return "deny-all"
  186. }
  187. // Role represents a user's role, either admin or regular user
  188. type Role string
  189. // User roles
  190. const (
  191. RoleAdmin = Role("admin") // Some queries have these values hardcoded!
  192. RoleUser = Role("user")
  193. RoleAnonymous = Role("anonymous")
  194. )
  195. // Everyone is a special username representing anonymous users
  196. const (
  197. Everyone = "*"
  198. everyoneID = "u_everyone"
  199. )
  200. var (
  201. allowedUsernameRegex = regexp.MustCompile(`^[-_.@a-zA-Z0-9]+$`) // Does not include Everyone (*)
  202. allowedTopicRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) // No '*'
  203. allowedTopicPatternRegex = regexp.MustCompile(`^[-_*A-Za-z0-9]{1,64}$`) // Adds '*' for wildcards!
  204. allowedTierRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
  205. )
  206. // AllowedRole returns true if the given role can be used for new users
  207. func AllowedRole(role Role) bool {
  208. return role == RoleUser || role == RoleAdmin
  209. }
  210. // AllowedUsername returns true if the given username is valid
  211. func AllowedUsername(username string) bool {
  212. return allowedUsernameRegex.MatchString(username)
  213. }
  214. // AllowedTopic returns true if the given topic name is valid
  215. func AllowedTopic(topic string) bool {
  216. return allowedTopicRegex.MatchString(topic)
  217. }
  218. // AllowedTopicPattern returns true if the given topic pattern is valid; this includes the wildcard character (*)
  219. func AllowedTopicPattern(topic string) bool {
  220. return allowedTopicPatternRegex.MatchString(topic)
  221. }
  222. // AllowedTier returns true if the given tier name is valid
  223. func AllowedTier(tier string) bool {
  224. return allowedTierRegex.MatchString(tier)
  225. }
  226. // Error constants used by the package
  227. var (
  228. ErrUnauthenticated = errors.New("unauthenticated")
  229. ErrUnauthorized = errors.New("unauthorized")
  230. ErrInvalidArgument = errors.New("invalid argument")
  231. ErrUserNotFound = errors.New("user not found")
  232. ErrTierNotFound = errors.New("tier not found")
  233. ErrTokenNotFound = errors.New("token not found")
  234. ErrTooManyReservations = errors.New("new tier has lower reservation limit")
  235. )