Search in sources :

Example 91 with AMIdentityRepository

use of com.sun.identity.idm.AMIdentityRepository 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;
}
Also used : SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) Attribute(com.sun.identity.idsvcs.Attribute) ArrayList(java.util.ArrayList) SSOException(com.iplanet.sso.SSOException) UserDetails(com.sun.identity.idsvcs.UserDetails) TokenExpired(com.sun.identity.idsvcs.TokenExpired) HashSet(java.util.HashSet) IdRepoException(com.sun.identity.idm.IdRepoException) AccessDenied(com.sun.identity.idsvcs.AccessDenied) IdType(com.sun.identity.idm.IdType) AMIdentity(com.sun.identity.idm.AMIdentity) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) GeneralFailure(com.sun.identity.idsvcs.GeneralFailure) Map(java.util.Map) HashMap(java.util.HashMap)

Example 92 with AMIdentityRepository

use of com.sun.identity.idm.AMIdentityRepository in project OpenAM by OpenRock.

the class IdentityServicesImpl method create.

/**
     * Creates a new {@code AMIdentity} in the identity repository with the
     * details specified in {@code identity}.
     *
     * @param identity The identity details.
     * @param admin The admin token.
     * @throws ResourceException If a problem occurs.
     */
public void create(IdentityDetails identity, SSOToken admin) throws ResourceException {
    Reject.ifNull(identity, admin);
    // Obtain identity details & verify
    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("Identity name not provided");
    }
    if (StringUtils.isEmpty(idType)) {
        idType = "user";
    }
    if (realm == null) {
        realm = "/";
    }
    try {
        // Obtain IdRepo to create validate IdType & operations
        IdType objectIdType = getIdType(idType);
        AMIdentityRepository repo = getRepo(admin, realm);
        if (!isOperationSupported(repo, objectIdType, IdOperation.CREATE)) {
            // TODO: add message to exception
            throw new UnsupportedOperationException("Unsupported: Type: " + idType + " Operation: CREATE");
        }
        // Obtain creation attributes
        Map<String, Set<String>> idAttrs = asMap(identity.getAttributes());
        // Create the identity, special case of Agents to merge
        // and validate the attributes
        AMIdentity amIdentity;
        if (isTypeAgent(objectIdType)) {
            createAgent(idAttrs, objectIdType, idType, idName, realm, admin);
        } else {
            // Create other identites like User, Group, Role, etc.
            amIdentity = repo.createIdentity(objectIdType, idName, idAttrs);
            // Process roles, groups & memberships
            if (IdType.USER.equals(objectIdType)) {
                Set<String> roles = asSet(identity.getRoleList());
                if (roles != null && !roles.isEmpty()) {
                    if (!isOperationSupported(repo, IdType.ROLE, IdOperation.EDIT)) {
                        // TODO: localize message
                        throw new UnsupportedOperationException("Unsupported: Type: " + IdType.ROLE + " Operation: EDIT");
                    }
                    for (String roleName : roles) {
                        AMIdentity role = fetchAMIdentity(repo, IdType.ROLE, roleName, false);
                        if (role != null) {
                            role.addMember(amIdentity);
                            role.store();
                        }
                    }
                }
                Set<String> groups = asSet(identity.getGroupList());
                if (groups != null && !groups.isEmpty()) {
                    if (!isOperationSupported(repo, IdType.GROUP, IdOperation.EDIT)) {
                        // TODO: localize message
                        throw new UnsupportedOperationException("Unsupported: Type: " + IdType.GROUP + " Operation: EDIT");
                    }
                    for (String groupName : groups) {
                        AMIdentity group = fetchAMIdentity(repo, IdType.GROUP, groupName, false);
                        if (group != null) {
                            group.addMember(amIdentity);
                            group.store();
                        }
                    }
                }
            }
            if (IdType.GROUP.equals(objectIdType) || IdType.ROLE.equals(objectIdType)) {
                Set<String> members = asSet(identity.getMemberList());
                if (members != null) {
                    if (IdType.GROUP.equals(objectIdType) && !isOperationSupported(repo, IdType.GROUP, IdOperation.EDIT)) {
                        throw new ForbiddenException("Token is not authorized");
                    }
                    if (IdType.ROLE.equals(objectIdType) && !isOperationSupported(repo, IdType.ROLE, IdOperation.EDIT)) {
                        throw new ForbiddenException("Token is not authorized");
                    }
                    for (String memberName : members) {
                        AMIdentity user = fetchAMIdentity(repo, IdType.USER, memberName, false);
                        if (user != null) {
                            amIdentity.addMember(user);
                        }
                    }
                    amIdentity.store();
                }
            }
        }
    } catch (IdRepoDuplicateObjectException ex) {
        throw new ConflictException("Resource already exists", ex);
    } catch (IdRepoException e) {
        debug.error("IdentityServicesImpl:create", e);
        if (IdRepoErrorCode.ACCESS_DENIED.equals(e.getErrorCode())) {
            throw new ForbiddenException(e.getMessage());
        } else if (e.getLdapErrorIntCode() == LDAPConstants.LDAP_CONSTRAINT_VIOLATION) {
            debug.error(e.getMessage(), e);
            throw new BadRequestException();
        } else {
            throw new NotFoundException(e.getMessage());
        }
    } catch (SSOException | SMSException | ConfigurationException | MalformedURLException | UnsupportedOperationException e) {
        debug.error("IdentityServicesImpl:create", e);
        throw new NotFoundException(e.getMessage());
    } catch (ObjectNotFound e) {
        debug.error("IdentityServicesImpl:create", e);
        throw new NotFoundException(e.getMessage());
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) MalformedURLException(java.net.MalformedURLException) Set(java.util.Set) HashSet(java.util.HashSet) ConflictException(org.forgerock.json.resource.ConflictException) SMSException(com.sun.identity.sm.SMSException) IdRepoException(com.sun.identity.idm.IdRepoException) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) IdType(com.sun.identity.idm.IdType) ConfigurationException(com.sun.identity.common.configuration.ConfigurationException) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) IdRepoDuplicateObjectException(com.sun.identity.idm.IdRepoDuplicateObjectException) AMIdentity(com.sun.identity.idm.AMIdentity) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) BadRequestException(org.forgerock.json.resource.BadRequestException)

Example 93 with AMIdentityRepository

use of com.sun.identity.idm.AMIdentityRepository 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());
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) IdRepoException(com.sun.identity.idm.IdRepoException) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) IdType(com.sun.identity.idm.IdType) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) AMIdentity(com.sun.identity.idm.AMIdentity) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) Map(java.util.Map) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 94 with AMIdentityRepository

use of com.sun.identity.idm.AMIdentityRepository in project OpenAM by OpenRock.

the class IdentityServicesImpl method getSpecialUsers.

private Set<AMIdentity> getSpecialUsers(String realmName) {
    SSOToken adminToken = AccessController.doPrivileged(AdminTokenAction.getInstance());
    try {
        AMIdentityRepository repo = new AMIdentityRepository(realmName, adminToken);
        IdSearchResults results = repo.getSpecialIdentities(IdType.USER);
        return results.getSearchResults();
    } catch (IdRepoException | SSOException e) {
        debug.warning("AMModelBase.getSpecialUsers", e);
    }
    return Collections.emptySet();
}
Also used : SSOToken(com.iplanet.sso.SSOToken) IdSearchResults(com.sun.identity.idm.IdSearchResults) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException)

Example 95 with AMIdentityRepository

use of com.sun.identity.idm.AMIdentityRepository in project OpenAM by OpenRock.

the class RealmResourceOfferingModelImpl method setRealmDiscoEntry.

/**
     * Set resource offering entry.
     *
     * @param realm Realm Name.
     * @param smData Resource offering entry.
     * @throws AMConsoleException if entry cannot be set.
     */
public void setRealmDiscoEntry(String realm, SMDiscoveryServiceData smData) throws AMConsoleException {
    String[] params = { realm, AMAdminConstants.DISCOVERY_SERVICE };
    logEvent("ATTEMPT_MODIFY_SERVICE_UNDER_REALM", params);
    Map map = new HashMap(2);
    map.put(AMAdminConstants.DISCOVERY_SERVICE_NAME_DYNAMIC_DISCO_ENTRIES, smData.getDiscoveryEntries());
    try {
        AMIdentityRepository repo = new AMIdentityRepository(getUserSSOToken(), realm);
        AMIdentity realmIdentity = repo.getRealmIdentity();
        Set servicesFromIdRepo = realmIdentity.getAssignedServices();
        if (servicesFromIdRepo.contains(AMAdminConstants.DISCOVERY_SERVICE)) {
            realmIdentity.modifyService(AMAdminConstants.DISCOVERY_SERVICE, map);
        } else {
            OrganizationConfigManager orgCfgMgr = new OrganizationConfigManager(getUserSSOToken(), realm);
            orgCfgMgr.modifyService(AMAdminConstants.DISCOVERY_SERVICE, map);
        }
        logEvent("SUCCEED_MODIFY_SERVICE_UNDER_REALM", params);
    } catch (SSOException e) {
        String strError = getErrorString(e);
        String[] paramsEx = { realm, AMAdminConstants.DISCOVERY_SERVICE, strError };
        logEvent("SSO_EXCEPTION_MODIFY_SERVICE_UNDER_REALM", paramsEx);
        throw new AMConsoleException(strError);
    } catch (IdRepoException e) {
        String strError = getErrorString(e);
        String[] paramsEx = { realm, AMAdminConstants.DISCOVERY_SERVICE, strError };
        logEvent("IDREPO_EXCEPTION_MODIFY_SERVICE_UNDER_REALM", paramsEx);
        throw new AMConsoleException(strError);
    } catch (SMSException e) {
        String strError = getErrorString(e);
        String[] paramsEx = { realm, AMAdminConstants.DISCOVERY_SERVICE, strError };
        logEvent("SMS_EXCEPTION_MODIFY_SERVICE_UNDER_REALM", paramsEx);
        throw new AMConsoleException(strError);
    }
}
Also used : Set(java.util.Set) HashMap(java.util.HashMap) SMSException(com.sun.identity.sm.SMSException) AMIdentity(com.sun.identity.idm.AMIdentity) OrganizationConfigManager(com.sun.identity.sm.OrganizationConfigManager) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) AMConsoleException(com.sun.identity.console.base.model.AMConsoleException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

AMIdentityRepository (com.sun.identity.idm.AMIdentityRepository)138 IdRepoException (com.sun.identity.idm.IdRepoException)103 SSOException (com.iplanet.sso.SSOException)94 AMIdentity (com.sun.identity.idm.AMIdentity)85 Set (java.util.Set)82 HashSet (java.util.HashSet)58 SSOToken (com.iplanet.sso.SSOToken)56 IdSearchControl (com.sun.identity.idm.IdSearchControl)36 IdSearchResults (com.sun.identity.idm.IdSearchResults)36 Iterator (java.util.Iterator)32 CLIException (com.sun.identity.cli.CLIException)29 HashMap (java.util.HashMap)29 IdType (com.sun.identity.idm.IdType)28 Map (java.util.Map)27 IOutput (com.sun.identity.cli.IOutput)26 SMSException (com.sun.identity.sm.SMSException)24 OrganizationConfigManager (com.sun.identity.sm.OrganizationConfigManager)20 List (java.util.List)13 AMConsoleException (com.sun.identity.console.base.model.AMConsoleException)12 Callback (javax.security.auth.callback.Callback)6