|
package permission |
|
|
|
import "github.com/pkg/errors" |
|
|
|
|
|
|
|
type Error interface { |
|
error |
|
Permission() bool |
|
Unauthorized() bool |
|
} |
|
type genericError struct { |
|
unauthorized bool |
|
reason string |
|
stack errors.StackTrace |
|
} |
|
|
|
type stackTracer interface { |
|
StackTrace() errors.StackTrace |
|
} |
|
|
|
func newGeneric(unauth bool, reason string) genericError { |
|
return genericError{ |
|
unauthorized: unauth, |
|
reason: reason, |
|
stack: errors.New("").(stackTracer).StackTrace()[1:], |
|
} |
|
} |
|
|
|
|
|
func NewAccessDenied(reason string) error { |
|
return newGeneric(false, reason) |
|
} |
|
|
|
|
|
func Unauthorized() error { |
|
return newGeneric(true, "") |
|
} |
|
|
|
func (e genericError) ClientError() bool { return true } |
|
|
|
func (e genericError) Permission() bool { return true } |
|
func (e genericError) Unauthorized() bool { return e.unauthorized } |
|
func (e genericError) Error() string { |
|
prefix := "access denied" |
|
if e.unauthorized { |
|
prefix = "unauthorized" |
|
} |
|
if e.reason == "" { |
|
return prefix |
|
} |
|
|
|
return prefix + ": " + e.reason |
|
} |
|
|
|
|
|
func IsPermissionError(err error) bool { |
|
var e Error |
|
if errors.As(err, &e) && e.Permission() { |
|
return true |
|
} |
|
return false |
|
} |
|
|
|
|
|
func IsUnauthorized(err error) bool { |
|
var e Error |
|
if errors.As(err, &e) && e.Permission() && e.Unauthorized() { |
|
return true |
|
} |
|
return false |
|
} |
|
|