2022-01-23 06:02:16 +01:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import "errors"
|
|
|
|
|
2022-01-23 06:54:18 +01:00
|
|
|
// Auther is a generic interface to implement password-based authentication and authorization
|
|
|
|
type Auther interface {
|
2022-01-23 06:02:16 +01:00
|
|
|
Authenticate(user, pass string) (*User, error)
|
|
|
|
Authorize(user *User, topic string, perm Permission) error
|
|
|
|
}
|
|
|
|
|
2022-01-23 06:54:18 +01:00
|
|
|
type Manager interface {
|
|
|
|
AddUser(username, password string, role Role) error
|
|
|
|
RemoveUser(username string) error
|
2022-01-24 05:02:39 +01:00
|
|
|
Users() ([]*User, error)
|
|
|
|
User(username string) (*User, error)
|
2022-01-23 06:54:18 +01:00
|
|
|
ChangePassword(username, password string) error
|
2022-01-23 21:30:30 +01:00
|
|
|
ChangeRole(username string, role Role) error
|
2022-01-24 06:54:28 +01:00
|
|
|
DefaultAccess() (read bool, write bool)
|
2022-01-23 21:30:30 +01:00
|
|
|
AllowAccess(username string, topic string, read bool, write bool) error
|
|
|
|
ResetAccess(username string, topic string) error
|
2022-01-23 06:54:18 +01:00
|
|
|
}
|
|
|
|
|
2022-01-23 06:02:16 +01:00
|
|
|
type User struct {
|
2022-01-24 05:02:39 +01:00
|
|
|
Name string
|
2022-01-26 03:57:28 +01:00
|
|
|
Hash string // password hash (bcrypt)
|
2022-01-24 05:02:39 +01:00
|
|
|
Role Role
|
|
|
|
Grants []Grant
|
|
|
|
}
|
|
|
|
|
|
|
|
type Grant struct {
|
|
|
|
Topic string
|
|
|
|
Read bool
|
|
|
|
Write bool
|
2022-01-23 06:02:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type Permission int
|
|
|
|
|
|
|
|
const (
|
|
|
|
PermissionRead = Permission(1)
|
|
|
|
PermissionWrite = Permission(2)
|
|
|
|
)
|
|
|
|
|
|
|
|
type Role string
|
|
|
|
|
|
|
|
const (
|
2022-01-24 06:54:28 +01:00
|
|
|
RoleAdmin = Role("admin")
|
|
|
|
RoleUser = Role("user")
|
|
|
|
RoleAnonymous = Role("anonymous")
|
2022-01-23 06:02:16 +01:00
|
|
|
)
|
|
|
|
|
2022-01-24 06:54:28 +01:00
|
|
|
const (
|
|
|
|
Everyone = "*"
|
|
|
|
)
|
2022-01-23 21:30:30 +01:00
|
|
|
|
|
|
|
func AllowedRole(role Role) bool {
|
|
|
|
return role == RoleUser || role == RoleAdmin
|
|
|
|
}
|
|
|
|
|
2022-01-24 05:02:39 +01:00
|
|
|
var (
|
2022-01-26 03:57:28 +01:00
|
|
|
ErrUnauthenticated = errors.New("unauthenticated")
|
|
|
|
ErrUnauthorized = errors.New("unauthorized")
|
|
|
|
ErrInvalidArgument = errors.New("invalid argument")
|
|
|
|
ErrNotFound = errors.New("not found")
|
2022-01-24 05:02:39 +01:00
|
|
|
)
|