Files
RenewCMS/api/pkg/access/access.go
T

35 lines
836 B
Go

package access
import (
"RenewCMS/api/pkg/apperr"
"RenewCMS/internal/domain/role"
"context"
"errors"
"net/http"
)
type grantsContextKey struct{}
func NewContext(ctx context.Context, grants role.GrantSet) context.Context {
return context.WithValue(ctx, grantsContextKey{}, grants)
}
func Grants(r *http.Request) role.GrantSet {
grants, _ := r.Context().Value(grantsContextKey{}).(role.GrantSet)
return grants
}
func WriteMissingPermission(w http.ResponseWriter, key string) {
w.Header().Set(apperr.MissingPermissionHeader, key)
http.Error(w, apperr.MissingPermissionErrorMessage, http.StatusForbidden)
}
func WriteIfMissingPermission(w http.ResponseWriter, err error) bool {
var missing role.MissingPermissionError
if !errors.As(err, &missing) {
return false
}
WriteMissingPermission(w, missing.Key)
return true
}