auth.go 4.9 KB

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