types.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. Upgradable bool `json:"upgradable"`
  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. func NewPermission(read, write bool) Permission {
  96. p := uint8(0)
  97. if read {
  98. p |= uint8(PermissionRead)
  99. }
  100. if write {
  101. p |= uint8(PermissionWrite)
  102. }
  103. return Permission(p)
  104. }
  105. func ParsePermission(s string) (Permission, error) {
  106. switch s {
  107. case "read-write", "rw":
  108. return NewPermission(true, true), nil
  109. case "read-only", "read", "ro":
  110. return NewPermission(true, false), nil
  111. case "write-only", "write", "wo":
  112. return NewPermission(false, true), nil
  113. case "deny-all", "deny", "none":
  114. return NewPermission(false, false), nil
  115. default:
  116. return NewPermission(false, false), errors.New("invalid permission")
  117. }
  118. }
  119. func (p Permission) IsRead() bool {
  120. return p&PermissionRead != 0
  121. }
  122. func (p Permission) IsWrite() bool {
  123. return p&PermissionWrite != 0
  124. }
  125. func (p Permission) IsReadWrite() bool {
  126. return p.IsRead() && p.IsWrite()
  127. }
  128. func (p Permission) String() string {
  129. if p.IsReadWrite() {
  130. return "read-write"
  131. } else if p.IsRead() {
  132. return "read-only"
  133. } else if p.IsWrite() {
  134. return "write-only"
  135. }
  136. return "deny-all"
  137. }
  138. // Role represents a user's role, either admin or regular user
  139. type Role string
  140. // User roles
  141. const (
  142. RoleAdmin = Role("admin") // Some queries have these values hardcoded!
  143. RoleUser = Role("user")
  144. RoleAnonymous = Role("anonymous")
  145. )
  146. // Everyone is a special username representing anonymous users
  147. const (
  148. Everyone = "*"
  149. )
  150. var (
  151. allowedUsernameRegex = regexp.MustCompile(`^[-_.@a-zA-Z0-9]+$`) // Does not include Everyone (*)
  152. allowedTopicRegex = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) // No '*'
  153. allowedTopicPatternRegex = regexp.MustCompile(`^[-_*A-Za-z0-9]{1,64}$`) // Adds '*' for wildcards!
  154. )
  155. // AllowedRole returns true if the given role can be used for new users
  156. func AllowedRole(role Role) bool {
  157. return role == RoleUser || role == RoleAdmin
  158. }
  159. // AllowedUsername returns true if the given username is valid
  160. func AllowedUsername(username string) bool {
  161. return allowedUsernameRegex.MatchString(username)
  162. }
  163. // AllowedTopic returns true if the given topic name is valid
  164. func AllowedTopic(username string) bool {
  165. return allowedTopicRegex.MatchString(username)
  166. }
  167. // AllowedTopicPattern returns true if the given topic pattern is valid; this includes the wildcard character (*)
  168. func AllowedTopicPattern(username string) bool {
  169. return allowedTopicPatternRegex.MatchString(username)
  170. }
  171. // Error constants used by the package
  172. var (
  173. ErrUnauthenticated = errors.New("unauthenticated")
  174. ErrUnauthorized = errors.New("unauthorized")
  175. ErrInvalidArgument = errors.New("invalid argument")
  176. ErrNotFound = errors.New("not found")
  177. )