use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project carbon-identity-framework by wso2.
the class ChallengeQuestionProcessor method setChallengesOfUser.
/**
* @param userName
* @param tenantId
* @param challengesDTOs
* @throws IdentityException
*/
public void setChallengesOfUser(String userName, int tenantId, UserChallengesDTO[] challengesDTOs) throws IdentityException {
try {
if (log.isDebugEnabled()) {
log.debug("Challenge Question from the user profile.");
}
List<String> challengesUris = new ArrayList<String>();
String challengesUrisValue = "";
String separator = IdentityMgtConfig.getInstance().getChallengeQuestionSeparator();
Map<String, String> oldClaims = new HashMap<String, String>();
Map<String, String> newClaims = new HashMap<String, String>();
String[] requestclaims = new String[challengesDTOs.length];
int x = 0;
for (UserChallengesDTO claimDto : challengesDTOs) {
requestclaims[x++] = claimDto.getId();
}
// Getting user store manager here to reduce the calls for claim retrieval.
// TODO need to put into a new method in a new release version. Used to avoid API changes in patch.
org.wso2.carbon.user.core.UserStoreManager userStoreManager = null;
RealmService realmService = IdentityMgtServiceComponent.getRealmService();
try {
if (realmService.getTenantUserRealm(tenantId) != null) {
userStoreManager = (org.wso2.carbon.user.core.UserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager();
}
} catch (Exception e) {
String msg = "Error retrieving the user store manager for the tenant";
log.error(msg, e);
throw IdentityException.error(msg, e);
}
if (userStoreManager != null) {
oldClaims = userStoreManager.getUserClaimValues(userName, requestclaims, null);
}
if (!ArrayUtils.isEmpty(challengesDTOs)) {
for (UserChallengesDTO dto : challengesDTOs) {
if (dto.getId() != null && dto.getQuestion() != null && dto.getAnswer() != null) {
String oldClaimValue = oldClaims.get(dto.getId());
if ((oldClaimValue != null) && oldClaimValue.contains(separator)) {
String oldAnswer = oldClaimValue.split(separator)[1];
if (!oldAnswer.trim().equals(dto.getAnswer().trim())) {
String claimValue = dto.getQuestion().trim() + separator + Utils.doHash(dto.getAnswer().trim().toLowerCase());
if (!oldClaimValue.equals(claimValue)) {
newClaims.put(dto.getId().trim(), claimValue);
}
}
} else {
String claimValue = dto.getQuestion().trim() + separator + Utils.doHash(dto.getAnswer().trim().toLowerCase());
newClaims.put(dto.getId().trim(), claimValue);
}
challengesUris.add(dto.getId().trim());
}
}
for (String challengesUri : challengesUris) {
if ("".equals(challengesUrisValue)) {
challengesUrisValue = challengesUri;
} else {
challengesUrisValue = challengesUrisValue + IdentityMgtConfig.getInstance().getChallengeQuestionSeparator() + challengesUri;
}
}
newClaims.put("http://wso2.org/claims/challengeQuestionUris", challengesUrisValue);
// Single call to save all challenge questions.
userStoreManager.setUserClaimValues(userName, newClaims, UserCoreConstants.DEFAULT_PROFILE);
}
} catch (org.wso2.carbon.user.api.UserStoreException e) {
String msg = "No associated challenge question found for the user";
throw IdentityException.error(msg, e);
}
}
use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project carbon-mediation by wso2.
the class OpenAPIProcessor method getUpdatedSwaggerFromApi.
/**
* Update a given swagger definition of the Synapse API.
*
* @param existingSwagger swagger definition needs to be updated.
* @param isJSONIn input swagger data type JSON / YAML.
* @param isJSONOut output swagger data type JSON / YAML.
* @return updated swagger definition as string.
*/
public String getUpdatedSwaggerFromApi(String existingSwagger, boolean isJSONIn, boolean isJSONOut) throws APIGenException {
if (api == null) {
throw new APIGenException("Provided API is null");
}
if (StringUtils.isEmpty(existingSwagger)) {
throw new APIGenException("Provided swagger definition is empty");
}
if (isJSONIn) {
JsonNode jsonNodeTree = null;
try {
jsonNodeTree = new ObjectMapper().readTree(existingSwagger);
existingSwagger = new YAMLMapper().writeValueAsString(jsonNodeTree);
} catch (JsonProcessingException e) {
throw new APIGenException("Error occurred while converting the swagger to YAML format", e);
}
}
OpenAPIV3Parser apiv3Parser = new OpenAPIV3Parser();
SwaggerParseResult swaggerParseResult = apiv3Parser.readContents(existingSwagger);
OpenAPI openAPI = swaggerParseResult.getOpenAPI();
Paths paths = openAPI.getPaths();
Paths newPaths = new Paths();
final Map<String, Object> dataMap = GenericApiObjectDefinition.getPathMap(api);
for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
boolean pathItemExists = false;
PathItem pathItem;
if (paths.containsKey(entry.getKey())) {
pathItem = paths.get(entry.getKey());
pathItemExists = true;
} else {
pathItem = new PathItem();
}
Map<String, Object> methodMap = (Map<String, Object>) entry.getValue();
List<String> newMethodsList = new ArrayList<>();
for (Map.Entry<String, Object> methodEntry : methodMap.entrySet()) {
Operation operation = null;
boolean operationExists = false;
if (pathItemExists) {
newMethodsList.add(methodEntry.getKey());
switch(methodEntry.getKey()) {
case OPERATION_HTTP_GET:
operation = pathItem.getGet();
break;
case OPERATION_HTTP_POST:
operation = pathItem.getPost();
break;
case OPERATION_HTTP_DELETE:
operation = pathItem.getDelete();
break;
case OPERATION_HTTP_PUT:
operation = pathItem.getPut();
break;
case OPERATION_HTTP_HEAD:
operation = pathItem.getHead();
break;
case OPERATION_HTTP_PATCH:
operation = pathItem.getPatch();
break;
case OPERATION_HTTP_OPTIONS:
operation = pathItem.getOptions();
}
}
if (operation == null) {
operation = new Operation();
} else {
operationExists = true;
}
Object[] paramArr = (Object[]) ((Map<String, Object>) methodEntry.getValue()).get(PARAMETERS);
if (operationExists) {
List<Parameter> parameters = operation.getParameters();
List<Parameter> newParameter = new ArrayList<>();
if (paramArr != null && paramArr.length > 0) {
for (Object o : paramArr) {
String paramType = (String) ((Map<String, Object>) o).get(PARAMETER_IN);
String paramName = (String) ((Map<String, Object>) o).get(PARAMETER_NAME);
Optional<Parameter> existing = null;
switch(paramType) {
case PARAMETER_IN_PATH:
existing = parameters.stream().filter(c -> c.getName().equals(paramName) && c instanceof PathParameter).findFirst();
break;
case PARAMETER_IN_QUERY:
existing = parameters.stream().filter(c -> c.getName().equals(paramName) && c instanceof QueryParameter).findFirst();
break;
}
if (existing == null || !existing.isPresent()) {
// if we found parameter do not update
updatePathQueryAndBodyParams(operation, paramType, paramName, newParameter);
} else {
newParameter.add(existing.get());
}
updateDefaultResponseAndPathItem(pathItem, operation, methodEntry, operationExists);
}
} else {
// no parameters defined ( default resource in the API )
updateDefaultResponseAndPathItem(pathItem, operation, methodEntry, operationExists);
}
// remove deleted parameters from swagger
if (newParameter.size() > 0) {
parameters.removeIf(c -> !newParameter.contains(c));
}
} else {
populateParameters(pathItem, methodMap);
}
}
if (pathItemExists) {
// Remove additional methods
List<String> allMethodsList = Arrays.asList(new String[] { "get", "post", "put", "delete", "head", "options", "patch" });
List<String> differences = allMethodsList.stream().filter(element -> !newMethodsList.contains(element)).collect(Collectors.toList());
for (String method : differences) {
switch(method) {
case OPERATION_HTTP_GET:
pathItem.setGet(null);
break;
case OPERATION_HTTP_POST:
pathItem.setPost(null);
break;
case OPERATION_HTTP_DELETE:
pathItem.setDelete(null);
break;
case OPERATION_HTTP_PUT:
pathItem.setPut(null);
break;
case OPERATION_HTTP_HEAD:
pathItem.setHead(null);
break;
case OPERATION_HTTP_PATCH:
pathItem.setPatch(null);
break;
case OPERATION_HTTP_OPTIONS:
pathItem.setOptions(null);
break;
}
}
}
newPaths.put(entry.getKey(), pathItem);
}
// Adding the new path map
openAPI.setPaths(newPaths);
updateInfoSection(openAPI);
try {
updateServersSection(openAPI);
} catch (AxisFault axisFault) {
throw new APIGenException("Error occurred while getting host details", axisFault);
}
try {
if (isJSONOut) {
return Json.mapper().writeValueAsString(openAPI);
}
return Yaml.mapper().writeValueAsString(openAPI);
} catch (JsonProcessingException e) {
throw new APIGenException("Error occurred while creating the output JAML/JSON", e);
}
}
use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project carbon-mediation by wso2.
the class CacheMediatorFactory method createSpecificMediator.
/**
* {@inheritDoc}
*/
protected Mediator createSpecificMediator(OMElement elem, Properties properties) {
if (!CachingConstants.CACHE_Q.equals(elem.getQName())) {
handleException("Unable to create the cache mediator. Unexpected element as the cache mediator configuration");
}
CacheMediator cache = new CacheMediator(cacheManager);
OMAttribute collectorAttr = elem.getAttribute(ATT_COLLECTOR);
if (collectorAttr != null && collectorAttr.getAttributeValue() != null) {
if ("true".equals(collectorAttr.getAttributeValue())) {
cache.setCollector(true);
OMAttribute scopeAttribute = elem.getAttribute(ATT_SCOPE);
if (scopeAttribute != null && scopeAttribute.getAttributeValue() != null) {
cache.setScope(scopeAttribute.getAttributeValue().trim());
}
} else if ("false".equals(collectorAttr.getAttributeValue())) {
cache.setCollector(false);
OMAttribute timeoutAttr = elem.getAttribute(ATT_TIMEOUT);
if (timeoutAttr != null && timeoutAttr.getAttributeValue() != null) {
cache.setTimeout(Long.parseLong(timeoutAttr.getAttributeValue().trim()));
} else {
cache.setTimeout(CachingConstants.DEFAULT_TIMEOUT);
}
OMAttribute maxMessageSizeAttr = elem.getAttribute(ATT_MAX_MSG_SIZE);
if (maxMessageSizeAttr != null && maxMessageSizeAttr.getAttributeValue() != null) {
cache.setMaxMessageSize(Integer.parseInt(maxMessageSizeAttr.getAttributeValue().trim()));
} else {
cache.setMaxMessageSize(-1);
}
OMAttribute idAttribute = elem.getAttribute(ATT_ID);
if (idAttribute != null && idAttribute.getAttributeValue() != null) {
cache.setId(idAttribute.getAttributeValue().trim());
}
OMAttribute hashGeneratorAttribute = elem.getAttribute(ATT_HASH_GENERATOR);
if (hashGeneratorAttribute != null && hashGeneratorAttribute.getAttributeValue() != null) {
cache.setHashGenerator(hashGeneratorAttribute.getAttributeValue().trim());
}
OMAttribute scopeAttribute = elem.getAttribute(ATT_SCOPE);
if (scopeAttribute != null && scopeAttribute.getAttributeValue() != null) {
cache.setScope(scopeAttribute.getAttributeValue().trim());
}
String className = null;
OMElement protocolElem = elem.getFirstChildWithName(PROTOCOL_Q);
Map<String, Object> props = new HashMap<>();
if (protocolElem != null) {
OMAttribute typeAttr = protocolElem.getAttribute(ATT_TYPE);
if (typeAttr != null && typeAttr.getAttributeValue() != null) {
OMElement hashGeneratorElem = protocolElem.getFirstChildWithName(HASH_GENERATOR_Q);
if (hashGeneratorElem != null) {
className = hashGeneratorElem.getText();
}
String protocolType = typeAttr.getAttributeValue().toUpperCase().trim();
cache.setProtocolType(protocolType);
if (CachingConstants.HTTP_PROTOCOL_TYPE.equals(protocolType)) {
OMElement methodElem = protocolElem.getFirstChildWithName(HTTP_METHODS_TO_CACHE_Q);
if (methodElem != null) {
String[] methods = methodElem.getText().split(",");
if (!"".equals(methods[0])) {
for (int i = 0; i < methods.length; i++) {
methods[i] = methods[i].toUpperCase().trim();
if (!(PassThroughConstants.HTTP_POST.equals(methods[i]) || PassThroughConstants.HTTP_GET.equals(methods[i]) || PassThroughConstants.HTTP_HEAD.equals(methods[i]) || PassThroughConstants.HTTP_PUT.equals(methods[i]) || PassThroughConstants.HTTP_DELETE.equals(methods[i]) || PassThroughConstants.HTTP_OPTIONS.equals(methods[i]) || PassThroughConstants.HTTP_CONNECT.equals(methods[i]) || "PATCH".equals(methods[i]) || CachingConstants.ALL.equals(methods[i]))) {
handleException("Unexpected method type: " + methods[i]);
}
}
cache.setHTTPMethodsToCache(methods);
}
} else {
cache.setHTTPMethodsToCache(CachingConstants.ALL);
}
OMElement headersToIncludeInHash = protocolElem.getFirstChildWithName(HEADERS_TO_INCLUDE_IN_HASH_Q);
if (headersToIncludeInHash != null) {
String[] headers = headersToIncludeInHash.getText().split(",");
for (int i = 0; i < headers.length; i++) {
headers[i] = headers[i].trim();
}
cache.setHeadersToIncludeInHash(headers);
} else {
cache.setHeadersToIncludeInHash("");
}
OMElement headersToExcludeInHash = protocolElem.getFirstChildWithName(HEADERS_TO_EXCLUDE_IN_HASH_Q);
if (headersToExcludeInHash != null) {
String[] headers = headersToExcludeInHash.getText().split(",");
for (int i = 0; i < headers.length; i++) {
headers[i] = headers[i].trim();
}
cache.setHeadersToExcludeInHash(headers);
} else {
cache.setHeadersToExcludeInHash("");
}
OMElement responseCodesElem = protocolElem.getFirstChildWithName(RESPONSE_CODES_Q);
if (responseCodesElem != null) {
String responses = responseCodesElem.getText();
if (!"".equals(responses) && responses != null) {
cache.setResponseCodes(responses);
}
} else {
cache.setResponseCodes(CachingConstants.ANY_RESPONSE_CODE);
}
OMElement enableCacheControlElem = protocolElem.getFirstChildWithName(ENABLE_CACHE_CONTROL_Q);
if (enableCacheControlElem != null) {
String cacheControlElemText = enableCacheControlElem.getText();
if (StringUtils.isNotEmpty(cacheControlElemText)) {
cache.setCacheControlEnabled(Boolean.parseBoolean(cacheControlElemText));
}
} else {
cache.setCacheControlEnabled(CachingConstants.DEFAULT_ENABLE_CACHE_CONTROL);
}
OMElement addAgeHeaderElem = protocolElem.getFirstChildWithName(INCLUDE_AGE_HEADER_Q);
if (addAgeHeaderElem != null) {
String addAgeHeaderElemText = addAgeHeaderElem.getText();
if (StringUtils.isNotEmpty(addAgeHeaderElemText)) {
cache.setAddAgeHeaderEnabled(Boolean.parseBoolean(addAgeHeaderElemText));
}
} else {
cache.setCacheControlEnabled(CachingConstants.DEFAULT_ADD_AGE_HEADER);
}
props.put(CachingConstants.INCLUDED_HEADERS_PROPERTY, cache.getHeadersToIncludeInHash());
props.put(CachingConstants.EXCLUDED_HEADERS_PROPERTY, cache.getHeadersToExcludeInHash());
}
} else {
cache.setProtocolType(CachingConstants.HTTP_PROTOCOL_TYPE);
}
} else {
OMAttribute hashGeneratorAttr = elem.getAttribute(ATT_HASH_GENERATOR);
if (hashGeneratorAttr != null && hashGeneratorAttr.getAttributeValue() != null) {
className = hashGeneratorAttr.getAttributeValue();
}
}
if (className != null && !"".equals(className)) {
try {
Class generator = Class.forName(className);
Object o = generator.newInstance();
if (o instanceof DigestGenerator) {
cache.setDigestGenerator((DigestGenerator) o);
} else {
handleException("Specified class for the hashGenerator is not a " + "DigestGenerator. It *must* implement " + "org.wso2.carbon.mediator.cache.digest.DigestGenerator interface");
}
} catch (ClassNotFoundException e) {
handleException("Unable to load the hash generator class", e);
} catch (IllegalAccessException e) {
handleException("Unable to access the hash generator class", e);
} catch (InstantiationException e) {
handleException("Unable to instantiate the hash generator class", e);
}
} else {
cache.setDigestGenerator(CachingConstants.DEFAULT_HASH_GENERATOR);
}
props.put(CachingConstants.PERMANENTLY_EXCLUDED_HEADERS_STRING, CachingConstants.PERMANENTLY_EXCLUDED_HEADERS);
cache.getDigestGenerator().init(props);
OMElement onCacheHitElem = elem.getFirstChildWithName(ON_CACHE_HIT_Q);
if (onCacheHitElem != null) {
OMAttribute sequenceAttr = onCacheHitElem.getAttribute(ATT_SEQUENCE);
if (sequenceAttr != null && sequenceAttr.getAttributeValue() != null) {
cache.setOnCacheHitRef(sequenceAttr.getAttributeValue());
} else if (onCacheHitElem.getFirstElement() != null) {
cache.setOnCacheHitSequence(new SequenceMediatorFactory().createAnonymousSequence(onCacheHitElem, properties));
}
} else {
cache.setOnCacheHitRef(null);
cache.setOnCacheHitSequence(null);
}
OMElement implElem = elem.getFirstChildWithName(IMPLEMENTATION_Q);
if (implElem != null) {
OMAttribute sizeAttr = implElem.getAttribute(ATT_SIZE);
if (sizeAttr != null && sizeAttr.getAttributeValue() != null) {
cache.setInMemoryCacheSize(Integer.parseInt(sizeAttr.getAttributeValue().trim()));
} else {
cache.setInMemoryCacheSize(-1);
}
OMAttribute typeAttribute = implElem.getAttribute(ATT_TYPE);
if (typeAttribute != null && typeAttribute.getAttributeValue() != null) {
cache.setImplementationType(typeAttribute.getAttributeValue().trim());
}
}
} else {
handleException("The value for collector has to be either true or false");
}
} else {
handleException("The collector attribute must be specified");
}
addAllCommentChildrenToList(elem, cache.getCommentsList());
return cache;
}
use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project product-is by wso2.
the class SCIM2UserTestCase method testUpdateUserWhenExternalClaimDeleted.
@Test(dependsOnMethods = "testGetUser")
public void testUpdateUserWhenExternalClaimDeleted() throws Exception {
AutomationContext context = new AutomationContext("IDENTITY", testUserMode);
backendURL = context.getContextUrls().getBackEndUrl();
loginLogoutClient = new LoginLogoutClient(context);
sessionCookie = loginLogoutClient.login();
HttpPost postRequest = new HttpPost(getPath());
postRequest.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
postRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
JSONObject rootObject = new JSONObject();
JSONArray schemas = new JSONArray();
rootObject.put(SCHEMAS_ATTRIBUTE, schemas);
JSONObject names = new JSONObject();
names.put(FAMILY_NAME_ATTRIBUTE, "udaranga");
names.put(GIVEN_NAME_ATTRIBUTE, "buddhima");
rootObject.put(NAME_ATTRIBUTE, names);
rootObject.put(USER_NAME_ATTRIBUTE, "wso2is");
JSONObject emailWork = new JSONObject();
emailWork.put(TYPE_PARAM, EMAIL_TYPE_WORK_ATTRIBUTE);
emailWork.put(VALUE_PARAM, EMAIL_TYPE_WORK_CLAIM_VALUE);
JSONObject emailHome = new JSONObject();
emailHome.put(TYPE_PARAM, EMAIL_TYPE_HOME_ATTRIBUTE);
emailHome.put(VALUE_PARAM, EMAIL_TYPE_HOME_CLAIM_VALUE);
JSONArray emails = new JSONArray();
emails.add(emailWork);
emails.add(emailHome);
rootObject.put(EMAILS_ATTRIBUTE, emails);
rootObject.put(PASSWORD_ATTRIBUTE, PASSWORD);
StringEntity entity = new StringEntity(rootObject.toString());
postRequest.setEntity(entity);
HttpResponse postResponse = client.execute(postRequest);
assertEquals(postResponse.getStatusLine().getStatusCode(), 201, "User has not been created in patch process successfully.");
Object responseObj = JSONValue.parse(EntityUtils.toString(postResponse.getEntity()));
EntityUtils.consume(postResponse.getEntity());
String userId = ((JSONObject) responseObj).get(ID_ATTRIBUTE).toString();
assertNotNull(userId);
String userResourcePath = getPath() + "/" + userId;
claimMetadataManagementServiceClient = new ClaimMetadataManagementServiceClient(backendURL, sessionCookie);
claimMetadataManagementServiceClient.removeExternalClaim("urn:ietf:params:scim:schemas:core:2.0:User", "urn:ietf:params:scim:schemas:core:2.0:User:name.honorificSuffix");
HttpPatch request = new HttpPatch(userResourcePath);
StringEntity params = new StringEntity("{\"schemas\":[\"urn:ietf:params:scim:api:messages:2.0:PatchOp\"]," + "\"Operations\":[{\"op\":\"replace\",\"path\":\"name\",\"value\":{\"givenName\":\"mahela\"," + "\"familyName\":\"jayaxxxx\"}}]}");
request.setEntity(params);
request.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
HttpResponse response = client.execute(request);
assertEquals(response.getStatusLine().getStatusCode(), 200, "User has not been updated successfully.");
Object responseObjAfterPatch = JSONValue.parse(EntityUtils.toString(response.getEntity()));
EntityUtils.consume(response.getEntity());
String updatedGivenName = ((JSONObject) responseObjAfterPatch).get(NAME_ATTRIBUTE).toString();
assertTrue(updatedGivenName.contains("mahela"));
}
use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project product-is by wso2.
the class SCIM2CustomSchemaUserTestCase method testPatchRemoveUserAttributes.
@Test(dependsOnMethods = "testPatchReplaceUserAttributes", description = "Tests patch remove operation for custom" + " schema attributes with /Users api.")
public void testPatchRemoveUserAttributes() throws Exception {
String body = readResource("scim2-custom-schema-patch-remove-attribute.json");
Response response = getResponseOfPatch(userIdEndpointURL, body, SCIM_CONTENT_TYPE);
ExtractableResponse<Response> extractableResponse = response.then().log().ifValidationFails().assertThat().statusCode(HttpStatus.SC_OK).and().assertThat().header(HttpHeaders.CONTENT_TYPE, SCIM_CONTENT_TYPE).extract();
Assert.assertNotNull(extractableResponse);
Object customSchema = extractableResponse.path(CUSTOM_SCHEMA_URI_WITH_ESCAPE_CHARS);
assertNotNull(customSchema);
Object country = ((LinkedHashMap) customSchema).get(COUNTRY_CLAIM_ATTRIBUTE_NAME);
assertNull(country);
LinkedHashMap manager = (LinkedHashMap) ((LinkedHashMap) customSchema).get(MANAGER_CLAIM_ATTRIBUTE_NAME);
assertNotNull(manager);
String managerEMail = manager.get(MANAGER_EMAIL_CLAIM_ATTRIBUTE_NAME).toString();
assertEquals(managerEMail, MANAGER_EMAIL_LOCAL_CLAIM_VALUE_AFTER_REPLACE);
}
Aggregations