Files
bridge/internal/permissions/roles.go
2023-07-01 00:04:52 +00:00

83 lines
1.8 KiB
Go

package permissions
import (
"context"
"fmt"
"net/http"
"go.infratographer.com/x/gidx"
"golang.org/x/exp/slices"
)
type ResourceRoleCreate struct {
Actions []string `json:"actions"`
}
type ResourceRoleCreateResponse struct {
ID string `json:"id"`
}
type ResourceRoles []ResourceRole
type ResourceRole struct {
ID gidx.PrefixedID `json:"id"`
Actions []string `json:"actions"`
}
func (c *Client) CreateRole(ctx context.Context, resourceID gidx.PrefixedID, actions []string) (gidx.PrefixedID, error) {
path := fmt.Sprintf("/api/v1/resources/%s/roles", resourceID.String())
body, err := encodeJSON(ResourceRoleCreate{
Actions: actions,
})
if err != nil {
return gidx.NullPrefixedID, err
}
var response ResourceRoleCreateResponse
if _, err = c.DoRequest(ctx, http.MethodPost, path, body, &response); err != nil {
return gidx.NullPrefixedID, err
}
roleID, err := gidx.Parse(response.ID)
if err != nil {
return gidx.NullPrefixedID, err
}
return roleID, nil
}
func (c *Client) ListResourceRoles(ctx context.Context, resourceID gidx.PrefixedID) (ResourceRoles, error) {
path := fmt.Sprintf("/api/v1/resources/%s/roles", resourceID.String())
var response ResourceRoles
if _, err := c.DoRequest(ctx, http.MethodGet, path, nil, &response); err != nil {
return nil, err
}
return response, nil
}
func (c *Client) FindResourceRoleByActions(ctx context.Context, resourceID gidx.PrefixedID, actions []string) (ResourceRole, error) {
roles, err := c.ListResourceRoles(ctx, resourceID)
if err != nil {
return ResourceRole{}, err
}
slices.Sort(actions)
for _, role := range roles {
roleActions := role.Actions
slices.Sort(roleActions)
if slices.Equal(actions, roleActions) {
return role, nil
}
}
return ResourceRole{}, ErrRoleNotFound
}