auth.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package auth
  2. import "errors"
  3. // Auther is a generic interface to implement password-based authentication and authorization
  4. type Auther interface {
  5. Authenticate(user, pass string) (*User, error)
  6. Authorize(user *User, topic string, perm Permission) error
  7. }
  8. type Manager interface {
  9. AddUser(username, password string, role Role) error
  10. RemoveUser(username string) error
  11. Users() ([]*User, error)
  12. User(username string) (*User, error)
  13. ChangePassword(username, password string) error
  14. ChangeRole(username string, role Role) error
  15. DefaultAccess() (read bool, write bool)
  16. AllowAccess(username string, topic string, read bool, write bool) error
  17. ResetAccess(username string, topic string) error
  18. }
  19. type User struct {
  20. Name string
  21. Hash string // password hash (bcrypt)
  22. Role Role
  23. Grants []Grant
  24. }
  25. type Grant struct {
  26. Topic string
  27. Read bool
  28. Write bool
  29. }
  30. type Permission int
  31. const (
  32. PermissionRead = Permission(1)
  33. PermissionWrite = Permission(2)
  34. )
  35. type Role string
  36. const (
  37. RoleAdmin = Role("admin")
  38. RoleUser = Role("user")
  39. RoleAnonymous = Role("anonymous")
  40. )
  41. const (
  42. Everyone = "*"
  43. )
  44. func AllowedRole(role Role) bool {
  45. return role == RoleUser || role == RoleAdmin
  46. }
  47. var (
  48. ErrUnauthenticated = errors.New("unauthenticated")
  49. ErrUnauthorized = errors.New("unauthorized")
  50. ErrInvalidArgument = errors.New("invalid argument")
  51. ErrNotFound = errors.New("not found")
  52. )