use of org.forgerock.json.resource.InternalServerErrorException in project OpenAM by OpenRock.
the class IdentityServicesImpl method searchIdentityDetails.
/**
* Searches the identity repository to find all identities that match the search criteria and returns them as a
* list of identities.
*
* @param crestQuery A CREST Query object which will contain either a _queryId or a _queryFilter.
* @param searchModifiers The search modifiers
* @param admin Your SSO token.
* @return a list of matching identities.
* @throws ResourceException
*/
public List<IdentityDetails> searchIdentityDetails(CrestQuery crestQuery, Map<String, Set<String>> searchModifiers, SSOToken admin) throws ResourceException {
try {
String realm = "/";
String objectType = "User";
if (searchModifiers != null) {
realm = attractValues("realm", searchModifiers, "/");
objectType = attractValues("objecttype", searchModifiers, "User");
}
AMIdentityRepository repo = getRepo(admin, realm);
IdType idType = getIdType(objectType);
if (idType != null) {
List<AMIdentity> identities = fetchAMIdentities(idType, crestQuery, true, repo, searchModifiers);
List<IdentityDetails> result = new ArrayList<>();
for (AMIdentity identity : identities) {
result.add(convertToIdentityDetails(identity, null));
}
return result;
}
debug.error("IdentityServicesImpl.searchIdentities unsupported IdType " + objectType);
throw new BadRequestException("searchIdentities: unsupported IdType " + objectType);
} catch (IdRepoException e) {
debug.error("IdentityServicesImpl.searchIdentities", e);
throw new InternalServerErrorException(e.getMessage());
} catch (SSOException e) {
debug.error("IdentityServicesImpl.searchIdentities", e);
throw new InternalServerErrorException(e.getMessage());
} catch (ObjectNotFound e) {
debug.error("IdentityServicesImpl.searchIdentities", e);
throw new NotFoundException(e.getMessage());
}
}
use of org.forgerock.json.resource.InternalServerErrorException in project OpenAM by OpenRock.
the class IdentityServicesImpl method update.
/**
* Updates an {@code AMIdentity} in the identity repository with the
* details specified in {@code identity}.
*
* @param identity The updated identity details.
* @param admin The admin token.
* @throws ResourceException If a problem occurs.
*/
public void update(IdentityDetails identity, SSOToken admin) throws ResourceException {
String idName = identity.getName();
String idType = identity.getType();
String realm = identity.getRealm();
if (StringUtils.isEmpty(idName)) {
// TODO: add a message to the exception
throw new BadRequestException("");
}
if (StringUtils.isEmpty(idType)) {
idType = "user";
}
if (realm == null) {
realm = "";
}
try {
IdType objectIdType = getIdType(idType);
AMIdentityRepository repo = getRepo(admin, realm);
if (!isOperationSupported(repo, objectIdType, IdOperation.EDIT)) {
// TODO: add message to exception
throw new ForbiddenException("");
}
AMIdentity amIdentity = getAMIdentity(admin, repo, idType, idName);
if (amIdentity == null) {
String msg = "Object \'" + idName + "\' of type \'" + idType + "\' not found.'";
throw new NotFoundException(msg);
}
if (isSpecialUser(amIdentity)) {
throw new ForbiddenException("Cannot update attributes for this user.");
}
Map<String, Set<String>> attrs = asMap(identity.getAttributes());
if (attrs != null && !attrs.isEmpty()) {
Map<String, Set<String>> idAttrs = new HashMap<>();
Set<String> removeAttrs = new HashSet<>();
for (Map.Entry<String, Set<String>> entry : attrs.entrySet()) {
String attrName = entry.getKey();
Set<String> attrValues = entry.getValue();
if (attrValues != null && !attrValues.isEmpty()) {
// attribute to add or modify
idAttrs.put(attrName, attrValues);
} else {
// attribute to remove
removeAttrs.add(attrName);
}
}
boolean storeNeeded = false;
if (!idAttrs.isEmpty()) {
amIdentity.setAttributes(idAttrs);
storeNeeded = true;
}
if (!removeAttrs.isEmpty()) {
amIdentity.removeAttributes(removeAttrs);
storeNeeded = true;
}
if (storeNeeded) {
amIdentity.store();
}
}
if (IdType.USER.equals(objectIdType)) {
Set<String> roles = asSet(identity.getRoleList());
if (!roles.isEmpty()) {
setMemberships(repo, amIdentity, roles, IdType.ROLE);
}
Set<String> groups = asSet(identity.getGroupList());
if (!groups.isEmpty()) {
setMemberships(repo, amIdentity, groups, IdType.GROUP);
}
}
if (IdType.GROUP.equals(objectIdType) || IdType.ROLE.equals(objectIdType)) {
Set<String> members = asSet(identity.getMemberList());
if (!members.isEmpty()) {
setMembers(repo, amIdentity, members, IdType.USER);
}
}
} catch (IdRepoException ex) {
debug.error("IdentityServicesImpl:update", ex);
if (IdRepoErrorCode.LDAP_EXCEPTION.equals(ex.getErrorCode())) {
throw new InternalServerErrorException(ex.getConstraintViolationDetails());
} else if (LDAPConstants.LDAP_INVALID_SYNTAX.equals(ex.getLDAPErrorCode())) {
throw new BadRequestException("Unrecognized or invalid syntax for an attribute.");
} else if (IdRepoErrorCode.ILLEGAL_ARGUMENTS.equals(ex.getErrorCode())) {
throw new BadRequestException(ex);
}
throw RESOURCE_MAPPING_HANDLER.handleError(ex);
} catch (SSOException ex) {
debug.error("IdentityServicesImpl:update", ex);
throw new BadRequestException(ex.getMessage());
} catch (ObjectNotFound e) {
debug.error("IdentityServicesImpl:update", e);
throw new NotFoundException(e.getMessage());
}
}
use of org.forgerock.json.resource.InternalServerErrorException in project OpenAM by OpenRock.
the class IdentityResourceV2 method anonymousUpdate.
/**
* Perform an anonymous update of a user's password using the provided token.
*
* The token must match a token placed in the CTS in order for the request
* to proceed.
*
* @param context Non null
* @param request Non null
* @param realm Non null
*/
private Promise<ActionResponse, ResourceException> anonymousUpdate(final Context context, final ActionRequest request, final String realm) {
final String tokenID;
String confirmationId;
String username;
String nwpassword;
final JsonValue jVal = request.getContent();
try {
tokenID = jVal.get(TOKEN_ID).asString();
jVal.remove(TOKEN_ID);
confirmationId = jVal.get(CONFIRMATION_ID).asString();
jVal.remove(CONFIRMATION_ID);
username = jVal.get(USERNAME).asString();
nwpassword = jVal.get("userpassword").asString();
if (username == null || username.isEmpty()) {
throw new BadRequestException("username not provided");
}
if (nwpassword == null || username.isEmpty()) {
throw new BadRequestException("new password not provided");
}
validateToken(tokenID, realm, username, confirmationId);
// update Identity
SSOToken admin = RestUtils.getToken();
// Update instance with new password value
return updateInstance(admin, jVal, realm).thenAsync(new AsyncFunction<ActionResponse, ActionResponse, ResourceException>() {
@Override
public Promise<ActionResponse, ResourceException> apply(ActionResponse response) {
// Only remove the token if the update was successful, errors will be set in the handler.
try {
// Even though the generated token will eventually timeout, delete it after a successful read
// so that the reset password request cannot be made again using the same token.
CTSHolder.getCTS().deleteAsync(tokenID);
} catch (DeleteFailedException e) {
// reading and deleting, the token has expired.
if (debug.messageEnabled()) {
debug.message("Deleting token " + tokenID + " after a successful " + "read failed due to " + e.getMessage(), e);
}
} catch (CoreTokenException cte) {
// For any unexpected CTS error
debug.error("Error performing anonymousUpdate", cte);
return new InternalServerErrorException(cte.getMessage(), cte).asPromise();
}
return newResultPromise(response);
}
});
} catch (BadRequestException bre) {
// For any malformed request.
debug.warning("Bad request received for anonymousUpdate ", bre);
return bre.asPromise();
} catch (ResourceException re) {
debug.warning("Error performing anonymousUpdate", re);
return re.asPromise();
} catch (CoreTokenException cte) {
// For any unexpected CTS error
debug.error("Error performing anonymousUpdate", cte);
return new InternalServerErrorException(cte).asPromise();
}
}
use of org.forgerock.json.resource.InternalServerErrorException in project OpenAM by OpenRock.
the class RealmResource method queryCollection.
/**
* Returns names of all realms included in the subtree rooted by the realm indicated
* in the query url.
*
* Names are unsorted and given as full paths.
*
* Filtering, sorting, and paging of results is not supported.
*
* {@inheritDoc}
*/
@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest request, QueryResourceHandler handler) {
final String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
final RealmContext realmContext = context.asContext(RealmContext.class);
final String realmPath = realmContext.getResolvedRealm();
try {
final SSOTokenManager mgr = SSOTokenManager.getInstance();
final SSOToken ssoToken = mgr.createSSOToken(getCookieFromServerContext(context));
final OrganizationConfigManager ocm = new OrganizationConfigManager(ssoToken, realmPath);
final List<String> realmsInSubTree = new ArrayList<String>();
realmsInSubTree.add(realmPath);
for (final Object subRealmRelativePath : ocm.getSubOrganizationNames("*", true)) {
if (realmPath.endsWith("/")) {
realmsInSubTree.add(realmPath + subRealmRelativePath);
} else {
realmsInSubTree.add(realmPath + "/" + subRealmRelativePath);
}
}
debug.message("RealmResource :: QUERY : performed by " + principalName);
for (final Object realmName : realmsInSubTree) {
JsonValue val = new JsonValue(realmName);
ResourceResponse resource = newResourceResponse((String) realmName, "0", val);
handler.handleResource(resource);
}
return newResultPromise(newQueryResponse());
} catch (SSOException ex) {
debug.error("RealmResource :: QUERY by " + principalName + " failed : " + ex);
return new ForbiddenException().asPromise();
} catch (SMSException ex) {
debug.error("RealmResource :: QUERY by " + principalName + " failed :" + ex);
switch(ex.getExceptionCode()) {
case STATUS_NO_PERMISSION:
// This exception will be thrown if permission to read realms from SMS has not been delegated
return new ForbiddenException().asPromise();
default:
return new InternalServerErrorException().asPromise();
}
}
}
use of org.forgerock.json.resource.InternalServerErrorException in project OpenAM by OpenRock.
the class IdentityResourceV2 method confirmationIdCheck.
/**
* Will validate confirmationId is correct
* @param request Request from client to confirm registration
*/
private Promise<ActionResponse, ResourceException> confirmationIdCheck(final ActionRequest request, final String realm) {
final String METHOD = "IdentityResource.confirmationIdCheck";
final JsonValue jVal = request.getContent();
String tokenID = "";
String confirmationId;
String email;
String username;
//email or username value used to create confirmationId
String hashComponent = null;
String hashComponentAttr = null;
JsonValue result = new JsonValue(new LinkedHashMap<String, Object>(1));
try {
tokenID = jVal.get(TOKEN_ID).asString();
confirmationId = jVal.get(CONFIRMATION_ID).asString();
email = jVal.get(EMAIL).asString();
username = jVal.get(USERNAME).asString();
if (StringUtils.isBlank(confirmationId)) {
if (debug.errorEnabled()) {
debug.error("{} :: Bad Request - confirmationId not found in request.", METHOD);
}
throw new BadRequestException("confirmationId not provided");
}
if (StringUtils.isBlank(email) && !StringUtils.isBlank(username)) {
hashComponent = username;
hashComponentAttr = USERNAME;
}
if (!StringUtils.isBlank(email) && StringUtils.isBlank(username)) {
hashComponent = email;
hashComponentAttr = EMAIL;
}
if (StringUtils.isBlank(hashComponent)) {
if (debug.errorEnabled()) {
debug.error("{} :: Bad Request - hashComponent not found in request.", METHOD);
}
throw new BadRequestException("Required information not provided");
}
if (StringUtils.isBlank(tokenID)) {
if (debug.errorEnabled()) {
debug.error("{} :: Bad Request - tokenID not found in request.", METHOD);
}
throw new BadRequestException("tokenId not provided");
}
validateToken(tokenID, realm, hashComponent, confirmationId);
// build resource
result.put(hashComponentAttr, hashComponent);
result.put(TOKEN_ID, tokenID);
result.put(CONFIRMATION_ID, confirmationId);
if (debug.messageEnabled()) {
debug.message("{} :: Confirmed for token '{}' with confirmation '{}'", METHOD, tokenID, confirmationId);
}
return newResultPromise(newActionResponse(result));
} catch (BadRequestException bre) {
debug.warning("{} :: Cannot confirm registration/forgotPassword for : {}", METHOD, hashComponent, bre);
return bre.asPromise();
} catch (ResourceException re) {
debug.warning("{} :: Resource error for : {}", METHOD, hashComponent, re);
return re.asPromise();
} catch (CoreTokenException cte) {
debug.error("{} :: CTE error for : {}", METHOD, hashComponent, cte);
return new InternalServerErrorException(cte).asPromise();
}
}
Aggregations