types.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. // Package user deals with authentication and authorization against topics
  2. package user
  3. import (
  4. "errors"
  5. "regexp"
  6. "time"
  7. )
  8. // User is a struct that represents a user
  9. type User struct {
  10. Name string
  11. Hash string // password hash (bcrypt)
  12. Token string // Only set if token was used to log in
  13. Role Role
  14. Prefs *Prefs
  15. Plan *Plan
  16. Stats *Stats
  17. }
  18. // Auther is an interface for authentication and authorization
  19. type Auther interface {
  20. // Authenticate checks username and password and returns a user if correct. The method
  21. // returns in constant-ish time, regardless of whether the user exists or the password is
  22. // correct or incorrect.
  23. Authenticate(username, password string) (*User, error)
  24. // Authorize returns nil if the given user has access to the given topic using the desired
  25. // permission. The user param may be nil to signal an anonymous user.
  26. Authorize(user *User, topic string, perm Permission) error
  27. }
  28. // Token represents a user token, including expiry date
  29. type Token struct {
  30. Value string
  31. Expires time.Time
  32. }
  33. // Prefs represents a user's configuration settings
  34. type Prefs struct {
  35. Language string `json:"language,omitempty"`
  36. Notification *NotificationPrefs `json:"notification,omitempty"`
  37. Subscriptions []*Subscription `json:"subscriptions,omitempty"`
  38. }
  39. // PlanCode is code identifying a user's plan
  40. type PlanCode string
  41. // Default plan codes
  42. const (
  43. PlanUnlimited = PlanCode("unlimited")
  44. PlanDefault = PlanCode("default")
  45. PlanNone = PlanCode("none")
  46. )
  47. // Plan represents a user's account type, including its account limits
  48. type Plan struct {
  49. Code string `json:"name"`
  50. Upgradeable bool `json:"upgradeable"`
  51. MessagesLimit int64 `json:"messages_limit"`
  52. EmailsLimit int64 `json:"emails_limit"`
  53. TopicsLimit int64 `json:"topics_limit"`
  54. AttachmentFileSizeLimit int64 `json:"attachment_file_size_limit"`
  55. AttachmentTotalSizeLimit int64 `json:"attachment_total_size_limit"`
  56. }
  57. // Subscription represents a user's topic subscription
  58. type Subscription struct {
  59. ID string `json:"id"`
  60. BaseURL string `json:"base_url"`
  61. Topic string `json:"topic"`
  62. DisplayName string `json:"display_name"`
  63. }
  64. // NotificationPrefs represents the user's notification settings
  65. type NotificationPrefs struct {
  66. Sound string `json:"sound,omitempty"`
  67. MinPriority int `json:"min_priority,omitempty"`
  68. DeleteAfter int `json:"delete_after,omitempty"`
  69. }
  70. // Stats is a struct holding daily user statistics
  71. type Stats struct {
  72. Messages int64
  73. Emails int64
  74. }
  75. // Grant is a struct that represents an access control entry to a topic by a user
  76. type Grant struct {
  77. TopicPattern string // May include wildcard (*)
  78. Allow Permission
  79. }
  80. // Reservation is a struct that represents the ownership over a topic by a user
  81. type Reservation struct {
  82. Topic string
  83. Owner Permission
  84. Everyone Permission
  85. }
  86. // Permission represents a read or write permission to a topic
  87. type Permission uint8
  88. // Permissions to a topic
  89. const (
  90. PermissionDenyAll Permission = iota
  91. PermissionRead
  92. PermissionWrite
  93. PermissionReadWrite // 3!
  94. )
  95. // NewPermission is a helper to create a Permission based on read/write bool values
  96. func NewPermission(read, write bool) Permission {
  97. p := uint8(0)
  98. if read {
  99. p |= uint8(PermissionRead)
  100. }
  101. if write {
  102. p |= uint8(PermissionWrite)
  103. }
  104. return Permission(p)
  105. }
  106. // ParsePermission parses the string representation and returns a Permission
  107. func ParsePermission(s string) (Permission, error) {
  108. switch s {
  109. case "read-write", "rw":
  110. return NewPermission(true, true), nil
  111. case "read-only", "read", "ro":
  112. return NewPermission(true, false), nil
  113. case "write-only", "write", "wo":
  114. return NewPermission(false, true), nil
  115. case "deny-all", "deny", "none":
  116. return NewPermission(false, false), nil
  117. default:
  118. return NewPermission(false, false), errors.New("invalid permission")
  119. }
  120. }
  121. // IsRead returns true if readable
  122. func (p Permission) IsRead() bool {
  123. return p&PermissionRead != 0
  124. }
  125. // IsWrite returns true if writable
  126. func (p Permission) IsWrite() bool {
  127. return p&PermissionWrite != 0
  128. }
  129. // IsReadWrite returns true if readable and writable
  130. func (p Permission) IsReadWrite() bool {
  131. return p.IsRead() && p.IsWrite()
  132. }
  133. // String returns a string representation of the permission
  134. func (p Permission) String() string {
  135. if p.IsReadWrite() {
  136. return "read-write"
  137. } else if p.IsRead() {
  138. return "read-only"
  139. } else if p.IsWrite() {
  140. return "write-only"
  141. }
  142. return "deny-all"
  143. }
  144. // Role represents a user's role, either admin or regular user
  145. type Role string
  146. // User roles
  147. const (
  148. RoleAdmin = Role("admin") // Some queries have these values hardcoded!
  149. RoleUser = Role("user")
  150. RoleAnonymous = Role("anonymous")
  151. )
  152. // Everyone is a special username representing anonymous users
  153. const (
  154. Everyone = "*"
  155. )
  156. var (
  157. allowedUsernameRegex = regexp.MustCompile(`^[-_.@a-zA-Z0-9]+$`) // Does not include Everyone (*)
  158. allowedTopicRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) // No '*'
  159. allowedTopicPatternRegex = regexp.MustCompile(`^[-_*A-Za-z0-9]{1,64}$`) // Adds '*' for wildcards!
  160. )
  161. // AllowedRole returns true if the given role can be used for new users
  162. func AllowedRole(role Role) bool {
  163. return role == RoleUser || role == RoleAdmin
  164. }
  165. // AllowedUsername returns true if the given username is valid
  166. func AllowedUsername(username string) bool {
  167. return allowedUsernameRegex.MatchString(username)
  168. }
  169. // AllowedTopic returns true if the given topic name is valid
  170. func AllowedTopic(username string) bool {
  171. return allowedTopicRegex.MatchString(username)
  172. }
  173. // AllowedTopicPattern returns true if the given topic pattern is valid; this includes the wildcard character (*)
  174. func AllowedTopicPattern(username string) bool {
  175. return allowedTopicPatternRegex.MatchString(username)
  176. }
  177. // Error constants used by the package
  178. var (
  179. ErrUnauthenticated = errors.New("unauthenticated")
  180. ErrUnauthorized = errors.New("unauthorized")
  181. ErrInvalidArgument = errors.New("invalid argument")
  182. ErrNotFound = errors.New("not found")
  183. )