auth.go 5.0 KB

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