auth.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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 *UserPlan
  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 UserPlan struct {
  61. Name string `json:"name"`
  62. MessagesLimit int `json:"messages_limit"`
  63. EmailsLimit int `json:"emails_limit"`
  64. AttachmentBytesLimit int64 `json:"attachment_bytes_limit"`
  65. }
  66. type UserSubscription struct {
  67. ID string `json:"id"`
  68. BaseURL string `json:"base_url"`
  69. Topic string `json:"topic"`
  70. }
  71. type UserNotificationPrefs struct {
  72. Sound string `json:"sound,omitempty"`
  73. MinPriority int `json:"min_priority,omitempty"`
  74. DeleteAfter int `json:"delete_after,omitempty"`
  75. }
  76. // Grant is a struct that represents an access control entry to a topic
  77. type Grant struct {
  78. TopicPattern string // May include wildcard (*)
  79. AllowRead bool
  80. AllowWrite bool
  81. }
  82. // Permission represents a read or write permission to a topic
  83. type Permission int
  84. // Permissions to a topic
  85. const (
  86. PermissionRead = Permission(1)
  87. PermissionWrite = Permission(2)
  88. )
  89. // Role represents a user's role, either admin or regular user
  90. type Role string
  91. // User roles
  92. const (
  93. RoleAdmin = Role("admin")
  94. RoleUser = Role("user")
  95. RoleAnonymous = Role("anonymous")
  96. )
  97. // Everyone is a special username representing anonymous users
  98. const (
  99. Everyone = "*"
  100. )
  101. var (
  102. allowedUsernameRegex = regexp.MustCompile(`^[-_.@a-zA-Z0-9]+$`) // Does not include Everyone (*)
  103. allowedTopicPatternRegex = regexp.MustCompile(`^[-_*A-Za-z0-9]{1,64}$`) // Adds '*' for wildcards!
  104. )
  105. // AllowedRole returns true if the given role can be used for new users
  106. func AllowedRole(role Role) bool {
  107. return role == RoleUser || role == RoleAdmin
  108. }
  109. // AllowedUsername returns true if the given username is valid
  110. func AllowedUsername(username string) bool {
  111. return allowedUsernameRegex.MatchString(username)
  112. }
  113. // AllowedTopicPattern returns true if the given topic pattern is valid; this includes the wildcard character (*)
  114. func AllowedTopicPattern(username string) bool {
  115. return allowedTopicPatternRegex.MatchString(username)
  116. }
  117. // Error constants used by the package
  118. var (
  119. ErrUnauthenticated = errors.New("unauthenticated")
  120. ErrUnauthorized = errors.New("unauthorized")
  121. ErrInvalidArgument = errors.New("invalid argument")
  122. ErrNotFound = errors.New("not found")
  123. )