mirror of
https://github.com/goharbor/harbor.git
synced 2024-12-19 23:28:20 +01:00
feat(api,permission): add HasPermission, HasProjectPermission in BaseAPI (#10618)
Signed-off-by: He Weiwei <hweiwei@vmware.com>
This commit is contained in:
parent
b1437c1341
commit
791439086d
@ -20,6 +20,11 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/go-openapi/runtime/middleware"
|
"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"
|
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 {
|
func (*BaseAPI) SendError(ctx context.Context, err error) middleware.Responder {
|
||||||
return errs.NewErrResponder(err)
|
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)
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user