Skip to content

Commit

Permalink
Better handling for maps including the ability to wrap the Map.Entry …
Browse files Browse the repository at this point in the history
…classes to control the naming of the key and value GraphQL fields.

Added the GraphQLOverrideName annotation that tells our custom TypeInfoGenerator to not append 'Input' and 'Scalar' to InputTypes and Scalar types respectively.
  • Loading branch information
blevine committed Oct 5, 2024
1 parent 7bc60db commit 366f0a7
Show file tree
Hide file tree
Showing 22 changed files with 1,039 additions and 102 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import net.brianlevine.keycloak.graphql.queries.ErrorQuery;
import net.brianlevine.keycloak.graphql.queries.RealmQuery;
import net.brianlevine.keycloak.graphql.queries.UserQuery;

import net.brianlevine.keycloak.graphql.util.OverrideTypeInfoGenerator;
import org.keycloak.models.KeycloakSession;

import java.util.Collections;
Expand All @@ -20,27 +22,35 @@

public class GraphQLController {

private final GraphQL graphQL;
private GraphQL graphQL;

// TODO: Maybe call initialization from the REST provider factory
public GraphQLController() {
RealmQuery realmQuery = new RealmQuery();
ErrorQuery errorQuery = new ErrorQuery();
UserQuery userQuery = new UserQuery();

//Schema generated from query classes
GraphQLSchema schema = new GraphQLSchemaGenerator()
.withBasePackages(
"net.brianlevine.keycloak.graphql"
)
.withOperationsFromSingletons(realmQuery, errorQuery, userQuery)
.withRelayConnectionCheckRelaxed()
.generate();

graphQL = GraphQLRuntime
.newGraphQL(schema)
.defaultDataFetcherExceptionHandler(new KeycloakGraphQLDataFetcherExceptionHandler())
.build();
}

private GraphQL getSchema() {

if (graphQL == null) {
RealmQuery realmQuery = new RealmQuery();
ErrorQuery errorQuery = new ErrorQuery();
UserQuery userQuery = new UserQuery();

//Schema generated from query classes
GraphQLSchema schema = new GraphQLSchemaGenerator()
.withBasePackages("net.brianlevine.keycloak.graphql")
.withOperationsFromSingletons(realmQuery, errorQuery, userQuery)
.withRelayConnectionCheckRelaxed()
.withTypeInfoGenerator(new OverrideTypeInfoGenerator().withHierarchicalNames(false))
.generate();

graphQL = GraphQLRuntime
.newGraphQL(schema)
.defaultDataFetcherExceptionHandler(new KeycloakGraphQLDataFetcherExceptionHandler())
.build();

}


return graphQL;
}

public Map<String, Object> executeQuery(String query, String operationName, KeycloakSession session, Request request, HttpHeaders headers, Map<String, Object> variables) {
Expand All @@ -49,7 +59,7 @@ public Map<String, Object> executeQuery(String query, String operationName, Keyc
ctx.put("request", request);
ctx.put("headers", headers);

ExecutionResult executionResult = graphQL.execute(ExecutionInput.newExecutionInput()
ExecutionResult executionResult = getSchema().execute(ExecutionInput.newExecutionInput()
.query(query)
.operationName(operationName)
.variables(variables)
Expand All @@ -70,6 +80,6 @@ public String printSchema() {
.includeScalarTypes(true)
.includeSchemaDefinition(true)
.includeIntrospectionTypes(true)
).print(graphQL.getGraphQLSchema());
).print(getSchema().getGraphQLSchema());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package net.brianlevine.keycloak.graphql.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* TBD: Notional. Maybe use this to change the field names for Map.Entry objects.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface GraphQLMapAlias {
String keyAlias() default "";
String valueAlias() default "";
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package net.brianlevine.keycloak.graphql.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* For InputTypes and Scalars. Classes annotated with GraphQLOverrideTypeName will not have a suffix ('Input' for
* InputTypes and 'Scalar' for Scalar types) appended.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface GraphQLOverrideTypeName {
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,8 @@
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.protocol.oidc.TokenManager;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.services.resources.admin.AdminAuth;
import org.keycloak.services.resources.admin.RealmsAdminResource;
import org.keycloak.services.resources.admin.permissions.AdminPermissions;


Expand All @@ -37,18 +35,16 @@ public Page<RealmType> getRealms(
AdminAuth auth = Auth.authenticateRealmAdminRequest(session, headers);
Page<RealmType> ret;


// TODO: If we use ExportUtils.exportRealm() we could get more realm information into the realm
// representation. If we do that, we might want to look at the GraphQL query to set the
// ExportOptions. OR, maybe we just want to have our own version of exportRealm() with even finer-
// grained options based on what fields were requested in the GraphQL query

RealmsAdminResource rar = new RealmsAdminResource(session, auth, new TokenManager());
try {
List<RealmRepresentation> realms = rar.getRealms(false).toList();
List<RealmType> realmTypes = realms.stream().map(rep -> rep != null ? new RealmType(session, rep) : null)
List<RealmRepresentation> realms = session.realms().getRealmsStream()
.map(realm -> toRealmRep(session, auth, realm))
.filter(Objects::nonNull)
.toList();

List<RealmType> realmTypes = realms.stream()
.map(rep -> rep != null ? new RealmType(session, rep) : null)
.toList();

ret = new Page<>(realms.size(), limit, realmTypes);
} catch (ForbiddenException e) {
ret = Page.emptyPage();
Expand Down Expand Up @@ -102,7 +98,11 @@ private RealmType toRealmType(KeycloakSession session, RealmModel realm, AdminAu
*/
protected RealmRepresentation toRealmRep(KeycloakSession session, AdminAuth auth, RealmModel realm) {
if (AdminPermissions.realms(session, auth).canView(realm)) {
return ModelToRepresentation.toRepresentation(session, realm, false);
// TODO: Choice of adding additional fields to RealmRepresentation by setting export and internal
// arguments. Setting both to true gets us the most fields. Is this OK?
final boolean internal = true;
final boolean export = true;
return ModelToRepresentation.toRepresentation(session, realm, internal, export);
} else if (AdminPermissions.realms(session, auth).isAdmin(realm)) {
RealmRepresentation rep = new RealmRepresentation();
rep.setRealm(realm.getName());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package net.brianlevine.keycloak.graphql.types;

import net.brianlevine.keycloak.graphql.util.PagedMap;

import java.util.Map;

public class AttributeMap extends PagedMap<String, String, AttributeMap.Entry> {

public AttributeMap(Map<String, String> map, int start, int limit) {
super(map, start, limit, AttributeMap.Entry.class);
}

public static class Entry extends PagedMap.DelegatingEntry<String, String> implements Map.Entry<String, String> {
public Entry(Map.Entry<String, String> delegate) {
super(delegate);
}

public String getName() {
return delegate.getKey();
}

public String getValue() {
return delegate.getValue();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package net.brianlevine.keycloak.graphql.types;

import com.fasterxml.jackson.databind.JsonNode;
import io.leangen.graphql.annotations.types.GraphQLType;
import org.keycloak.representations.idm.ClientPolicyExecutorRepresentation;

import java.util.Objects;

@GraphQLType
@SuppressWarnings("unused")
public class ClientPolicyExecutorType {
private final ClientPolicyExecutorRepresentation delegate;

public ClientPolicyExecutorType(ClientPolicyExecutorRepresentation clientPolicyExecutorRepresentation) {
this.delegate = clientPolicyExecutorRepresentation;
}

public String getExecutorProviderId() {
return delegate.getExecutorProviderId();
}

public void setExecutorProviderId(String providerId) {
delegate.setExecutorProviderId(providerId);
}

public JsonNode getConfiguration() {
return delegate.getConfiguration();
}

public void setConfiguration(JsonNode configuration) {
delegate.setConfiguration(configuration);
}

@Override
public boolean equals(Object o) {
if (delegate.getClass() != o.getClass()) return false;
return delegate.equals(o);
}

@Override
public int hashCode() {
return delegate.hashCode();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package net.brianlevine.keycloak.graphql.types;

import io.leangen.graphql.annotations.GraphQLArgument;
import io.leangen.graphql.annotations.types.GraphQLType;
import net.brianlevine.keycloak.graphql.util.Page;
import org.keycloak.representations.idm.ClientPolicyExecutorRepresentation;
import org.keycloak.representations.idm.ClientProfileRepresentation;

import java.util.List;
import java.util.Objects;

@GraphQLType
@SuppressWarnings("unused")
public class ClientProfileType {
private final ClientProfileRepresentation delegate;

public ClientProfileType(ClientProfileRepresentation clientProfileRepresentation) {
this.delegate = clientProfileRepresentation;
}

public String getName() {
return delegate.getName();
}

public void setName(String name) {
delegate.setName(name);
}

public String getDescription() {
return delegate.getDescription();
}

public void setDescription(String description) {
delegate.setDescription(description);
}

public Page<ClientPolicyExecutorType> getExecutors(@GraphQLArgument(defaultValue = "0")int start, @GraphQLArgument(defaultValue = "100")int limit) {
List<ClientPolicyExecutorRepresentation> executors = delegate.getExecutors();
List<ClientPolicyExecutorType> ets = executors.stream()
.skip(start)
.limit(limit)
.map(ClientPolicyExecutorType::new)
.toList();

return new Page<>(executors.size(), limit, ets);
}

public void setExecutors(List<ClientPolicyExecutorRepresentation> executors) {
delegate.setExecutors(executors);
}

@Override
public boolean equals(Object o) {
if (delegate.getClass() != o.getClass()) return false;
return delegate.equals(o);
}

@Override
public int hashCode() {
return delegate.hashCode();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package net.brianlevine.keycloak.graphql.types;

import io.leangen.graphql.annotations.GraphQLArgument;
import io.leangen.graphql.annotations.types.GraphQLType;
import net.brianlevine.keycloak.graphql.util.Page;
import org.keycloak.representations.idm.ClientScopeRepresentation;
import org.keycloak.representations.idm.ProtocolMapperRepresentation;

import java.util.List;
import java.util.Map;

@GraphQLType
@SuppressWarnings("unused")
public class ClientScopeType {
private final ClientScopeRepresentation delegate;

public ClientScopeType(ClientScopeRepresentation clientScopeRepresentation) {
this.delegate = clientScopeRepresentation;
}

public String getId() {
return delegate.getId();
}

public void setId(String id) {
delegate.setId(id);
}

public String getName() {
return delegate.getName();
}

public void setName(String name) {
delegate.setName(name);
}

public String getDescription() {
return delegate.getDescription();
}

public void setDescription(String description) {
delegate.setDescription(description);
}

public Page<ProtocolMapperType> getProtocolMappers(@GraphQLArgument(defaultValue = "0")int start, @GraphQLArgument(defaultValue = "100")int limit) {
List<ProtocolMapperType> pms = delegate.getProtocolMappers().stream()
.skip(start)
.limit(limit)
.map(ProtocolMapperType::new)
.toList();

return new Page<>(pms.size(), limit, pms);
}

public void setProtocolMappers(List<ProtocolMapperRepresentation> protocolMappers) {
delegate.setProtocolMappers(protocolMappers);
}

public String getProtocol() {
return delegate.getProtocol();
}

public void setProtocol(String protocol) {
delegate.setProtocol(protocol);
}

public AttributeMap getAttributes(@GraphQLArgument(defaultValue = "0")int start, @GraphQLArgument(defaultValue = "100")int limit) {
return new AttributeMap(delegate.getAttributes(), start, limit);
}

public void setAttributes(Map<String, String> attributes) {
delegate.setAttributes(attributes);
}

@Override
public boolean equals(Object o) {
if (!(o instanceof ClientScopeRepresentation)) return false;
return delegate.equals(o);
}

@Override
public int hashCode() {
return delegate.hashCode();
}
}
Loading

0 comments on commit 366f0a7

Please sign in to comment.