use of com.sun.identity.idsvcs.GeneralFailure in project OpenAM by OpenRock.
the class IdentityServicesImpl method read.
public IdentityDetails read(String name, Map<String, Set<String>> attributes, SSOToken admin) throws IdServicesException {
IdentityDetails rv = null;
String realm = null;
String repoRealm;
String identityType = null;
List<String> attrsToGet = null;
if (attributes != null) {
for (Attribute attr : asAttributeArray(attributes)) {
String attrName = attr.getName();
if ("realm".equalsIgnoreCase(attrName)) {
String[] values = attr.getValues();
if (values != null && values.length > 0) {
realm = values[0];
}
} else if ("objecttype".equalsIgnoreCase(attrName)) {
String[] values = attr.getValues();
if (values != null && values.length > 0) {
identityType = values[0];
}
} else {
if (attrsToGet == null) {
attrsToGet = new ArrayList<>();
}
attrsToGet.add(attrName);
}
}
}
if (StringUtils.isEmpty(realm)) {
repoRealm = "/";
} else {
repoRealm = realm;
}
if (StringUtils.isEmpty(identityType)) {
identityType = "User";
}
try {
AMIdentity amIdentity = getAMIdentity(admin, identityType, name, repoRealm);
if (amIdentity == null) {
debug.error("IdentityServicesImpl:read identity not found");
throw new ObjectNotFound(name);
}
if (isSpecialUser(amIdentity)) {
throw new AccessDenied("Cannot retrieve attributes for this user.");
}
rv = convertToIdentityDetails(amIdentity, attrsToGet);
if (!StringUtils.isEmpty(realm)) {
// use the realm specified by the request
rv.setRealm(realm);
}
} catch (IdRepoException e) {
debug.error("IdentityServicesImpl:read", e);
mapIdRepoException(e);
} catch (SSOException e) {
debug.error("IdentityServicesImpl:read", e);
throw new GeneralFailure(e.getMessage());
}
return rv;
}
use of com.sun.identity.idsvcs.GeneralFailure in project OpenAM by OpenRock.
the class IdentityResourceV1 method readInstance.
/**
* {@inheritDoc}
*/
@Override
public Promise<ResourceResponse, ResourceException> readInstance(final Context context, final String resourceId, final ReadRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
final String realm = realmContext.getResolvedRealm();
IdentityDetails dtls;
try {
SSOToken admin = getSSOToken(getCookieFromServerContext(context));
dtls = identityServices.read(resourceId, getIdentityServicesAttributes(realm), admin);
String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
debug.message("IdentityResource.readInstance :: READ of resourceId={} in realm={} performed by " + "principalName={}", resourceId, realm, principalName);
return newResultPromise(buildResourceResponse(resourceId, context, dtls));
} catch (final NeedMoreCredentials needMoreCredentials) {
debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={} : User does not have enough " + "privileges.", resourceId, needMoreCredentials);
return new ForbiddenException("User does not have enough privileges.", needMoreCredentials).asPromise();
} catch (final ObjectNotFound objectNotFound) {
debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={} : Resource cannot be found.", resourceId, objectNotFound);
return new NotFoundException("Resource cannot be found.", objectNotFound).asPromise();
} catch (final TokenExpired tokenExpired) {
debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={} : Unauthorized", resourceId, tokenExpired);
return new PermanentException(401, "Unauthorized", null).asPromise();
} catch (final AccessDenied accessDenied) {
debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={} : Access denied", resourceId, accessDenied);
return new ForbiddenException(accessDenied.getMessage(), accessDenied).asPromise();
} catch (final GeneralFailure generalFailure) {
debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={}", resourceId, generalFailure);
return new BadRequestException(generalFailure.getMessage(), generalFailure).asPromise();
} catch (final Exception e) {
debug.error("IdentityResource.readInstance() :: Cannot READ resourceId={}", resourceId, e);
return new NotFoundException(e.getMessage(), e).asPromise();
}
}
use of com.sun.identity.idsvcs.GeneralFailure in project OpenAM by OpenRock.
the class IdentityResourceV1 method updateInstance.
@Override
public Promise<ResourceResponse, ResourceException> updateInstance(final Context context, final String resourceId, final UpdateRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
final String realm = realmContext.getResolvedRealm();
final JsonValue jsonValue = request.getContent();
final String rev = request.getRevision();
IdentityDetails dtls, newDtls;
ResourceResponse resource;
try {
SSOToken admin = getSSOToken(getCookieFromServerContext(context));
// Retrieve details about user to be updated
dtls = identityServices.read(resourceId, getIdentityServicesAttributes(realm), admin);
//be removed from the IdentityDetails object.
if (!isAdmin(context)) {
for (String attrName : jsonValue.keys()) {
if ("userpassword".equalsIgnoreCase(attrName)) {
String newPassword = jsonValue.get(attrName).asString();
if (!StringUtils.isBlank(newPassword)) {
String oldPassword = RestUtils.getMimeHeaderValue(context, OLD_PASSWORD);
if (StringUtils.isBlank(oldPassword)) {
throw new BadRequestException("The old password is missing from the request");
}
//This is an end-user trying to change the password, so let's change the password by
//verifying that the provided old password is correct. We also remove the password from the
//list of attributes to prevent the administrative password reset via the update call.
jsonValue.remove(attrName);
IdentityRestUtils.changePassword(context, realm, resourceId, oldPassword, newPassword);
}
break;
}
}
}
newDtls = jsonValueToIdentityDetails(objectType, jsonValue, realm);
if (newDtls.getName() != null && !resourceId.equalsIgnoreCase(newDtls.getName())) {
throw new BadRequestException("id in path does not match id in request body");
}
newDtls.setName(resourceId);
// update resource with new details
identityServices.update(newDtls, admin);
// read updated identity back to client
IdentityDetails checkIdent = identityServices.read(dtls.getName(), getIdentityServicesAttributes(realm), admin);
// handle updated resource
resource = newResourceResponse(resourceId, "0", identityDetailsToJsonValue(checkIdent));
return newResultPromise(resource);
} catch (final ObjectNotFound onf) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Could not find the " + "resource", resourceId, onf);
return new NotFoundException("Could not find the resource [ " + resourceId + " ] to update", onf).asPromise();
} catch (final NeedMoreCredentials needMoreCredentials) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Token is not authorized", resourceId, needMoreCredentials);
return new ForbiddenException("Token is not authorized", needMoreCredentials).asPromise();
} catch (final TokenExpired tokenExpired) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Unauthorized", resourceId, tokenExpired);
return new PermanentException(401, "Unauthorized", null).asPromise();
} catch (final AccessDenied accessDenied) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Access denied", resourceId, accessDenied);
return new ForbiddenException(accessDenied.getMessage(), accessDenied).asPromise();
} catch (final GeneralFailure generalFailure) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={}", resourceId, generalFailure);
return new BadRequestException(generalFailure.getMessage(), generalFailure).asPromise();
} catch (NotFoundException e) {
debug.warning("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Could not find the " + "resource", resourceId, e);
return new NotFoundException("Could not find the resource [ " + resourceId + " ] to update", e).asPromise();
} catch (ResourceException re) {
debug.warning("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} ", resourceId, re);
return re.asPromise();
} catch (SSOException ssoe) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={}", resourceId, ssoe);
return new ForbiddenException(ssoe).asPromise();
} catch (final Exception e) {
debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={}", resourceId, e);
return new NotFoundException(e).asPromise();
}
}
use of com.sun.identity.idsvcs.GeneralFailure in project OpenAM by OpenRock.
the class IdentityResourceV3 method patchInstance.
/**
* Patch the user's password and only the password. No other value may be patched. The old value of the
* password does not have to be known. Admin only. The only patch operation supported is "replace", i.e. not
* "add" or "move", etc.
*
* @param context The context
* @param resourceId The username we're patching
* @param request The patch request
*/
@Override
public Promise<ResourceResponse, ResourceException> patchInstance(final Context context, final String resourceId, final PatchRequest request) {
if (!objectType.equals(IdentityRestUtils.USER_TYPE)) {
return new BadRequestException("Cannot patch object type " + objectType).asPromise();
}
RealmContext realmContext = context.asContext(RealmContext.class);
final String realm = realmContext.getResolvedRealm();
try {
if (!isAdmin(context)) {
return new ForbiddenException("Only admin can patch user values").asPromise();
}
SSOToken ssoToken = getSSOToken(RestUtils.getToken().getTokenID().toString());
IdentityServicesImpl identityServices = getIdentityServices();
IdentityDetails identityDetails = identityServices.read(resourceId, getIdentityServicesAttributes(realm, objectType), ssoToken);
Attribute[] existingAttributes = identityDetails.getAttributes();
Map<String, Set<String>> existingAttributeMap = attributesToMap(existingAttributes);
Map<String, Set<String>> newAttributeMap = new HashMap<>();
if (existingAttributeMap.containsKey(IdentityRestUtils.UNIVERSAL_ID)) {
Set<String> values = existingAttributeMap.get(IdentityRestUtils.UNIVERSAL_ID);
if (isNotEmpty(values) && !isUserActive(values.iterator().next())) {
return new ForbiddenException("User " + resourceId + " is not active: Request is forbidden").asPromise();
}
}
boolean updateNeeded = false;
for (PatchOperation patchOperation : request.getPatchOperations()) {
switch(patchOperation.getOperation()) {
case PatchOperation.OPERATION_REPLACE:
{
String name = getFieldName(patchOperation.getField());
if (!patchableAttributes.contains(name)) {
return new BadRequestException("For the object type " + IdentityRestUtils.USER_TYPE + ", field \"" + name + "\" cannot be altered by PATCH").asPromise();
}
JsonValue value = patchOperation.getValue();
newAttributeMap.put(name, identityAttributeJsonToSet(value));
updateNeeded = true;
break;
}
default:
return new BadRequestException("PATCH of " + IdentityRestUtils.USER_TYPE + " does not support operation " + patchOperation.getOperation()).asPromise();
}
}
if (updateNeeded) {
identityDetails.setAttributes(mapToAttributes(newAttributeMap));
identityServices.update(identityDetails, ssoToken);
// re-read the altered identity details from the repo.
identityDetails = identityServices.read(resourceId, getIdentityServicesAttributes(realm, objectType), ssoToken);
}
return newResultPromise(newResourceResponse("result", "1", identityDetailsToJsonValue(identityDetails)));
} catch (final ObjectNotFound notFound) {
logger.error("IdentityResourceV3.patchInstance cannot find resource " + resourceId, notFound);
return new NotFoundException("Resource cannot be found.", notFound).asPromise();
} catch (final TokenExpired tokenExpired) {
logger.error("IdentityResourceV3.patchInstance, token expired", tokenExpired);
return new PermanentException(401, "Unauthorized", null).asPromise();
} catch (final AccessDenied accessDenied) {
logger.error("IdentityResourceV3.patchInstance, access denied", accessDenied);
return new ForbiddenException(accessDenied.getMessage(), accessDenied).asPromise();
} catch (final GeneralFailure generalFailure) {
logger.error("IdentityResourceV3.patchInstance, general failure " + generalFailure.getMessage());
return new BadRequestException(generalFailure.getMessage(), generalFailure).asPromise();
} catch (ForbiddenException fex) {
logger.warning("IdentityResourceV3.patchInstance, insufficient privileges.", fex);
return fex.asPromise();
} catch (NotFoundException notFound) {
logger.warning("IdentityResourceV3.patchInstance " + resourceId + " not found", notFound);
return new NotFoundException("Resource " + resourceId + " cannot be found.", notFound).asPromise();
} catch (ResourceException resourceException) {
logger.warning("IdentityResourceV3.patchInstance caught ResourceException", resourceException);
return resourceException.asPromise();
} catch (Exception exception) {
logger.error("IdentityResourceV3.patchInstance caught exception", exception);
return new InternalServerErrorException(exception.getMessage(), exception).asPromise();
}
}
use of com.sun.identity.idsvcs.GeneralFailure in project OpenAM by OpenRock.
the class IdentityServicesImpl method attributes.
private UserDetails attributes(List<String> attributeNames, Token subject, Boolean refresh) throws TokenExpired, GeneralFailure, AccessDenied {
UserDetails details = new UserDetails();
try {
SSOToken ssoToken = getSSOToken(subject);
if (refresh != null && refresh) {
SSOTokenManager.getInstance().refreshSession(ssoToken);
}
Map<String, Set<String>> sessionAttributes = new HashMap<>();
Set<String> s;
if (attributeNames != null) {
String propertyNext;
for (String attrNext : attributeNames) {
s = new HashSet<>();
if (attrNext.equalsIgnoreCase("idletime")) {
s.add(Long.toString(ssoToken.getIdleTime()));
} else if (attrNext.equalsIgnoreCase("timeleft")) {
s.add(Long.toString(ssoToken.getTimeLeft()));
} else if (attrNext.equalsIgnoreCase("maxsessiontime")) {
s.add(Long.toString(ssoToken.getMaxSessionTime()));
} else if (attrNext.equalsIgnoreCase("maxidletime")) {
s.add(Long.toString(ssoToken.getMaxIdleTime()));
} else {
propertyNext = ssoToken.getProperty(attrNext);
if (propertyNext != null && !propertyNext.isEmpty()) {
s.add(propertyNext);
}
}
if (!s.isEmpty()) {
sessionAttributes.put(attrNext, s);
}
}
}
// Obtain user memberships (roles and groups)
AMIdentity userIdentity = IdUtils.getIdentity(ssoToken);
if (isSpecialUser(userIdentity)) {
throw new AccessDenied("Cannot retrieve attributes for this user.");
}
// Determine the types that can have members
SSOToken adminToken = AccessController.doPrivileged(AdminTokenAction.getInstance());
AMIdentityRepository idrepo = new AMIdentityRepository(userIdentity.getRealm(), adminToken);
Set<IdType> supportedTypes = idrepo.getSupportedIdTypes();
Set<IdType> membersTypes = new HashSet<>();
for (IdType type : supportedTypes) {
if (type.canHaveMembers().contains(userIdentity.getType())) {
membersTypes.add(type);
}
}
// Determine the roles and groups
List<String> roles = new ArrayList<>();
for (IdType type : membersTypes) {
try {
Set<AMIdentity> memberships = userIdentity.getMemberships(type);
for (AMIdentity membership : memberships) {
roles.add(membership.getUniversalId());
}
} catch (IdRepoException ire) {
debug.message("IdentityServicesImpl:attributes", ire);
// Ignore and continue
}
}
String[] r = new String[roles.size()];
details.setRoles(roles.toArray(r));
Map<String, Set<String>> userAttributes;
if (attributeNames != null) {
Set<String> attrNames = new HashSet<>(attributeNames);
userAttributes = userIdentity.getAttributes(attrNames);
} else {
userAttributes = userIdentity.getAttributes();
}
if (userAttributes != null) {
for (Map.Entry<String, Set<String>> entry : sessionAttributes.entrySet()) {
if (userAttributes.keySet().contains(entry.getKey())) {
userAttributes.get(entry.getKey()).addAll(entry.getValue());
} else {
userAttributes.put(entry.getKey(), entry.getValue());
}
}
} else {
userAttributes = sessionAttributes;
}
List<Attribute> attributes = new ArrayList<>(userAttributes.size());
for (String name : userAttributes.keySet()) {
Attribute attribute = new Attribute();
attribute.setName(name);
Set<String> value = userAttributes.get(name);
if (value != null && !value.isEmpty()) {
List<String> valueList = new ArrayList<>(value.size());
// Convert the set to a List of String
for (String next : value) {
if (next != null) {
valueList.add(next);
}
}
String[] v = new String[valueList.size()];
attribute.setValues(valueList.toArray(v));
attributes.add(attribute);
}
}
Attribute[] a = new Attribute[attributes.size()];
details.setAttributes(attributes.toArray(a));
} catch (IdRepoException e) {
debug.error("IdentityServicesImpl:attributes", e);
throw new GeneralFailure(e.getMessage());
} catch (SSOException e) {
debug.error("IdentityServicesImpl:attributes", e);
throw new GeneralFailure(e.getMessage());
} catch (TokenExpired e) {
debug.warning("IdentityServicesImpl:attributes original error", e);
throw new TokenExpired("Cannot retrieve Token.");
}
//TODO handle token translation
details.setToken(subject);
return details;
}
Aggregations