Search in sources :

Example 56 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project identity-inbound-provisioning-scim2 by wso2-extensions.

the class RoleResource method patchRole.

@PATCH
@Path("{id}")
public Response patchRole(@PathParam(SCIMConstants.CommonSchemaConstants.ID) String id, @HeaderParam(SCIMConstants.CONTENT_TYPE_HEADER) String inputFormat, @HeaderParam(SCIMProviderConstants.ACCEPT_HEADER) String outputFormat, String resourceString) {
    try {
        // content-type header is compulsory in post request.
        if (inputFormat == null) {
            String error = SCIMProviderConstants.CONTENT_TYPE + " not present in the request header";
            throw new FormatNotSupportedException(error);
        }
        if (!isValidInputFormat(inputFormat)) {
            String error = inputFormat + " is not supported.";
            throw new FormatNotSupportedException(error);
        }
        if (!isValidOutputFormat(outputFormat)) {
            String error = outputFormat + " is not supported.";
            throw new FormatNotSupportedException(error);
        }
        // Obtain the role manager.
        RoleManager roleManager = IdentitySCIMManager.getInstance().getRoleManager();
        // Create charon-SCIM role resource manager and hand-over the request.
        RoleResourceManager roleResourceManager = new RoleResourceManager();
        SCIMResponse response = roleResourceManager.updateWithPATCHRole(id, resourceString, roleManager);
        return SupportUtils.buildResponse(response);
    } catch (CharonException e) {
        return handleCharonException(e);
    } catch (FormatNotSupportedException e) {
        return handleFormatNotSupportedException(e);
    }
}
Also used : FormatNotSupportedException(org.wso2.charon3.core.exceptions.FormatNotSupportedException) RoleResourceManager(org.wso2.charon3.core.protocol.endpoints.RoleResourceManager) RoleManager(org.wso2.charon3.core.extensions.RoleManager) CharonException(org.wso2.charon3.core.exceptions.CharonException) SCIMResponse(org.wso2.charon3.core.protocol.SCIMResponse) Path(javax.ws.rs.Path) PATCH(org.wso2.carbon.identity.jaxrs.designator.PATCH)

Example 57 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project identity-inbound-provisioning-scim2 by wso2-extensions.

the class UserResource method patchUser.

@PATCH
@Path("{id}")
public Response patchUser(@PathParam(SCIMConstants.CommonSchemaConstants.ID) String id, @HeaderParam(SCIMProviderConstants.CONTENT_TYPE) String inputFormat, @HeaderParam(SCIMProviderConstants.ACCEPT_HEADER) String outputFormat, @QueryParam(SCIMProviderConstants.ATTRIBUTES) String attribute, @QueryParam(SCIMProviderConstants.EXCLUDE_ATTRIBUTES) String excludedAttributes, String resourceString) {
    try {
        // content-type header is compulsory in post request.
        if (inputFormat == null) {
            String error = SCIMProviderConstants.CONTENT_TYPE + " not present in the request header";
            throw new FormatNotSupportedException(error);
        }
        if (!isValidInputFormat(inputFormat)) {
            String error = inputFormat + " is not supported.";
            throw new FormatNotSupportedException(error);
        }
        if (!isValidOutputFormat(outputFormat)) {
            String error = outputFormat + " is not supported.";
            throw new FormatNotSupportedException(error);
        }
        // obtain the user store manager
        UserManager userManager = IdentitySCIMManager.getInstance().getUserManager();
        // Build Custom schema
        buildCustomSchema(userManager, getTenantId());
        // create charon-SCIM user endpoint and hand-over the request.
        UserResourceManager userResourceEndpoint = new UserResourceManager();
        SCIMResponse response = userResourceEndpoint.updateWithPATCH(id, resourceString, userManager, attribute, excludedAttributes);
        return SupportUtils.buildResponse(response);
    } catch (CharonException e) {
        return handleCharonException(e);
    } catch (FormatNotSupportedException e) {
        return handleFormatNotSupportedException(e);
    }
}
Also used : FormatNotSupportedException(org.wso2.charon3.core.exceptions.FormatNotSupportedException) UserManager(org.wso2.charon3.core.extensions.UserManager) CharonException(org.wso2.charon3.core.exceptions.CharonException) UserResourceManager(org.wso2.charon3.core.protocol.endpoints.UserResourceManager) SCIMResponse(org.wso2.charon3.core.protocol.SCIMResponse) PATCH(org.wso2.carbon.identity.jaxrs.designator.PATCH)

Example 58 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project identity-inbound-provisioning-scim2 by wso2-extensions.

the class GroupResource method processRequest.

private Response processRequest(final Map<String, String> requestAttributes) {
    String id = requestAttributes.get(SCIMProviderConstants.ID);
    String httpVerb = requestAttributes.get(SCIMProviderConstants.HTTP_VERB);
    String resourceString = requestAttributes.get(SCIMProviderConstants.RESOURCE_STRING);
    String attributes = requestAttributes.get(SCIMProviderConstants.ATTRIBUTES);
    String excludedAttributes = requestAttributes.get(SCIMProviderConstants.EXCLUDE_ATTRIBUTES);
    String search = requestAttributes.get(SCIMProviderConstants.SEARCH);
    JSONArray outputPermissions;
    Gson gson = new Gson();
    HashMap<String, String> responseHeaders = new HashMap<>();
    responseHeaders.put("Content-Type", SCIMProviderConstants.APPLICATION_SCIM_JSON);
    try {
        // Obtain the user store manager
        SCIMUserManager userManager = (SCIMUserManager) IdentitySCIMManager.getInstance().getUserManager();
        // Create charon-SCIM group endpoint and hand-over the request.
        GroupResourceManager groupResourceManager = new GroupResourceManager();
        SCIMResponse scimResponse = null;
        String groupName;
        if (GET.class.getSimpleName().equals(httpVerb) && id == null) {
            String filter = requestAttributes.get(SCIMProviderConstants.FILTER);
            String sortBy = requestAttributes.get(SCIMProviderConstants.SORT_BY);
            String sortOrder = requestAttributes.get(SCIMProviderConstants.SORT_ORDER);
            String domainName = requestAttributes.get(SCIMProviderConstants.DOMAIN);
            // Processing count and startIndex in the request.
            Integer startIndex = convertStringPaginationParamsToInteger(requestAttributes.get(SCIMProviderConstants.START_INDEX), SCIMProviderConstants.START_INDEX);
            Integer count = convertStringPaginationParamsToInteger(requestAttributes.get(SCIMProviderConstants.COUNT), SCIMProviderConstants.COUNT);
            scimResponse = groupResourceManager.listWithGET(userManager, filter, startIndex, count, sortBy, sortOrder, domainName, attributes, excludedAttributes);
        } else if (GET.class.getSimpleName().equals(httpVerb) && isGroupPermissionsRequest(requestAttributes)) {
            try {
                groupName = getGroupName(id, userManager, groupResourceManager, excludedAttributes);
                outputPermissions = new JSONArray(Arrays.asList(userManager.getGroupPermissions(groupName)));
                scimResponse = new SCIMResponse(ResponseCodeConstants.CODE_OK, outputPermissions.toString(), responseHeaders);
            } catch (JSONException e) {
                return SupportUtils.buildResponse(groupResourceManager.get(id, userManager, attributes, excludedAttributes));
            }
        } else if (GET.class.getSimpleName().equals(httpVerb)) {
            scimResponse = groupResourceManager.get(id, userManager, attributes, excludedAttributes);
        } else if (POST.class.getSimpleName().equals(httpVerb) && search.equals("1")) {
            scimResponse = groupResourceManager.listWithPOST(resourceString, userManager);
        } else if (POST.class.getSimpleName().equals(httpVerb)) {
            scimResponse = groupResourceManager.create(resourceString, userManager, attributes, excludedAttributes);
        } else if (PUT.class.getSimpleName().equals(httpVerb) && isGroupPermissionsRequest(requestAttributes)) {
            try {
                groupName = getGroupName(id, userManager, groupResourceManager, excludedAttributes);
                String[] permissions = gson.fromJson(resourceString, String[].class);
                // Replace the existing permission paths with given array.
                userManager.setGroupPermissions(groupName, permissions);
                outputPermissions = new JSONArray(Arrays.asList(userManager.getGroupPermissions(groupName)));
                scimResponse = new SCIMResponse(ResponseCodeConstants.CODE_OK, outputPermissions.toString(), responseHeaders);
            } catch (JSONException e) {
                return SupportUtils.buildResponse(groupResourceManager.get(id, userManager, attributes, excludedAttributes));
            }
        } else if (PUT.class.getSimpleName().equals(httpVerb)) {
            scimResponse = groupResourceManager.updateWithPUT(id, resourceString, userManager, attributes, excludedAttributes);
        } else if (PATCH.class.getSimpleName().equals(httpVerb) && isGroupPermissionsRequest(requestAttributes)) {
            try {
                groupName = getGroupName(id, userManager, groupResourceManager, excludedAttributes);
                // Decode the resource string and get the permissions to add or remove.
                HashMap<String, String[]> permissionMap = decodePatchOperation(resourceString);
                userManager.updatePermissionListOfGroup(groupName, permissionMap.get(SCIMProviderConstants.ADD), permissionMap.get(SCIMProviderConstants.REMOVE));
                outputPermissions = new JSONArray(Arrays.asList(userManager.getGroupPermissions(groupName)));
                scimResponse = new SCIMResponse(ResponseCodeConstants.CODE_OK, outputPermissions.toString(), responseHeaders);
            } catch (JSONException e) {
                return SupportUtils.buildResponse(groupResourceManager.get(id, userManager, attributes, excludedAttributes));
            }
        } else if (PATCH.class.getSimpleName().equals(httpVerb)) {
            if (isGroupReturnedInPatchResponse() || isAttributesRequested(attributes)) {
                scimResponse = groupResourceManager.updateWithPATCH(id, resourceString, userManager, attributes, excludedAttributes);
            } else {
                scimResponse = groupResourceManager.updateWithPATCH(id, resourceString, userManager);
            }
        } else if (DELETE.class.getSimpleName().equals(httpVerb)) {
            scimResponse = groupResourceManager.delete(id, userManager);
        }
        return SupportUtils.buildResponse(Objects.requireNonNull(scimResponse));
    } catch (BadRequestException e) {
        logger.error("The Patch request is invalid. Unable to decode." + e);
        return SupportUtils.buildResponse(new SCIMResponse(ResponseCodeConstants.CODE_BAD_REQUEST, "The Patch request is invalid.", responseHeaders));
    } catch (CharonException e) {
        return handleCharonException(e);
    } catch (UserStoreException | RolePermissionException e) {
        return handleCharonException(new CharonException("Error occurred when getting the permissions from server", e));
    }
}
Also used : SCIMUserManager(org.wso2.carbon.identity.scim2.common.impl.SCIMUserManager) HashMap(java.util.HashMap) POST(javax.ws.rs.POST) JSONArray(org.json.JSONArray) Gson(com.google.gson.Gson) JSONException(org.json.JSONException) RolePermissionException(org.wso2.carbon.user.mgt.RolePermissionException) GroupResourceManager(org.wso2.charon3.core.protocol.endpoints.GroupResourceManager) PUT(javax.ws.rs.PUT) PATCH(org.wso2.carbon.identity.jaxrs.designator.PATCH) GET(javax.ws.rs.GET) UserStoreException(org.wso2.carbon.user.api.UserStoreException) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) CharonException(org.wso2.charon3.core.exceptions.CharonException) SCIMResponse(org.wso2.charon3.core.protocol.SCIMResponse)

Example 59 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project identity-api-server by wso2.

the class ServerConfigManagementService method patchCORSConfig.

/**
 * Patch the CORS config of a tenant.
 *
 * @param corsPatchList List of patch operations.
 */
public void patchCORSConfig(List<CORSPatch> corsPatchList) {
    if (CollectionUtils.isEmpty(corsPatchList)) {
        return;
    }
    String tenantDomain = ContextLoader.getTenantDomainFromContext();
    CORSConfiguration corsConfiguration;
    try {
        corsConfiguration = ConfigsServiceHolder.getInstance().getCorsManagementService().getCORSConfiguration(tenantDomain);
    } catch (CORSManagementServiceException e) {
        throw handleCORSException(e, Constants.ErrorMessage.ERROR_CODE_CORS_CONFIG_RETRIEVE, null);
    }
    try {
        for (CORSPatch corsPatch : corsPatchList) {
            String path = corsPatch.getPath();
            CORSPatch.OperationEnum operation = corsPatch.getOperation();
            String value = corsPatch.getValue().trim();
            // We support only 'REPLACE', 'ADD' and 'REMOVE' patch operations.
            if (operation == CORSPatch.OperationEnum.REPLACE) {
                if (path.matches(Constants.CORS_CONFIG_ALLOW_GENERIC_HTTP_PATH_REGEX)) {
                    corsConfiguration.setAllowGenericHttpRequests(Boolean.parseBoolean(value));
                } else if (path.matches(Constants.CORS_CONFIG_ALLOW_ANY_ORIGIN_PATH_REGEX)) {
                    corsConfiguration.setAllowAnyOrigin(Boolean.parseBoolean(value));
                } else if (path.matches(Constants.CORS_CONFIG_ALLOW_SUBDOMAINS_PATH_REGEX)) {
                    corsConfiguration.setAllowSubdomains(Boolean.parseBoolean(value));
                } else if (path.matches(Constants.CORS_CONFIG_SUPPORTED_METHODS_PATH_REGEX)) {
                    corsConfiguration.setSupportedMethods(new HashSet<>(Collections.singletonList(value)));
                } else if (path.matches(Constants.CORS_CONFIG_SUPPORT_ANY_HEADER_PATH_REGEX)) {
                    corsConfiguration.setSupportAnyHeader(Boolean.parseBoolean(value));
                } else if (path.matches(Constants.CORS_CONFIG_SUPPORTED_HEADERS_PATH_REGEX)) {
                    corsConfiguration.setSupportedHeaders(new HashSet<>(Collections.singletonList(value)));
                } else if (path.matches(Constants.CORS_CONFIG_EXPOSED_HEADERS_PATH_REGEX)) {
                    corsConfiguration.setExposedHeaders(new HashSet<>(Collections.singletonList(value)));
                } else if (path.matches(Constants.CORS_CONFIG_SUPPORTS_CREDENTIALS_PATH_REGEX)) {
                    corsConfiguration.setSupportsCredentials(Boolean.parseBoolean(value));
                } else if (path.matches(Constants.CORS_CONFIG_MAX_AGE_PATH_REGEX)) {
                    corsConfiguration.setMaxAge(Integer.parseInt(value));
                } else {
                    // Throw an error if any other patch operations are sent in the request.
                    throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, "Unsupported patch operation");
                }
            } else if (operation == CORSPatch.OperationEnum.ADD) {
                if (path.matches(Constants.CORS_CONFIG_SUPPORTED_METHODS_PATH_REGEX)) {
                    corsConfiguration.getSupportedMethods().add(value);
                } else if (path.matches(Constants.CORS_CONFIG_SUPPORTED_HEADERS_PATH_REGEX)) {
                    corsConfiguration.getSupportedHeaders().add(value);
                } else if (path.matches(Constants.CORS_CONFIG_EXPOSED_HEADERS_PATH_REGEX)) {
                    corsConfiguration.getExposedHeaders().add(value);
                } else {
                    // Throw an error if any other patch operations are sent in the request.
                    throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, "Unsupported patch operation");
                }
            } else if (operation == CORSPatch.OperationEnum.REMOVE) {
                if (path.matches(Constants.CORS_CONFIG_SUPPORTED_METHODS_PATH_REGEX)) {
                    corsConfiguration.getSupportedMethods().remove(value);
                } else if (path.matches(Constants.CORS_CONFIG_SUPPORTED_HEADERS_PATH_REGEX)) {
                    corsConfiguration.getSupportedHeaders().remove(value);
                } else if (path.matches(Constants.CORS_CONFIG_EXPOSED_HEADERS_PATH_REGEX)) {
                    corsConfiguration.getExposedHeaders().remove(value);
                } else {
                    // Throw an error if any other patch operations are sent in the request.
                    throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, "Unsupported patch operation");
                }
            } else {
                // Throw an error if any other patch operations are sent in the request.
                throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, "Unsupported patch operation");
            }
        }
        // Set the patched configuration object as the new CORS configuration for the tenant.
        ConfigsServiceHolder.getInstance().getCorsManagementService().setCORSConfiguration(corsConfiguration, tenantDomain);
    } catch (CORSManagementServiceException e) {
        throw handleCORSException(e, Constants.ErrorMessage.ERROR_CODE_CORS_CONFIG_UPDATE, null);
    }
}
Also used : CORSConfiguration(org.wso2.carbon.identity.cors.mgt.core.model.CORSConfiguration) CORSPatch(org.wso2.carbon.identity.api.server.configs.v1.model.CORSPatch) CORSManagementServiceException(org.wso2.carbon.identity.cors.mgt.core.exception.CORSManagementServiceException) HashSet(java.util.HashSet)

Example 60 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project identity-api-server by wso2.

the class ServerConfigManagementService method patchConfigs.

/**
 * Patch Server Configs. Patch 'REPLACE', 'ADD', 'REMOVE' operations have been supported for primary attributes in
 * ServerConfig model.
 *
 * @param patchRequest Patch request in Json Patch notation See
 *                     <a href="https://tools.ietf.org/html/rfc6902">https://tools.ietf
 *                     .org/html/rfc6902</a>.
 */
public void patchConfigs(List<Patch> patchRequest) {
    try {
        IdentityProvider residentIdP = ConfigsServiceHolder.getInstance().getIdentityProviderManager().getResidentIdP(ContextLoader.getTenantDomainFromContext());
        // Resident Identity Provider can be null only due to an internal server error.
        if (residentIdP == null) {
            throw handleException(Response.Status.INTERNAL_SERVER_ERROR, Constants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_CONFIGS, null);
        }
        IdentityProvider idpToUpdate = createIdPClone(residentIdP);
        processPatchRequest(patchRequest, idpToUpdate);
        // To avoid updating non-existing authenticators in DB layer.
        idpToUpdate.setFederatedAuthenticatorConfigs(new FederatedAuthenticatorConfig[0]);
        ConfigsServiceHolder.getInstance().getIdentityProviderManager().updateResidentIdP(idpToUpdate, ContextLoader.getTenantDomainFromContext());
    } catch (IdentityProviderManagementException e) {
        throw handleIdPException(e, Constants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_CONFIGS, null);
    }
}
Also used : IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Aggregations

BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)19 ArrayList (java.util.ArrayList)11 HashMap (java.util.HashMap)11 Test (org.testng.annotations.Test)11 JSONArray (org.json.JSONArray)9 JSONObject (org.json.JSONObject)9 Attribute (org.wso2.charon3.core.attributes.Attribute)9 ComplexAttribute (org.wso2.charon3.core.attributes.ComplexAttribute)9 MultiValuedAttribute (org.wso2.charon3.core.attributes.MultiValuedAttribute)9 SimpleAttribute (org.wso2.charon3.core.attributes.SimpleAttribute)9 CharonException (org.wso2.charon3.core.exceptions.CharonException)9 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)8 List (java.util.List)7 NotImplementedException (org.wso2.charon3.core.exceptions.NotImplementedException)7 LinkedHashMap (java.util.LinkedHashMap)6 Map (java.util.Map)6 JSONException (org.json.JSONException)6 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)6 AttributeSchema (org.wso2.charon3.core.schema.AttributeSchema)6 ExtractableResponse (io.restassured.response.ExtractableResponse)5