Search in sources :

Example 16 with ResourceStore

use of org.keycloak.authorization.store.ResourceStore in project keycloak by keycloak.

the class JPAPermissionTicketStore method findGrantedResources.

@Override
public List<Resource> findGrantedResources(String requester, String name, int first, int max) {
    TypedQuery<String> query = name == null ? entityManager.createNamedQuery("findGrantedResources", String.class) : entityManager.createNamedQuery("findGrantedResourcesByName", String.class);
    query.setFlushMode(FlushModeType.COMMIT);
    query.setParameter("requester", requester);
    if (name != null) {
        query.setParameter("resourceName", "%" + name.toLowerCase() + "%");
    }
    List<String> result = paginateQuery(query, first, max).getResultList();
    List<Resource> list = new LinkedList<>();
    ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();
    for (String id : result) {
        Resource resource = resourceStore.findById(id, null);
        if (Objects.nonNull(resource)) {
            list.add(resource);
        }
    }
    return list;
}
Also used : Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore) LinkedList(java.util.LinkedList)

Example 17 with ResourceStore

use of org.keycloak.authorization.store.ResourceStore in project keycloak by keycloak.

the class JPAPermissionTicketStore method findGrantedOwnerResources.

@Override
public List<Resource> findGrantedOwnerResources(String owner, int first, int max) {
    TypedQuery<String> query = entityManager.createNamedQuery("findGrantedOwnerResources", String.class);
    query.setFlushMode(FlushModeType.COMMIT);
    query.setParameter("owner", owner);
    List<String> result = paginateQuery(query, first, max).getResultList();
    List<Resource> list = new LinkedList<>();
    ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();
    for (String id : result) {
        Resource resource = resourceStore.findById(id, null);
        if (Objects.nonNull(resource)) {
            list.add(resource);
        }
    }
    return list;
}
Also used : Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore) LinkedList(java.util.LinkedList)

Example 18 with ResourceStore

use of org.keycloak.authorization.store.ResourceStore in project keycloak by keycloak.

the class JPAResourceStore method findByResourceServer.

@Override
public List<Resource> findByResourceServer(Map<Resource.FilterOption, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ResourceEntity> querybuilder = builder.createQuery(ResourceEntity.class);
    Root<ResourceEntity> root = querybuilder.from(ResourceEntity.class);
    querybuilder.select(root.get("id"));
    List<Predicate> predicates = new ArrayList();
    if (resourceServerId != null) {
        predicates.add(builder.equal(root.get("resourceServer"), resourceServerId));
    }
    attributes.forEach((filterOption, value) -> {
        switch(filterOption) {
            case ID:
            case OWNER:
                predicates.add(root.get(filterOption.getName()).in(value));
                break;
            case SCOPE_ID:
                predicates.add(root.join("scopes").get("id").in(value));
                break;
            case OWNER_MANAGED_ACCESS:
                predicates.add(builder.equal(root.get(filterOption.getName()), Boolean.valueOf(value[0])));
                break;
            case URI:
                predicates.add(builder.lower(root.join("uris")).in(value[0].toLowerCase()));
                break;
            case URI_NOT_NULL:
                // predicates.add(builder.isNotEmpty(root.get("uris"))); looks like there is a bug in hibernate and this line doesn't work: https://hibernate.atlassian.net/browse/HHH-6686
                // Workaround
                Expression<Integer> urisSize = builder.size(root.get("uris"));
                predicates.add(builder.notEqual(urisSize, 0));
                break;
            case NAME:
            case TYPE:
                predicates.add(builder.like(builder.lower(root.get(filterOption.getName())), "%" + value[0].toLowerCase() + "%"));
                break;
            case EXACT_NAME:
                predicates.add(builder.equal(builder.lower(root.get(filterOption.getName())), value[0].toLowerCase()));
                break;
            default:
                throw new IllegalArgumentException("Unsupported filter [" + filterOption + "]");
        }
    });
    querybuilder.where(predicates.toArray(new Predicate[predicates.size()])).orderBy(builder.asc(root.get("name")));
    TypedQuery query = entityManager.createQuery(querybuilder);
    List<String> result = paginateQuery(query, firstResult, maxResult).getResultList();
    List<Resource> list = new LinkedList<>();
    ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();
    for (String id : result) {
        Resource resource = resourceStore.findById(id, resourceServerId);
        if (resource != null) {
            list.add(resource);
        }
    }
    return list;
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) TypedQuery(javax.persistence.TypedQuery) ArrayList(java.util.ArrayList) Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore) LinkedList(java.util.LinkedList) Predicate(javax.persistence.criteria.Predicate) ResourceEntity(org.keycloak.authorization.jpa.entities.ResourceEntity)

Example 19 with ResourceStore

use of org.keycloak.authorization.store.ResourceStore in project keycloak by keycloak.

the class JPAResourceStore method findByOwnerFilter.

private void findByOwnerFilter(String ownerId, String resourceServerId, Consumer<Resource> consumer, int firstResult, int maxResult) {
    boolean pagination = firstResult > -1 && maxResult > -1;
    String queryName = pagination ? "findResourceIdByOwnerOrdered" : "findResourceIdByOwner";
    if (resourceServerId == null) {
        queryName = pagination ? "findAnyResourceIdByOwnerOrdered" : "findAnyResourceIdByOwner";
    }
    TypedQuery<ResourceEntity> query = entityManager.createNamedQuery(queryName, ResourceEntity.class);
    query.setFlushMode(FlushModeType.COMMIT);
    query.setParameter("owner", ownerId);
    if (resourceServerId != null) {
        query.setParameter("serverId", resourceServerId);
    }
    if (pagination) {
        query.setFirstResult(firstResult);
        query.setMaxResults(maxResult);
    }
    ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();
    closing(query.getResultStream().map(id -> resourceStore.findById(id.getId(), resourceServerId))).forEach(consumer);
}
Also used : ResourceEntity(org.keycloak.authorization.jpa.entities.ResourceEntity) ResourceStore(org.keycloak.authorization.store.ResourceStore)

Example 20 with ResourceStore

use of org.keycloak.authorization.store.ResourceStore in project keycloak by keycloak.

the class ResourceSetService method getPermissions.

@Path("{id}/permissions")
@GET
@NoCache
@Produces("application/json")
public Response getPermissions(@PathParam("id") String id) {
    requireView();
    StoreFactory storeFactory = authorization.getStoreFactory();
    ResourceStore resourceStore = storeFactory.getResourceStore();
    Resource model = resourceStore.findById(id, resourceServer.getId());
    if (model == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    PolicyStore policyStore = authorization.getStoreFactory().getPolicyStore();
    Set<Policy> policies = new HashSet<>();
    policies.addAll(policyStore.findByResource(model.getId(), resourceServer.getId()));
    if (model.getType() != null) {
        policies.addAll(policyStore.findByResourceType(model.getType(), resourceServer.getId()));
        Map<Resource.FilterOption, String[]> resourceFilter = new EnumMap<>(Resource.FilterOption.class);
        resourceFilter.put(Resource.FilterOption.OWNER, new String[] { resourceServer.getId() });
        resourceFilter.put(Resource.FilterOption.TYPE, new String[] { model.getType() });
        for (Resource resourceType : resourceStore.findByResourceServer(resourceFilter, resourceServer.getId(), -1, -1)) {
            policies.addAll(policyStore.findByResource(resourceType.getId(), resourceServer.getId()));
        }
    }
    policies.addAll(policyStore.findByScopeIds(model.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toList()), id, resourceServer.getId()));
    policies.addAll(policyStore.findByScopeIds(model.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toList()), null, resourceServer.getId()));
    List<PolicyRepresentation> representation = new ArrayList<>();
    for (Policy policyModel : policies) {
        if (!"uma".equalsIgnoreCase(policyModel.getType())) {
            PolicyRepresentation policy = new PolicyRepresentation();
            policy.setId(policyModel.getId());
            policy.setName(policyModel.getName());
            policy.setType(policyModel.getType());
            if (!representation.contains(policy)) {
                representation.add(policy);
            }
        }
    }
    return Response.ok(representation).build();
}
Also used : Policy(org.keycloak.authorization.model.Policy) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) BiFunction(java.util.function.BiFunction) Path(javax.ws.rs.Path) OAuthErrorException(org.keycloak.OAuthErrorException) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ErrorResponseException(org.keycloak.services.ErrorResponseException) ModelToRepresentation.toRepresentation(org.keycloak.models.utils.ModelToRepresentation.toRepresentation) Map(java.util.Map) ResourceOwnerRepresentation(org.keycloak.representations.idm.authorization.ResourceOwnerRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) DELETE(javax.ws.rs.DELETE) RealmModel(org.keycloak.models.RealmModel) EnumMap(java.util.EnumMap) Collection(java.util.Collection) Set(java.util.Set) PolicyStore(org.keycloak.authorization.store.PolicyStore) ResourceStore(org.keycloak.authorization.store.ResourceStore) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) RepresentationToModel.toModel(org.keycloak.models.utils.RepresentationToModel.toModel) ClientModel(org.keycloak.models.ClientModel) OperationType(org.keycloak.events.admin.OperationType) PathParam(javax.ws.rs.PathParam) Scope(org.keycloak.authorization.model.Scope) GET(javax.ws.rs.GET) StoreFactory(org.keycloak.authorization.store.StoreFactory) Constants(org.keycloak.models.Constants) HashMap(java.util.HashMap) Function(java.util.function.Function) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) UserModel(org.keycloak.models.UserModel) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) Status(javax.ws.rs.core.Response.Status) PathMatcher(org.keycloak.common.util.PathMatcher) ResourceServer(org.keycloak.authorization.model.ResourceServer) POST(javax.ws.rs.POST) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) Policy(org.keycloak.authorization.model.Policy) NoCache(org.jboss.resteasy.annotations.cache.NoCache) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) Resource(org.keycloak.authorization.model.Resource) AdminEventBuilder(org.keycloak.services.resources.admin.AdminEventBuilder) Resource(org.keycloak.authorization.model.Resource) ArrayList(java.util.ArrayList) ResourceStore(org.keycloak.authorization.store.ResourceStore) StoreFactory(org.keycloak.authorization.store.StoreFactory) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) PolicyStore(org.keycloak.authorization.store.PolicyStore) EnumMap(java.util.EnumMap) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Aggregations

ResourceStore (org.keycloak.authorization.store.ResourceStore)29 Resource (org.keycloak.authorization.model.Resource)22 StoreFactory (org.keycloak.authorization.store.StoreFactory)12 Scope (org.keycloak.authorization.model.Scope)11 ResourceServer (org.keycloak.authorization.model.ResourceServer)9 ArrayList (java.util.ArrayList)8 EnumMap (java.util.EnumMap)7 List (java.util.List)7 Map (java.util.Map)7 Set (java.util.Set)7 Policy (org.keycloak.authorization.model.Policy)7 UserModel (org.keycloak.models.UserModel)7 ErrorResponseException (org.keycloak.services.ErrorResponseException)7 HashMap (java.util.HashMap)6 LinkedList (java.util.LinkedList)6 Collectors (java.util.stream.Collectors)6 Produces (javax.ws.rs.Produces)6 AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)6 PermissionTicket (org.keycloak.authorization.model.PermissionTicket)6 PolicyStore (org.keycloak.authorization.store.PolicyStore)6