use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class RealmResource method createInstance.
/**
* {@inheritDoc}
*/
@Override
public Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
String realmPath = realmContext.getResolvedRealm();
ResourceResponse resource;
String parentRealm;
String childRealm;
String realm = null;
try {
hasPermission(context);
final JsonValue jVal = request.getContent();
// get the realm
realm = jVal.get("realm").asString();
if (StringUtils.isBlank(realm)) {
realm = request.getNewResourceId();
}
realm = checkForTopLevelRealm(realm);
if (StringUtils.isBlank(realm)) {
throw new BadRequestException("No realm name provided.");
} else if (!realm.startsWith("/")) {
realm = "/" + realm;
}
if (!realmPath.equalsIgnoreCase("/")) {
// build realm to comply with format if not top level
realm = realmPath + realm;
}
parentRealm = RealmUtils.getParentRealm(realm);
childRealm = RealmUtils.getChildRealm(realm);
OrganizationConfigManager ocm = new OrganizationConfigManager(getSSOToken(), parentRealm);
Map defaultValues = createServicesMap(jVal);
ocm.createSubOrganization(childRealm, defaultValues);
String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
debug.message("RealmResource.createInstance :: CREATE of realm " + childRealm + " in realm " + parentRealm + " performed by " + principalName);
// create a resource for handler to return
OrganizationConfigManager realmCreated = new OrganizationConfigManager(getSSOToken(), realm);
resource = newResourceResponse(childRealm, String.valueOf(System.currentTimeMillis()), createJsonMessage("realmCreated", realmCreated.getOrganizationName()));
return newResultPromise(resource);
} catch (SMSException smse) {
debug.error("RealmResource.createInstance() : Cannot find " + realm, smse);
try {
configureErrorMessage(smse);
return new BadRequestException(smse.getMessage(), smse).asPromise();
} catch (NotFoundException nf) {
debug.error("RealmResource.createInstance() : Cannot find " + realm, nf);
return nf.asPromise();
} catch (ForbiddenException fe) {
// User does not have authorization
debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, fe);
return fe.asPromise();
} catch (PermanentException pe) {
debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, pe);
// Cannot recover from this exception
return pe.asPromise();
} catch (ConflictException ce) {
debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, ce);
return ce.asPromise();
} catch (BadRequestException be) {
debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, be);
return be.asPromise();
} catch (Exception e) {
debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, e);
return new BadRequestException(e.getMessage(), e).asPromise();
}
} catch (SSOException sso) {
debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, sso);
return new PermanentException(401, "Access Denied", null).asPromise();
} catch (ForbiddenException fe) {
debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, fe);
return fe.asPromise();
} catch (BadRequestException be) {
debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, be);
return be.asPromise();
} catch (PermanentException pe) {
debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, pe);
// Cannot recover from this exception
return pe.asPromise();
} catch (Exception e) {
debug.error("RealmResource.createInstance()" + realm + ":" + e);
return new BadRequestException(e.getMessage(), e).asPromise();
}
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class IdentityResourceV2 method attemptResourceCreation.
private Promise<IdentityDetails, ResourceException> attemptResourceCreation(String realm, SSOToken admin, IdentityDetails identity, String resourceId) {
IdentityDetails dtls = null;
try {
// Create the resource
identityServices.create(identity, admin);
// Read created resource
dtls = identityServices.read(resourceId, getIdentityServicesAttributes(realm, objectType), admin);
if (debug.messageEnabled()) {
debug.message("IdentityResource.createInstance() :: Created resourceId={} in realm={} by AdminID={}", resourceId, realm, admin.getTokenID());
}
} catch (final ObjectNotFound notFound) {
debug.error("IdentityResource.createInstance() :: Cannot READ resourceId={} : Resource cannot be found.", resourceId, notFound);
return new NotFoundException("Resource not found.", notFound).asPromise();
} catch (final TokenExpired tokenExpired) {
debug.error("IdentityResource.createInstance() :: Cannot CREATE resourceId={} : Unauthorized", resourceId, tokenExpired);
return new PermanentException(401, "Unauthorized", null).asPromise();
} catch (final NeedMoreCredentials needMoreCredentials) {
debug.error("IdentityResource.createInstance() :: Cannot CREATE resourceId={} : Token is not authorized", resourceId, needMoreCredentials);
return new ForbiddenException("Token is not authorized", needMoreCredentials).asPromise();
} catch (final GeneralAccessDeniedError accessDenied) {
debug.error("IdentityResource.createInstance() :: Cannot CREATE " + accessDenied);
return new ForbiddenException().asPromise();
} catch (GeneralFailure generalFailure) {
debug.error("IdentityResource.createInstance() :: Cannot CREATE " + generalFailure);
return new BadRequestException("Resource cannot be created: " + generalFailure.getMessage(), generalFailure).asPromise();
} catch (AccessDenied accessDenied) {
debug.error("IdentityResource.createInstance() :: Cannot CREATE " + accessDenied);
return new ForbiddenException("Token is not authorized: " + accessDenied.getMessage(), accessDenied).asPromise();
} catch (ResourceException re) {
debug.warning("IdentityResource.createInstance() :: Cannot CREATE resourceId={}", resourceId, re);
return re.asPromise();
} catch (final Exception e) {
debug.error("IdentityResource.createInstance() :: Cannot CREATE resourceId={}", resourceId, e);
return new NotFoundException(e.getMessage(), e).asPromise();
}
return newResultPromise(dtls);
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class SmsRealmProvider method handleCreate.
@Override
public Promise<ResourceResponse, ResourceException> handleCreate(Context serverContext, CreateRequest createRequest) {
final JsonValue jsonContent = createRequest.getContent();
final String realmName = jsonContent.get(REALM_NAME_ATTRIBUTE_NAME).asString();
try {
if (StringUtils.isBlank(realmName)) {
throw new BadRequestException("No realm name provided");
}
if (containsBlacklistedCharacters(realmName)) {
throw new BadRequestException("Realm names cannot contain: " + BLACKLIST_CHARACTERS.toString());
}
RealmContext realmContext = serverContext.asContext(RealmContext.class);
StringBuilder realmPath = new StringBuilder(realmContext.getResolvedRealm());
String location = jsonContent.get(new JsonPointer(PATH_ATTRIBUTE_NAME)).asString();
if (realmPath.length() > 1) {
if (realmPath.charAt(realmPath.length() - 1) != '/' && !location.startsWith("/")) {
realmPath.append('/');
}
realmPath.append(location);
} else {
realmPath = new StringBuilder(location);
}
if (realmPath.charAt(realmPath.length() - 1) != '/') {
realmPath.append('/');
}
realmPath.append(realmName);
String path = realmPath.toString();
String parentRealm = RealmUtils.getParentRealm(path);
String childRealm = RealmUtils.getChildRealm(path);
OrganizationConfigManager realmManager = new OrganizationConfigManager(getUserSsoToken(serverContext), parentRealm);
Map<String, Map<String, Set>> serviceAttributes = new HashMap<>();
serviceAttributes.put(IdConstants.REPO_SERVICE, getAttributeMap(jsonContent));
realmManager.createSubOrganization(childRealm, serviceAttributes);
if (debug.messageEnabled()) {
debug.message("RealmResource.createInstance :: CREATE of realm {} in realm {} performed by {}", childRealm, parentRealm, PrincipalRestUtils.getPrincipalNameFromServerContext(serverContext));
}
JsonValue jsonValue = getJsonValue(path, parentRealm);
return newResultPromise(getResource(jsonValue));
} catch (SMSException e) {
return configureErrorMessage(e).asPromise();
} catch (SSOException sso) {
debug.error("RealmResource.createInstance() : Cannot CREATE " + realmName, sso);
return new PermanentException(401, "Access Denied", null).asPromise();
} catch (BadRequestException fe) {
debug.error("RealmResource.createInstance() : Cannot CREATE " + realmName, fe);
return fe.asPromise();
}
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class SmsRealmProvider method handleUpdate.
@Override
public Promise<ResourceResponse, ResourceException> handleUpdate(Context context, UpdateRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
String realmPath = realmContext.getResolvedRealm();
try {
checkValues(request.getContent());
} catch (BadRequestException e) {
debug.error("RealmResource.updateInstance() : Cannot UPDATE " + realmPath, e);
return new BadRequestException("Invalid attribute values").asPromise();
}
// protect against attempts to change a realm that does not exist as this results in unexpected behaviour
try {
String requestPath = getExpectedPathFromRequestContext(request);
if (!realmPath.equals(requestPath)) {
return new BadRequestException(BAD_REQUEST_REALM_NAME_ERROR_MESSAGE).asPromise();
}
} catch (org.forgerock.oauth2.core.exceptions.NotFoundException e) {
return new BadRequestException(BAD_REQUEST_REALM_NAME_ERROR_MESSAGE).asPromise();
}
final JsonValue realmDetails = request.getContent();
try {
hasPermission(context);
OrganizationConfigManager realmManager = new OrganizationConfigManager(getSSOToken(), realmPath);
realmManager.setAttributes(IdConstants.REPO_SERVICE, getAttributeMap(realmDetails));
final List<Object> newServiceNames = realmDetails.get(SERVICE_NAMES).asList();
if (newServiceNames != null) {
assignServices(realmManager, newServiceNames);
}
debug.message("RealmResource.updateInstance :: UPDATE of realm " + realmPath + " performed by " + PrincipalRestUtils.getPrincipalNameFromServerContext(context));
return newResultPromise(getResource(getJsonValue(realmPath)));
} catch (SMSException e) {
debug.error("RealmResource.updateInstance() : Cannot UPDATE " + realmPath, e);
return configureErrorMessage(e).asPromise();
} catch (SSOException | ForbiddenException | IdRepoException e) {
debug.error("RealmResource.updateInstance() : Cannot UPDATE " + realmPath, e);
return new PermanentException(401, "Access Denied", null).asPromise();
}
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class TokenResource method queryCollection.
@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest queryRequest, QueryResourceHandler handler) {
try {
JsonValue response;
Collection<QueryFilter<CoreTokenField>> query = new ArrayList<QueryFilter<CoreTokenField>>();
//get uid of submitter
AMIdentity uid;
try {
uid = getUid(context);
if (!uid.equals(adminUserId)) {
query.add(QueryFilter.equalTo(USERNAME_FIELD, uid.getName()));
query.add(QueryFilter.equalTo(REALM_FIELD, DNMapper.orgNameToRealmName(uid.getRealm())));
}
} catch (Exception e) {
if (debug.errorEnabled()) {
debug.error("TokenResource :: QUERY : Unable to query collection as no UID discovered " + "for requesting user.");
}
return new PermanentException(401, "Unauthorized", e).asPromise();
}
String id = queryRequest.getQueryId();
String queryString;
if (id.equals("access_token")) {
queryString = "tokenName=access_token";
} else {
queryString = id;
}
String[] constraints = queryString.split(",");
boolean userNamePresent = false;
for (String constraint : constraints) {
String[] params = constraint.split("=");
if (params.length == 2) {
if (OAuthTokenField.USER_NAME.getOAuthField().equals(params[0])) {
userNamePresent = true;
}
query.add(QueryFilter.equalTo(getOAuth2TokenField(params[0]), params[1]));
}
}
if (adminUserId.equals(uid)) {
if (!userNamePresent) {
return new BadRequestException("userName field MUST be set in _queryId").asPromise();
}
} else if (userNamePresent) {
return new BadRequestException("userName field MUST NOT be set in _queryId").asPromise();
}
response = tokenStore.query(QueryFilter.and(query));
return handleResponse(handler, response, context);
} catch (UnauthorizedClientException e) {
debug.error("TokenResource :: QUERY : Unable to query collection as the client is not authorized.", e);
return new PermanentException(401, e.getMessage(), e).asPromise();
} catch (CoreTokenException e) {
debug.error("TokenResource :: QUERY : Unable to query collection as the token store is not available.", e);
return new ServiceUnavailableException(e.getMessage(), e).asPromise();
} catch (InternalServerErrorException e) {
debug.error("TokenResource :: QUERY : Unable to query collection as writing the response failed.", e);
return e.asPromise();
} catch (NotFoundException e) {
debug.error("TokenResource :: QUERY : Unable to query collection as realm does not have OAuth 2 provider.", e);
return e.asPromise();
}
}
Aggregations