use of org.keycloak.client.admin.cli.config.ConfigData in project keycloak by keycloak.
the class AbstractAuthOptionsCmd method processGlobalOptions.
protected void processGlobalOptions() {
super.processGlobalOptions();
if (config != null && noconfig) {
throw new RuntimeException("Options --config and --no-config are mutually exclusive");
}
if (!noconfig) {
setConfigFile(config != null ? config : ConfigUtil.DEFAULT_CONFIG_FILE_PATH);
ConfigUtil.setHandler(new FileConfigHandler());
} else {
InMemoryConfigHandler handler = new InMemoryConfigHandler();
ConfigData data = new ConfigData();
initConfigData(data);
handler.setConfigData(data);
ConfigUtil.setHandler(handler);
}
}
use of org.keycloak.client.admin.cli.config.ConfigData in project keycloak by keycloak.
the class AbstractRequestCmd method process.
public CommandResult process(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
// see if Content-Type header is explicitly set to non-json value
Header ctype = headers.get("content-type");
InputStream content = null;
CmdStdinContext<JsonNode> ctx = new CmdStdinContext<>();
if (file != null) {
if (ctype != null && !"application/json".equals(ctype.getValue())) {
if ("-".equals(file)) {
content = System.in;
} else {
try {
content = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found: " + file);
}
}
} else {
ctx = parseFileOrStdin(file);
}
} else if (body != null) {
content = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
}
ConfigData config = loadConfig();
config = copyWithServerInfo(config);
setupTruststore(config, commandInvocation);
String auth = null;
config = ensureAuthInfo(config, commandInvocation);
config = copyWithServerInfo(config);
if (credentialsAvailable(config)) {
auth = ensureToken(config);
}
auth = auth != null ? "Bearer " + auth : null;
if (auth != null) {
headers.addIfMissing("Authorization", auth);
}
final String server = config.getServerUrl();
final String realm = getTargetRealm(config);
final String adminRoot = adminRestRoot != null ? adminRestRoot : composeAdminRoot(server);
String resourceUrl = composeResourceUrl(adminRoot, realm, url);
String typeName = extractTypeNameFromUri(resourceUrl);
if (filter.size() > 0) {
resourceUrl = HttpUtil.addQueryParamsToUri(resourceUrl, filter);
}
headers.addIfMissing("Accept", "application/json");
if (isUpdate() && mergeMode) {
ObjectNode result;
HeadersBodyStatus response;
try {
response = HttpUtil.doGet(resourceUrl, new HeadersBody(headers));
checkSuccess(resourceUrl, response);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
copyStream(response.getBody(), buffer);
result = MAPPER.readValue(buffer.toByteArray(), ObjectNode.class);
} catch (IOException e) {
throw new RuntimeException("HTTP request error: " + e.getMessage(), e);
}
CmdStdinContext<JsonNode> ctxremote = new CmdStdinContext<>();
ctxremote.setResult(result);
// merge local representation over remote one
if (ctx.getResult() != null) {
ReflectionUtil.merge(ctx.getResult(), (ObjectNode) ctxremote.getResult());
}
ctx = ctxremote;
}
if (attrs.size() > 0) {
if (content != null) {
throw new RuntimeException("Can't set attributes on content of type other than application/json");
}
ctx = mergeAttributes(ctx, MAPPER.createObjectNode(), attrs);
}
if (content == null && ctx.getContent() != null) {
content = new ByteArrayInputStream(ctx.getContent().getBytes(StandardCharsets.UTF_8));
}
ReturnFields returnFields = null;
if (fields != null) {
returnFields = new ReturnFields(fields);
}
// make sure content type is set
if (content != null) {
headers.addIfMissing("Content-Type", "application/json");
}
LinkedHashMap<String, String> queryParams = new LinkedHashMap<>();
if (offset != null) {
queryParams.put("first", String.valueOf(offset));
}
if (limit != null) {
queryParams.put("max", String.valueOf(limit));
}
if (queryParams.size() > 0) {
resourceUrl = HttpUtil.addQueryParamsToUri(resourceUrl, queryParams);
}
HeadersBodyStatus response;
try {
response = HttpUtil.doRequest(httpVerb, resourceUrl, new HeadersBody(headers, content));
} catch (IOException e) {
throw new RuntimeException("HTTP request error: " + e.getMessage(), e);
}
// output response
if (printHeaders) {
printOut(response.getStatus());
for (Header header : response.getHeaders()) {
printOut(header.getName() + ": " + header.getValue());
}
}
checkSuccess(resourceUrl, response);
AccessibleBufferOutputStream abos = new AccessibleBufferOutputStream(System.out);
if (response.getBody() == null) {
throw new RuntimeException("Internal error - response body should never be null");
}
if (printHeaders) {
printOut("");
}
Header location = response.getHeaders().get("Location");
String id = location != null ? extractLastComponentOfUri(location.getValue()) : null;
if (id != null) {
if (returnId) {
printOut(id);
} else if (!outputResult) {
printErr("Created new " + typeName + " with id '" + id + "'");
}
}
if (outputResult) {
if (isCreateOrUpdate() && (response.getStatusCode() == 204 || id != null)) {
// get object for id
headers = new Headers();
if (auth != null) {
headers.add("Authorization", auth);
}
try {
String fetchUrl = id != null ? (resourceUrl + "/" + id) : resourceUrl;
response = doGet(fetchUrl, new HeadersBody(headers));
} catch (IOException e) {
throw new RuntimeException("HTTP request error: " + e.getMessage(), e);
}
}
Header contentType = response.getHeaders().get("content-type");
boolean canPrettyPrint = contentType != null && contentType.getValue().equals("application/json");
boolean pretty = !compressed;
if (canPrettyPrint && (pretty || returnFields != null)) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
copyStream(response.getBody(), buffer);
try {
JsonNode rootNode = MAPPER.readValue(buffer.toByteArray(), JsonNode.class);
if (returnFields != null) {
rootNode = applyFieldFilter(MAPPER, rootNode, returnFields);
}
if (outputFormat == OutputFormat.JSON) {
// now pretty print it to output
MAPPER.writeValue(abos, rootNode);
} else {
printAsCsv(rootNode, returnFields, unquoted);
}
} catch (Exception ignored) {
copyStream(new ByteArrayInputStream(buffer.toByteArray()), abos);
}
} else {
copyStream(response.getBody(), abos);
}
}
int lastByte = abos.getLastByte();
if (lastByte != -1 && lastByte != 13 && lastByte != 10) {
printErr("");
}
return CommandResult.SUCCESS;
}
use of org.keycloak.client.admin.cli.config.ConfigData in project keycloak by keycloak.
the class AddRolesCmd method execute.
@Override
public CommandResult execute(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
List<String> roleNames = new LinkedList<>();
List<String> roleIds = new LinkedList<>();
try {
if (printHelp()) {
return help ? CommandResult.SUCCESS : CommandResult.FAILURE;
}
processGlobalOptions();
Iterator<String> it = args.iterator();
while (it.hasNext()) {
String option = it.next();
switch(option) {
case "--rolename":
{
optionRequiresValueCheck(it, option);
roleNames.add(it.next());
break;
}
case "--roleid":
{
optionRequiresValueCheck(it, option);
roleIds.add(it.next());
break;
}
default:
{
throw new IllegalArgumentException("Invalid option: " + option);
}
}
}
if (uid != null && uusername != null) {
throw new IllegalArgumentException("Incompatible options: --uid and --uusername are mutually exclusive");
}
if ((gid != null && gname != null) || (gid != null && gpath != null) || (gname != null && gpath != null)) {
throw new IllegalArgumentException("Incompatible options: --gid, --gname and --gpath are mutually exclusive");
}
if (roleNames.isEmpty() && roleIds.isEmpty()) {
throw new IllegalArgumentException("No role to add specified. Use --rolename or --roleid to specify roles to add");
}
if (cid != null && cclientid != null) {
throw new IllegalArgumentException("Incompatible options: --cid and --cclientid are mutually exclusive");
}
if (rid != null && rname != null) {
throw new IllegalArgumentException("Incompatible options: --rid and --rname are mutually exclusive");
}
if (isUserSpecified() && isGroupSpecified()) {
throw new IllegalArgumentException("Incompatible options: --uusername / --uid can't be used at the same time as --gname / --gid / --gpath");
}
if (isUserSpecified() && isCompositeRoleSpecified()) {
throw new IllegalArgumentException("Incompatible options: --uusername / --uid can't be used at the same time as --rname / --rid");
}
if (isGroupSpecified() && isCompositeRoleSpecified()) {
throw new IllegalArgumentException("Incompatible options: --rname / --rid can't be used at the same time as --gname / --gid / --gpath");
}
if (!isUserSpecified() && !isGroupSpecified() && !isCompositeRoleSpecified()) {
throw new IllegalArgumentException("No user nor group nor composite role specified. Use --uusername / --uid to specify user or --gname / --gid / --gpath to specify group or --rname / --rid to specify a composite role");
}
ConfigData config = loadConfig();
config = copyWithServerInfo(config);
setupTruststore(config, commandInvocation);
String auth = null;
config = ensureAuthInfo(config, commandInvocation);
config = copyWithServerInfo(config);
if (credentialsAvailable(config)) {
auth = ensureToken(config);
}
auth = auth != null ? "Bearer " + auth : null;
final String server = config.getServerUrl();
final String realm = getTargetRealm(config);
final String adminRoot = adminRestRoot != null ? adminRestRoot : composeAdminRoot(server);
if (isUserSpecified()) {
if (uid == null) {
uid = UserOperations.getIdFromUsername(adminRoot, realm, auth, uusername);
}
if (isClientSpecified()) {
// list client roles for a user
if (cid == null) {
cid = ClientOperations.getIdFromClientId(adminRoot, realm, auth, cclientid);
}
List<ObjectNode> roles = RoleOperations.getClientRoles(adminRoot, realm, cid, auth);
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(roles));
// now add all the roles
UserOperations.addClientRoles(adminRoot, realm, auth, uid, cid, new ArrayList<>(rolesToAdd));
} else {
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(RoleOperations.getRealmRolesAsNodes(adminRoot, realm, auth)));
// now add all the roles
UserOperations.addRealmRoles(adminRoot, realm, auth, uid, new ArrayList<>(rolesToAdd));
}
} else if (isGroupSpecified()) {
if (gname != null) {
gid = GroupOperations.getIdFromName(adminRoot, realm, auth, gname);
} else if (gpath != null) {
gid = GroupOperations.getIdFromPath(adminRoot, realm, auth, gpath);
}
if (isClientSpecified()) {
// list client roles for a group
if (cid == null) {
cid = ClientOperations.getIdFromClientId(adminRoot, realm, auth, cclientid);
}
List<ObjectNode> roles = RoleOperations.getClientRoles(adminRoot, realm, cid, auth);
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(roles));
// now add all the roles
GroupOperations.addClientRoles(adminRoot, realm, auth, gid, cid, new ArrayList<>(rolesToAdd));
} else {
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(RoleOperations.getRealmRolesAsNodes(adminRoot, realm, auth)));
// now add all the roles
GroupOperations.addRealmRoles(adminRoot, realm, auth, gid, new ArrayList<>(rolesToAdd));
}
} else if (isCompositeRoleSpecified()) {
if (rid == null) {
rid = RoleOperations.getIdFromRoleName(adminRoot, realm, auth, rname);
}
if (isClientSpecified()) {
// list client roles for a composite role
if (cid == null) {
cid = ClientOperations.getIdFromClientId(adminRoot, realm, auth, cclientid);
}
List<ObjectNode> roles = RoleOperations.getClientRoles(adminRoot, realm, cid, auth);
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(roles));
// now add all the roles
RoleOperations.addClientRoles(adminRoot, realm, auth, rid, new ArrayList<>(rolesToAdd));
} else {
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(RoleOperations.getRealmRolesAsNodes(adminRoot, realm, auth)));
// now add all the roles
RoleOperations.addRealmRoles(adminRoot, realm, auth, rid, new ArrayList<>(rolesToAdd));
}
} else {
throw new IllegalArgumentException("No user nor group, nor composite role specified. Use --uusername / --uid to specify user or --gname / --gid / --gpath to specify group or --rname / --rid to specify a composite role");
}
return CommandResult.SUCCESS;
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + suggestHelp(), e);
} finally {
commandInvocation.stop();
}
}
use of org.keycloak.client.admin.cli.config.ConfigData in project keycloak by keycloak.
the class RemoveRolesCmd method execute.
@Override
public CommandResult execute(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
List<String> roleNames = new LinkedList<>();
List<String> roleIds = new LinkedList<>();
try {
if (printHelp()) {
return help ? CommandResult.SUCCESS : CommandResult.FAILURE;
}
processGlobalOptions();
Iterator<String> it = args.iterator();
while (it.hasNext()) {
String option = it.next();
switch(option) {
case "--rolename":
{
optionRequiresValueCheck(it, option);
roleNames.add(it.next());
break;
}
case "--roleid":
{
optionRequiresValueCheck(it, option);
roleIds.add(it.next());
break;
}
default:
{
throw new IllegalArgumentException("Invalid option: " + option);
}
}
}
if (uid != null && uusername != null) {
throw new IllegalArgumentException("Incompatible options: --uid and --uusername are mutually exclusive");
}
if ((gid != null && gname != null) || (gid != null && gpath != null) || (gname != null && gpath != null)) {
throw new IllegalArgumentException("Incompatible options: --gid, --gname and --gpath are mutually exclusive");
}
if (roleNames.isEmpty() && roleIds.isEmpty()) {
throw new IllegalArgumentException("No role to remove specified. Use --rolename or --roleid to specify roles to remove");
}
if (cid != null && cclientid != null) {
throw new IllegalArgumentException("Incompatible options: --cid and --cclientid are mutually exclusive");
}
if (rid != null && rname != null) {
throw new IllegalArgumentException("Incompatible options: --rid and --rname are mutually exclusive");
}
if (isUserSpecified() && isGroupSpecified()) {
throw new IllegalArgumentException("Incompatible options: --uusername / --uid can't be used at the same time as --gname / --gid / --gpath");
}
if (isUserSpecified() && isCompositeRoleSpecified()) {
throw new IllegalArgumentException("Incompatible options: --uusername / --uid can't be used at the same time as --rname / --rid");
}
if (isGroupSpecified() && isCompositeRoleSpecified()) {
throw new IllegalArgumentException("Incompatible options: --rname / --rid can't be used at the same time as --gname / --gid / --gpath");
}
if (!isUserSpecified() && !isGroupSpecified() && !isCompositeRoleSpecified()) {
throw new IllegalArgumentException("No user nor group nor composite role specified. Use --uusername / --uid to specify user or --gname / --gid / --gpath to specify group or --rname / --rid to specify a composite role");
}
ConfigData config = loadConfig();
config = copyWithServerInfo(config);
setupTruststore(config, commandInvocation);
String auth = null;
config = ensureAuthInfo(config, commandInvocation);
config = copyWithServerInfo(config);
if (credentialsAvailable(config)) {
auth = ensureToken(config);
}
auth = auth != null ? "Bearer " + auth : null;
final String server = config.getServerUrl();
final String realm = getTargetRealm(config);
final String adminRoot = adminRestRoot != null ? adminRestRoot : composeAdminRoot(server);
if (isUserSpecified()) {
if (uid == null) {
uid = UserOperations.getIdFromUsername(adminRoot, realm, auth, uusername);
}
if (isClientSpecified()) {
// remove client roles from a user
if (cid == null) {
cid = ClientOperations.getIdFromClientId(adminRoot, realm, auth, cclientid);
}
List<ObjectNode> roles = RoleOperations.getClientRoles(adminRoot, realm, cid, auth);
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(roles));
// now remove the roles
UserOperations.removeClientRoles(adminRoot, realm, auth, uid, cid, new ArrayList<>(rolesToAdd));
} else {
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(RoleOperations.getRealmRolesAsNodes(adminRoot, realm, auth)));
// now remove the roles
UserOperations.removeRealmRoles(adminRoot, realm, auth, uid, new ArrayList<>(rolesToAdd));
}
} else if (isGroupSpecified()) {
if (gname != null) {
gid = GroupOperations.getIdFromName(adminRoot, realm, auth, gname);
} else if (gpath != null) {
gid = GroupOperations.getIdFromPath(adminRoot, realm, auth, gpath);
}
if (isClientSpecified()) {
// remove client roles from a group
if (cid == null) {
cid = ClientOperations.getIdFromClientId(adminRoot, realm, auth, cclientid);
}
List<ObjectNode> roles = RoleOperations.getClientRoles(adminRoot, realm, cid, auth);
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(roles));
// now remove the roles
GroupOperations.removeClientRoles(adminRoot, realm, auth, gid, cid, new ArrayList<>(rolesToAdd));
} else {
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(RoleOperations.getRealmRolesAsNodes(adminRoot, realm, auth)));
// now remove the roles
GroupOperations.removeRealmRoles(adminRoot, realm, auth, gid, new ArrayList<>(rolesToAdd));
}
} else if (isCompositeRoleSpecified()) {
if (rid == null) {
rid = RoleOperations.getIdFromRoleName(adminRoot, realm, auth, rname);
}
if (isClientSpecified()) {
// remove client roles from a role
if (cid == null) {
cid = ClientOperations.getIdFromClientId(adminRoot, realm, auth, cclientid);
}
List<ObjectNode> roles = RoleOperations.getClientRoles(adminRoot, realm, cid, auth);
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(roles));
// now remove the roles
RoleOperations.removeClientRoles(adminRoot, realm, auth, rid, new ArrayList<>(rolesToAdd));
} else {
Set<ObjectNode> rolesToAdd = getRoleRepresentations(roleNames, roleIds, new LocalSearch(RoleOperations.getRealmRolesAsNodes(adminRoot, realm, auth)));
// now remove the roles
RoleOperations.removeRealmRoles(adminRoot, realm, auth, rid, new ArrayList<>(rolesToAdd));
}
} else {
throw new IllegalArgumentException("No user nor group, nor composite role specified. Use --uusername / --uid to specify user or --gname / --gid / --gpath to specify group or --rname / --rid to specify a composite role");
}
return CommandResult.SUCCESS;
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + suggestHelp(), e);
} finally {
commandInvocation.stop();
}
}
use of org.keycloak.client.admin.cli.config.ConfigData in project keycloak by keycloak.
the class AbstractAuthOptionsCmd method copyWithServerInfo.
protected ConfigData copyWithServerInfo(ConfigData config) {
ConfigData result = config.deepcopy();
if (server != null) {
result.setServerUrl(server);
}
if (realm != null) {
result.setRealm(realm);
}
if (externalToken != null) {
result.setExternalToken(externalToken);
}
checkServerInfo(result);
return result;
}
Aggregations