auth.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. // Package auth deals with authentication and authorization against topics
  2. package auth
  3. import (
  4. "errors"
  5. "regexp"
  6. )
  7. // Manager is a generic interface to implement password and token based authentication and authorization
  8. type Manager interface {
  9. // Authenticate checks username and password and returns a user if correct. The method
  10. // returns in constant-ish time, regardless of whether the user exists or the password is
  11. // correct or incorrect.
  12. Authenticate(username, password string) (*User, error)
  13. AuthenticateToken(token string) (*User, error)
  14. CreateToken(user *User) (string, error)
  15. RemoveToken(user *User) error
  16. ChangeSettings(user *User) error
  17. // Authorize returns nil if the given user has access to the given topic using the desired
  18. // permission. The user param may be nil to signal an anonymous user.
  19. Authorize(user *User, topic string, perm Permission) error
  20. // AddUser adds a user with the given username, password and role. The password should be hashed
  21. // before it is stored in a persistence layer.
  22. AddUser(username, password string, role Role) error
  23. // RemoveUser deletes the user with the given username. The function returns nil on success, even
  24. // if the user did not exist in the first place.
  25. RemoveUser(username string) error
  26. // Users returns a list of users. It always also returns the Everyone user ("*").
  27. Users() ([]*User, error)
  28. // User returns the user with the given username if it exists, or ErrNotFound otherwise.
  29. // You may also pass Everyone to retrieve the anonymous user and its Grant list.
  30. User(username string) (*User, error)
  31. // ChangePassword changes a user's password
  32. ChangePassword(username, password string) error
  33. // ChangeRole changes a user's role. When a role is changed from RoleUser to RoleAdmin,
  34. // all existing access control entries (Grant) are removed, since they are no longer needed.
  35. ChangeRole(username string, role Role) error
  36. // AllowAccess adds or updates an entry in th access control list for a specific user. It controls
  37. // read/write access to a topic. The parameter topicPattern may include wildcards (*).
  38. AllowAccess(username string, topicPattern string, read bool, write bool) error
  39. // ResetAccess removes an access control list entry for a specific username/topic, or (if topic is
  40. // empty) for an entire user. The parameter topicPattern may include wildcards (*).
  41. ResetAccess(username string, topicPattern string) error
  42. // DefaultAccess returns the default read/write access if no access control entry matches
  43. DefaultAccess() (read bool, write bool)
  44. }
  45. // User is a struct that represents a user
  46. type User struct {
  47. Name string
  48. Hash string // password hash (bcrypt)
  49. Token string // Only set if token was used to log in
  50. Role Role
  51. Grants []Grant
  52. Prefs *UserPrefs
  53. Plan *Plan
  54. }
  55. type UserPrefs struct {
  56. Language string `json:"language,omitempty"`
  57. Notification *UserNotificationPrefs `json:"notification,omitempty"`
  58. Subscriptions []*UserSubscription `json:"subscriptions,omitempty"`
  59. }
  60. type PlanCode string
  61. const (
  62. PlanUnlimited = PlanCode("unlimited")
  63. PlanDefault = PlanCode("default")
  64. PlanNone = PlanCode("none")
  65. )
  66. type Plan struct {
  67. Code string `json:"name"`
  68. Upgradable bool `json:"upgradable"`
  69. MessagesLimit int64 `json:"messages_limit"`
  70. EmailsLimit int64 `json:"emails_limit"`
  71. AttachmentFileSizeLimit int64 `json:"attachment_file_size_limit"`
  72. AttachmentTotalSizeLimit int64 `json:"attachment_total_size_limit"`
  73. }
  74. type UserSubscription struct {
  75. ID string `json:"id"`
  76. BaseURL string `json:"base_url"`
  77. Topic string `json:"topic"`
  78. }
  79. type UserNotificationPrefs struct {
  80. Sound string `json:"sound,omitempty"`
  81. MinPriority int `json:"min_priority,omitempty"`
  82. DeleteAfter int `json:"delete_after,omitempty"`
  83. }
  84. // Grant is a struct that represents an access control entry to a topic
  85. type Grant struct {
  86. TopicPattern string // May include wildcard (*)
  87. AllowRead bool
  88. AllowWrite bool
  89. }
  90. // Permission represents a read or write permission to a topic
  91. type Permission int
  92. // Permissions to a topic
  93. const (
  94. PermissionRead = Permission(1)
  95. PermissionWrite = Permission(2)
  96. )
  97. // Role represents a user's role, either admin or regular user
  98. type Role string
  99. // User roles
  100. const (
  101. RoleAdmin = Role("admin")
  102. RoleUser = Role("user")
  103. RoleAnonymous = Role("anonymous")
  104. )
  105. // Everyone is a special username representing anonymous users
  106. const (
  107. Everyone = "*"
  108. )
  109. var (
  110. allowedUsernameRegex = regexp.MustCompile(`^[-_.@a-zA-Z0-9]+$`) // Does not include Everyone (*)
  111. allowedTopicPatternRegex = regexp.MustCompile(`^[-_*A-Za-z0-9]{1,64}$`) // Adds '*' for wildcards!
  112. )
  113. // AllowedRole returns true if the given role can be used for new users
  114. func AllowedRole(role Role) bool {
  115. return role == RoleUser || role == RoleAdmin
  116. }
  117. // AllowedUsername returns true if the given username is valid
  118. func AllowedUsername(username string) bool {
  119. return allowedUsernameRegex.MatchString(username)
  120. }
  121. // AllowedTopicPattern returns true if the given topic pattern is valid; this includes the wildcard character (*)
  122. func AllowedTopicPattern(username string) bool {
  123. return allowedTopicPatternRegex.MatchString(username)
  124. }
  125. // Error constants used by the package
  126. var (
  127. ErrUnauthenticated = errors.New("unauthenticated")
  128. ErrUnauthorized = errors.New("unauthorized")
  129. ErrInvalidArgument = errors.New("invalid argument")
  130. ErrNotFound = errors.New("not found")
  131. )