types.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package user
  2. import (
  3. "errors"
  4. "github.com/stripe/stripe-go/v74"
  5. "heckel.io/ntfy/v2/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. CallLimit int64 // Daily phone call limit
  79. ReservationLimit int64 // Number of topic reservations allowed by user
  80. AttachmentFileSizeLimit int64 // Max file size per file (bytes)
  81. AttachmentTotalSizeLimit int64 // Total file size for all files of this user (bytes)
  82. AttachmentExpiryDuration time.Duration // Duration after which attachments will be deleted
  83. AttachmentBandwidthLimit int64 // Daily bandwidth limit for the user
  84. StripeMonthlyPriceID string // Monthly price ID for paid tiers (price_...)
  85. StripeYearlyPriceID string // Yearly price ID for paid tiers (price_...)
  86. }
  87. // Context returns fields for the log
  88. func (t *Tier) Context() log.Context {
  89. return log.Context{
  90. "tier_id": t.ID,
  91. "tier_code": t.Code,
  92. "stripe_monthly_price_id": t.StripeMonthlyPriceID,
  93. "stripe_yearly_price_id": t.StripeYearlyPriceID,
  94. }
  95. }
  96. // Subscription represents a user's topic subscription
  97. type Subscription struct {
  98. BaseURL string `json:"base_url"`
  99. Topic string `json:"topic"`
  100. DisplayName *string `json:"display_name"`
  101. }
  102. // Context returns fields for the log
  103. func (s *Subscription) Context() log.Context {
  104. return log.Context{
  105. "base_url": s.BaseURL,
  106. "topic": s.Topic,
  107. }
  108. }
  109. // NotificationPrefs represents the user's notification settings
  110. type NotificationPrefs struct {
  111. Sound *string `json:"sound,omitempty"`
  112. MinPriority *int `json:"min_priority,omitempty"`
  113. DeleteAfter *int `json:"delete_after,omitempty"`
  114. }
  115. // Stats is a struct holding daily user statistics
  116. type Stats struct {
  117. Messages int64
  118. Emails int64
  119. Calls int64
  120. }
  121. // Billing is a struct holding a user's billing information
  122. type Billing struct {
  123. StripeCustomerID string
  124. StripeSubscriptionID string
  125. StripeSubscriptionStatus stripe.SubscriptionStatus
  126. StripeSubscriptionInterval stripe.PriceRecurringInterval
  127. StripeSubscriptionPaidUntil time.Time
  128. StripeSubscriptionCancelAt time.Time
  129. }
  130. // Grant is a struct that represents an access control entry to a topic by a user
  131. type Grant struct {
  132. TopicPattern string // May include wildcard (*)
  133. Allow Permission
  134. }
  135. // Reservation is a struct that represents the ownership over a topic by a user
  136. type Reservation struct {
  137. Topic string
  138. Owner Permission
  139. Everyone Permission
  140. }
  141. // Permission represents a read or write permission to a topic
  142. type Permission uint8
  143. // Permissions to a topic
  144. const (
  145. PermissionDenyAll Permission = iota
  146. PermissionRead
  147. PermissionWrite
  148. PermissionReadWrite // 3!
  149. )
  150. // NewPermission is a helper to create a Permission based on read/write bool values
  151. func NewPermission(read, write bool) Permission {
  152. p := uint8(0)
  153. if read {
  154. p |= uint8(PermissionRead)
  155. }
  156. if write {
  157. p |= uint8(PermissionWrite)
  158. }
  159. return Permission(p)
  160. }
  161. // ParsePermission parses the string representation and returns a Permission
  162. func ParsePermission(s string) (Permission, error) {
  163. switch strings.ToLower(s) {
  164. case "read-write", "rw":
  165. return NewPermission(true, true), nil
  166. case "read-only", "read", "ro":
  167. return NewPermission(true, false), nil
  168. case "write-only", "write", "wo":
  169. return NewPermission(false, true), nil
  170. case "deny-all", "deny", "none":
  171. return NewPermission(false, false), nil
  172. default:
  173. return NewPermission(false, false), errors.New("invalid permission")
  174. }
  175. }
  176. // IsRead returns true if readable
  177. func (p Permission) IsRead() bool {
  178. return p&PermissionRead != 0
  179. }
  180. // IsWrite returns true if writable
  181. func (p Permission) IsWrite() bool {
  182. return p&PermissionWrite != 0
  183. }
  184. // IsReadWrite returns true if readable and writable
  185. func (p Permission) IsReadWrite() bool {
  186. return p.IsRead() && p.IsWrite()
  187. }
  188. // String returns a string representation of the permission
  189. func (p Permission) String() string {
  190. if p.IsReadWrite() {
  191. return "read-write"
  192. } else if p.IsRead() {
  193. return "read-only"
  194. } else if p.IsWrite() {
  195. return "write-only"
  196. }
  197. return "deny-all"
  198. }
  199. // Role represents a user's role, either admin or regular user
  200. type Role string
  201. // User roles
  202. const (
  203. RoleAdmin = Role("admin") // Some queries have these values hardcoded!
  204. RoleUser = Role("user")
  205. RoleAnonymous = Role("anonymous")
  206. )
  207. // Everyone is a special username representing anonymous users
  208. const (
  209. Everyone = "*"
  210. everyoneID = "u_everyone"
  211. )
  212. var (
  213. allowedUsernameRegex = regexp.MustCompile(`^[-_.@a-zA-Z0-9]+$`) // Does not include Everyone (*)
  214. allowedTopicRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) // No '*'
  215. allowedTopicPatternRegex = regexp.MustCompile(`^[-_*A-Za-z0-9]{1,64}$`) // Adds '*' for wildcards!
  216. allowedTierRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
  217. )
  218. // AllowedRole returns true if the given role can be used for new users
  219. func AllowedRole(role Role) bool {
  220. return role == RoleUser || role == RoleAdmin
  221. }
  222. // AllowedUsername returns true if the given username is valid
  223. func AllowedUsername(username string) bool {
  224. return allowedUsernameRegex.MatchString(username)
  225. }
  226. // AllowedTopic returns true if the given topic name is valid
  227. func AllowedTopic(topic string) bool {
  228. return allowedTopicRegex.MatchString(topic)
  229. }
  230. // AllowedTopicPattern returns true if the given topic pattern is valid; this includes the wildcard character (*)
  231. func AllowedTopicPattern(topic string) bool {
  232. return allowedTopicPatternRegex.MatchString(topic)
  233. }
  234. // AllowedTier returns true if the given tier name is valid
  235. func AllowedTier(tier string) bool {
  236. return allowedTierRegex.MatchString(tier)
  237. }
  238. // Error constants used by the package
  239. var (
  240. ErrUnauthenticated = errors.New("unauthenticated")
  241. ErrUnauthorized = errors.New("unauthorized")
  242. ErrInvalidArgument = errors.New("invalid argument")
  243. ErrUserNotFound = errors.New("user not found")
  244. ErrUserExists = errors.New("user already exists")
  245. ErrTierNotFound = errors.New("tier not found")
  246. ErrTokenNotFound = errors.New("token not found")
  247. ErrPhoneNumberNotFound = errors.New("phone number not found")
  248. ErrTooManyReservations = errors.New("new tier has lower reservation limit")
  249. ErrPhoneNumberExists = errors.New("phone number already exists")
  250. )