types.go 7.3 KB

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