types.go 7.6 KB

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