types.go 8.4 KB

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