feat(api,permission): add HasPermission, HasProjectPermission in BaseAPI (#10618)

Signed-off-by: He Weiwei <hweiwei@vmware.com>
This commit is contained in:
He Weiwei 2020-02-04 08:42:00 +08:00 committed by GitHub
parent b1437c1341
commit 791439086d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -20,6 +20,11 @@ import (
"context"
"github.com/go-openapi/runtime/middleware"
"github.com/goharbor/harbor/src/common/rbac"
"github.com/goharbor/harbor/src/common/security"
"github.com/goharbor/harbor/src/common/utils"
"github.com/goharbor/harbor/src/common/utils/log"
"github.com/goharbor/harbor/src/pkg/project"
errs "github.com/goharbor/harbor/src/server/error"
)
@ -35,3 +40,40 @@ func (*BaseAPI) Prepare(ctx context.Context, operation string, params interface{
func (*BaseAPI) SendError(ctx context.Context, err error) middleware.Responder {
return errs.NewErrResponder(err)
}
// HasPermission returns true when the request has action permission on resource
func (*BaseAPI) HasPermission(ctx context.Context, action rbac.Action, resource rbac.Resource) bool {
s, ok := security.FromContext(ctx)
if !ok {
log.Warningf("security not found in the contxt")
return false
}
return s.Can(action, resource)
}
// HasProjectPermission returns true when the request has action permission on project subresource
func (b *BaseAPI) HasProjectPermission(ctx context.Context, projectIDOrName interface{}, action rbac.Action, subresource ...rbac.Resource) bool {
projectID, projectName, err := utils.ParseProjectIDOrName(projectIDOrName)
if err != nil {
return false
}
if projectName != "" {
// TODO: use the project controller to replace the project manager
p, err := project.Mgr.Get(projectName)
if err != nil {
log.Errorf("failed to get project %s: %v", projectName, err)
return false
}
if p == nil {
log.Warningf("project %s not found", projectName)
return false
}
projectID = p.ProjectID
}
resource := rbac.NewProjectNamespace(projectID).Resource(subresource...)
return b.HasPermission(ctx, action, resource)
}