use of com.sun.identity.idsvcs.IdentityDetails 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.IdentityDetails in project OpenAM by OpenRock.
the class IdentityResourceV2 method createInstance.
/**
* {@inheritDoc}
*/
@Override
public Promise<ResourceResponse, ResourceException> createInstance(final Context context, final CreateRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
final String realm = realmContext.getResolvedRealm();
try {
// anyone can create an account add
SSOToken admin = getSSOToken(getCookieFromServerContext(context));
final JsonValue jVal = request.getContent();
String resourceId = request.getNewResourceId();
IdentityDetails identity = jsonValueToIdentityDetails(objectType, jVal, realm);
// check to see if request has included resource ID
if (resourceId != null) {
if (identity.getName() != null) {
if (!resourceId.equalsIgnoreCase(identity.getName())) {
ResourceException be = new BadRequestException("id in path does not match id in request body");
debug.error("IdentityResource.createInstance() :: Cannot CREATE ", be);
return be.asPromise();
}
}
identity.setName(resourceId);
} else {
resourceId = identity.getName();
}
UserAttributeInfo userAttributeInfo = configHandler.getConfig(realm, UserAttributeInfoBuilder.class);
enforceWhiteList(context, request.getContent(), objectType, userAttributeInfo.getValidCreationAttributes());
final String id = resourceId;
return attemptResourceCreation(realm, admin, identity, resourceId).thenAsync(new AsyncFunction<IdentityDetails, ResourceResponse, ResourceException>() {
@Override
public Promise<ResourceResponse, ResourceException> apply(IdentityDetails dtls) {
if (dtls != null) {
String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
debug.message("IdentityResource.createInstance :: CREATE of resourceId={} in realm={} " + "performed by principalName={}", id, realm, principalName);
ResourceResponse resource = newResourceResponse(id, "0", identityDetailsToJsonValue(dtls));
return newResultPromise(resource);
} else {
debug.error("IdentityResource.createInstance() :: Identity not found");
return new NotFoundException("Identity not found").asPromise();
}
}
});
} catch (SSOException e) {
return new ForbiddenException(e).asPromise();
} catch (BadRequestException bre) {
return bre.asPromise();
}
}
use of com.sun.identity.idsvcs.IdentityDetails in project OpenAM by OpenRock.
the class IdentityResourceV1 method generateNewPasswordEmail.
/**
* Generates the e-mail contents based on the incoming request.
*
* Will only send the e-mail if all the following conditions are true:
*
* - Forgotten Password service is enabled
* - User exists
* - User has an e-mail address in their profile
* - E-mail service is correctly configured.
*
* @param context Non null.
* @param request Non null.
* @param realm Used as part of user lookup.
* @param restSecurity Non null.
*/
private Promise<ActionResponse, ResourceException> generateNewPasswordEmail(final Context context, final ActionRequest request, final String realm, final RestSecurity restSecurity) {
JsonValue result = new JsonValue(new LinkedHashMap<String, Object>(1));
final JsonValue jsonBody = request.getContent();
try {
// Check to make sure forgotPassword enabled
if (restSecurity == null) {
if (debug.warningEnabled()) {
debug.warning("Rest Security not created. restSecurity={}", restSecurity);
}
throw getException(UNAVAILABLE, "Rest Security Service not created");
}
if (!restSecurity.isForgotPassword()) {
if (debug.warningEnabled()) {
debug.warning("Forgot Password set to : {}", restSecurity.isForgotPassword());
}
throw getException(UNAVAILABLE, "Forgot password is not accessible.");
}
// Generate Admin Token
SSOToken adminToken = getSSOToken(RestUtils.getToken().getTokenID().toString());
Map<String, Set<String>> searchAttributes = getIdentityServicesAttributes(realm);
searchAttributes.putAll(getAttributeFromRequest(jsonBody));
List searchResults = identityServices.search(new CrestQuery("*"), searchAttributes, adminToken);
if (searchResults.isEmpty()) {
throw new NotFoundException("User not found");
} else if (searchResults.size() > 1) {
throw new ConflictException("Multiple users found");
} else {
String username = (String) searchResults.get(0);
IdentityDetails identityDetails = identityServices.read(username, getIdentityServicesAttributes(realm), adminToken);
String email = null;
String uid = null;
for (Map.Entry<String, Set<String>> attribute : asMap(identityDetails.getAttributes()).entrySet()) {
String attributeName = attribute.getKey();
if (MAIL.equalsIgnoreCase(attributeName)) {
if (attribute.getValue() != null && !attribute.getValue().isEmpty()) {
email = attribute.getValue().iterator().next();
}
} else if (UNIVERSAL_ID.equalsIgnoreCase(attributeName)) {
if (attribute.getValue() != null && !attribute.getValue().isEmpty()) {
uid = attribute.getValue().iterator().next();
}
}
}
// Check to see if user is Active/Inactive
if (!isUserActive(uid)) {
throw new ForbiddenException("Request is forbidden for this user");
}
// Check if email is provided
if (email == null || email.isEmpty()) {
throw new BadRequestException("No email provided in profile.");
}
// Get full deployment URL
HttpContext header = context.asContext(HttpContext.class);
StringBuilder deploymentURL = RestUtils.getFullDeploymentURI(header.getPath());
String subject = jsonBody.get("subject").asString();
String message = jsonBody.get("message").asString();
// Retrieve email registration token life time
if (restSecurity == null) {
if (debug.warningEnabled()) {
debug.warning("Rest Security not created. restSecurity={}", restSecurity);
}
throw new NotFoundException("Rest Security Service not created");
}
Long tokenLifeTime = restSecurity.getForgotPassTLT();
// Generate Token
org.forgerock.openam.cts.api.tokens.Token ctsToken = generateToken(email, username, tokenLifeTime, realm);
// Store token in datastore
CTSHolder.getCTS().createAsync(ctsToken);
// Create confirmationId
String confirmationId = Hash.hash(ctsToken.getTokenId() + username + SystemProperties.get(AM_ENCRYPTION_PWD));
// Build Confirmation URL
String confURL = restSecurity.getForgotPasswordConfirmationUrl();
StringBuilder confURLBuilder = new StringBuilder(100);
if (confURL == null || confURL.isEmpty()) {
confURLBuilder.append(deploymentURL.append("/json/confirmation/forgotPassword").toString());
} else {
confURLBuilder.append(confURL);
}
String confirmationLink = confURLBuilder.append("?confirmationId=").append(requestParamEncode(confirmationId)).append("&tokenId=").append(requestParamEncode(ctsToken.getTokenId())).append("&username=").append(requestParamEncode(username)).append("&realm=").append(realm).toString();
// Send Registration
sendNotification(email, subject, message, realm, confirmationLink);
String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
if (debug.messageEnabled()) {
debug.message("IdentityResource.generateNewPasswordEmail :: ACTION of generate new password email " + " for username={} in realm={} performed by principalName={}", username, realm, principalName);
}
}
return newResultPromise(newActionResponse(result));
} catch (NotFoundException e) {
debug.warning("Could not find user", e);
return e.asPromise();
} catch (ResourceException re) {
// Service not available, Neither or both Username/Email provided, User inactive
debug.warning(re.getMessage(), re);
return re.asPromise();
} catch (Exception e) {
// Intentional - all other errors are considered Internal Error.
debug.error("Internal error : Failed to send mail", e);
return new InternalServerErrorException("Failed to send mail", e).asPromise();
}
}
use of com.sun.identity.idsvcs.IdentityDetails 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.IdentityDetails 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();
}
}
Aggregations