use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class ClientResource method createInstance.
public Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest createRequest) {
String principal = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
Map<String, String> responseVal = new HashMap<String, String>();
try {
if (serviceSchema == null || serviceSchemaManager == null) {
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": No serviceSchema available.");
}
throw new PermanentException(ResourceException.INTERNAL_ERROR, "", null);
}
Map<String, ArrayList<String>> client = (Map<String, ArrayList<String>>) createRequest.getContent().getObject();
String realm = null;
if (client == null || client.isEmpty()) {
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": No client definition.");
}
throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client definition", null);
}
//check for id
String id = createRequest.getNewResourceId();
if (client.containsKey(OAuth2Constants.OAuth2Client.CLIENT_ID)) {
ArrayList<String> idList = client.remove(OAuth2Constants.OAuth2Client.CLIENT_ID);
if (idList != null && !idList.isEmpty()) {
id = idList.iterator().next();
}
}
if (id == null || id.isEmpty()) {
debug.error("ClientResource :: CREATE by " + principal + ": No client ID.");
throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client id", null);
}
//get realm
if (client.containsKey(OAuth2Constants.OAuth2Client.REALM)) {
ArrayList<String> realmList = client.remove(OAuth2Constants.OAuth2Client.REALM);
if (realmList != null && !realmList.isEmpty()) {
realm = realmList.iterator().next();
}
}
//check for required parameters
if (!client.containsKey(OAuth2Constants.OAuth2Client.USERPASSWORD) || client.get(OAuth2Constants.OAuth2Client.USERPASSWORD).iterator().next().isEmpty()) {
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": " + "Resource ID: " + id + ": No user password.");
}
throw new PermanentException(ResourceException.BAD_REQUEST, "Missing user password", null);
}
if (client.containsKey(OAuth2Constants.OAuth2Client.CLIENT_TYPE)) {
String type = client.get(OAuth2Constants.OAuth2Client.CLIENT_TYPE).iterator().next();
if (!(type.equals("Confidential") || type.equals("Public"))) {
debug.error("ClientResource :: CREATE by " + principal + ": " + "Resource ID: " + id + ": No client type.");
throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client type", null);
}
} else {
debug.error("ClientResource :: CREATE by" + principal + ": " + "Resource ID: " + id + ": No client type.");
throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client type", null);
}
Map<String, Set<String>> attrs = new HashMap<String, Set<String>>();
for (Map.Entry mapEntry : client.entrySet()) {
List<String> list = (ArrayList) mapEntry.getValue();
Set<String> set = new HashSet<String>();
if (isSingle((String) mapEntry.getKey())) {
set.add((String) ((ArrayList) mapEntry.getValue()).get(0));
} else {
for (int i = 0; i < list.size(); i++) {
set.add("[" + i + "]=" + list.get(i));
}
}
attrs.put((String) mapEntry.getKey(), set);
}
Set<String> temp = new HashSet<String>();
temp.add("OAuth2Client");
attrs.put("AgentType", temp);
temp = new HashSet<String>();
temp.add("Active");
attrs.put("sunIdentityServerDeviceStatus", temp);
manager.createIdentity(realm, id, attrs);
responseVal.put("success", "true");
JsonValue response = new JsonValue(responseVal);
ResourceResponse resource = newResourceResponse("results", String.valueOf(System.currentTimeMillis()), response);
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "CREATED_CLIENT", responseVal.toString() };
auditLogger.logAccessMessage("CREATED_CLIENT", obs, null);
}
return newResultPromise(resource);
} catch (IdRepoException e) {
responseVal.put("success", "false");
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
}
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to " + "IdRepo exception.", e);
}
return new InternalServerErrorException("Unable to create client", e).asPromise();
} catch (SSOException e) {
responseVal.put("success", "false");
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
}
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to " + "SSO exception.", e);
}
return new InternalServerErrorException("Unable to create client", e).asPromise();
} catch (PermanentException e) {
responseVal.put("success", "false");
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
}
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to exception.", e);
}
return e.asPromise();
} catch (org.forgerock.json.resource.BadRequestException e) {
responseVal.put("success", "false");
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
}
debug.error("ClientResource :: CREATE : Unable to create client due to Bad Request.", e);
return e.asPromise();
}
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class TokenResource method deleteToken.
/**
* Deletes the token with the provided token id.
*
* @param context The context.
* @param tokenId The token id.
* @param deleteRefreshToken Whether to delete associated refresh token, if token id is for an access token.
* @return {@code Void} if the token has been deleted.
*/
private Promise<Void, ResourceException> deleteToken(Context context, String tokenId, boolean deleteRefreshToken) {
try {
AMIdentity uid = getUid(context);
JsonValue token = tokenStore.read(tokenId);
if (token == null) {
if (debug.errorEnabled()) {
debug.error("TokenResource :: DELETE : No token with ID, " + tokenId + " found to delete");
}
throw new NotFoundException("Token Not Found", null);
}
String username = getAttributeValue(token, USERNAME);
if (username == null || username.isEmpty()) {
if (debug.errorEnabled()) {
debug.error("TokenResource :: DELETE : No username associated with " + "token with ID, " + tokenId + ".");
}
throw new PermanentException(HttpURLConnection.HTTP_NOT_FOUND, "Not Found", null);
}
String grantType = getAttributeValue(token, GRANT_TYPE);
if (grantType != null && grantType.equalsIgnoreCase(CLIENT_CREDENTIALS)) {
if (deleteRefreshToken) {
deleteAccessTokensRefreshToken(token);
}
tokenStore.delete(tokenId);
} else {
String realm = getAttributeValue(token, REALM);
AMIdentity uid2 = identityManager.getResourceOwnerIdentity(username, realm);
if (uid.equals(uid2) || uid.equals(adminUserId)) {
if (deleteRefreshToken) {
deleteAccessTokensRefreshToken(token);
}
tokenStore.delete(tokenId);
} else {
if (debug.errorEnabled()) {
debug.error("TokenResource :: DELETE : Only the resource owner or an administrator may perform " + "a delete on the token with ID, " + tokenId + ".");
}
throw new PermanentException(401, "Unauthorized", null);
}
}
return newResultPromise(null);
} catch (CoreTokenException e) {
return new ServiceUnavailableException(e.getMessage(), e).asPromise();
} catch (ResourceException e) {
return e.asPromise();
} catch (SSOException e) {
debug.error("TokenResource :: DELETE : Unable to retrieve identity of the requesting user. Unauthorized.");
return new PermanentException(401, "Unauthorized", e).asPromise();
} catch (IdRepoException e) {
debug.error("TokenResource :: DELETE : Unable to retrieve identity of the requesting user. Unauthorized.");
return new PermanentException(401, "Unauthorized", e).asPromise();
} catch (UnauthorizedClientException e) {
debug.error("TokenResource :: DELETE : Requesting user is unauthorized.");
return new PermanentException(401, "Unauthorized", e).asPromise();
}
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class XMLResourceExceptionHandler method write.
@Override
public void write(MessageContext context, AuthenticationException exception) {
Reject.ifNull(exception);
try {
ResourceException jre;
if (exception instanceof AuthenticationFailedException) {
jre = new PermanentException(Status.UNAUTHORIZED.getCode(), exception.getMessage(), null);
} else if (exception.getCause() instanceof ResourceException) {
jre = (ResourceException) exception.getCause();
} else {
LOGGER.error(exception.getMessage(), exception);
jre = new InternalServerErrorException("Authentication Failed", exception);
}
AuditTrail auditTrail = context.getAuditTrail();
List<Map<String, Object>> failureReasonList = auditTrail.getFailureReasons();
if (failureReasonList != null && !failureReasonList.isEmpty()) {
jre.setDetail(json(object(field("failureReasons", failureReasonList))));
}
Response response = context.getResponse();
response.setStatus(Status.valueOf(jre.getCode()));
context.<Response>getResponse().getHeaders().put(ContentTypeHeader.valueOf(MediaType.XML_UTF_8.toString()));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Transformer transformer = XMLUtils.getTransformerFactory().newTransformer();
transformer.transform(new DOMSource(asXMLDOM(jre.includeCauseInJsonValue().toJsonValue().asMap())), new StreamResult(outputStream));
response.getEntity().setBytes(outputStream.toByteArray());
} catch (TransformerException e1) {
throw new IllegalStateException("Could not write XML to response", e1);
}
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class SmsRealmProvider method handleDelete.
@Override
public Promise<ResourceResponse, ResourceException> handleDelete(Context serverContext, DeleteRequest request) {
RealmContext realmContext = serverContext.asContext(RealmContext.class);
String realmPath = realmContext.getResolvedRealm();
try {
OrganizationConfigManager realmManager = new OrganizationConfigManager(getSSOToken(), realmPath);
final ResourceResponse resource = getResource(getJsonValue(realmPath));
realmManager.deleteSubOrganization(null, false);
String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(serverContext);
debug.message("RealmResource.deleteInstance :: DELETE of realm " + realmPath + " performed by " + principalName);
return newResultPromise(resource);
} catch (SMSException smse) {
ResourceException exception = configureErrorMessage(smse);
if (exception instanceof NotFoundException) {
debug.warning("RealmResource.deleteInstance() : Cannot find {}", realmPath, smse);
return exception.asPromise();
} else if (exception instanceof ForbiddenException || exception instanceof PermanentException || exception instanceof ConflictException || exception instanceof BadRequestException) {
debug.warning("RealmResource.deleteInstance() : Cannot DELETE {}", realmPath, smse);
return exception.asPromise();
} else {
return new BadRequestException(exception.getMessage(), exception).asPromise();
}
} catch (Exception e) {
return new BadRequestException(e.getMessage(), e).asPromise();
}
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class SmsRealmProvider method handleRead.
@Override
public Promise<ResourceResponse, ResourceException> handleRead(Context context, ReadRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
String realmPath = realmContext.getResolvedRealm();
if (!request.getResourcePath().isEmpty()) {
//if the resource path is not empty, the realm has not resolved correctly
return new NotFoundException("Realm \"" + RealmUtils.concatenateRealmPath(RealmUtils.cleanRealm(realmPath), RealmUtils.cleanRealm(request.getResourcePath())) + "\" is not a valid realm.").asPromise();
}
try {
JsonValue jsonResponse = getJsonValue(realmPath);
if (debug.messageEnabled()) {
debug.message("RealmResource.readInstance :: READ : Successfully read realm, " + realmPath + " performed by " + PrincipalRestUtils.getPrincipalNameFromServerContext(context));
}
return newResultPromise(getResource(jsonResponse));
} catch (SMSException smse) {
ResourceException exception = configureErrorMessage(smse);
if (exception instanceof NotFoundException) {
debug.warning("RealmResource.readInstance() : Cannot find {}", realmPath, smse);
return exception.asPromise();
} else if (exception instanceof ForbiddenException || exception instanceof PermanentException || exception instanceof ConflictException || exception instanceof BadRequestException) {
debug.warning("RealmResource.readInstance() : Cannot READ {}", realmPath, smse);
return exception.asPromise();
} else {
return new BadRequestException(exception.getMessage(), exception).asPromise();
}
} catch (Exception e) {
return new BadRequestException(e.getMessage(), e).asPromise();
}
}
Aggregations