types.go 8.6 KB

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