Search in sources :

Example 1 with StorageOSUserDAO

use of com.emc.storageos.db.client.model.StorageOSUserDAO in project coprhd-controller by CoprHD.

the class StorageOSLdapPersonAttributeDao method getStorageOSUser.

/*
     * @see com.emc.storageos.auth.StorageOSPersonAttributeDao#getPerson(java.lang.String)
     */
@Override
public StorageOSUserDAO getStorageOSUser(final Credentials credentials, ValidationFailureReason[] failureReason) {
    final String username = ((UsernamePasswordCredentials) credentials).getUserName();
    UserAndTenants userAndTenants = getStorageOSUserAndTenants(username, failureReason);
    if (null != userAndTenants) {
        StorageOSUserDAO user = userAndTenants._user;
        Map<URI, UserMapping> tenants = userAndTenants._tenants;
        if (null == tenants || tenants.isEmpty()) {
            _log.error("User {} did not match any tenant", username);
        } else if (tenants.keySet().size() > 1) {
            _log.error("User {} mapped to tenants {}", username, tenants.keySet().toArray());
        } else {
            user.setTenantId(tenants.keySet().iterator().next().toString());
        }
        return user;
    }
    return null;
}
Also used : StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) UserMapping(com.emc.storageos.security.authorization.BasePermissionsHelper.UserMapping) URI(java.net.URI) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 2 with StorageOSUserDAO

use of com.emc.storageos.db.client.model.StorageOSUserDAO in project coprhd-controller by CoprHD.

the class StorageOSLdapPersonAttributeDao method getStorageOSUser.

/*
     * another implementation of getStorageOSUser which throws Exception with error message instead of using failure reason.
     */
@Override
public StorageOSUserDAO getStorageOSUser(final Credentials credentials) {
    final String username = ((UsernamePasswordCredentials) credentials).getUserName();
    ValidationFailureReason[] failureReason = new ValidationFailureReason[1];
    UserAndTenants userAndTenants = getStorageOSUserAndTenants(username, failureReason);
    if (userAndTenants == null) {
        switch(failureReason[0]) {
            case LDAP_CONNECTION_FAILED:
                throw SecurityException.fatals.communicationToLDAPResourceFailed();
            case LDAP_MANAGER_AUTH_FAILED:
                throw SecurityException.fatals.ldapManagerAuthenticationFailed();
            case USER_OR_GROUP_NOT_FOUND_FOR_TENANT:
            default:
                throw APIException.badRequests.principalSearchFailed(username);
        }
    }
    StorageOSUserDAO user = userAndTenants._user;
    Map<URI, UserMapping> tenants = userAndTenants._tenants;
    if (null == tenants || tenants.isEmpty()) {
        _log.error("User {} did not match any tenant", username);
        throw APIException.forbidden.userDoesNotMapToAnyTenancy(user.getUserName());
    }
    if (tenants.keySet().size() > 1) {
        _log.error("User {} mapped to tenants {}", username, tenants.keySet().toArray());
        throw APIException.forbidden.userBelongsToMultiTenancy(user.getUserName(), tenantName(tenants.keySet()));
    }
    user.setTenantId(tenants.keySet().iterator().next().toString());
    return user;
}
Also used : ValidationFailureReason(com.emc.storageos.auth.AuthenticationManager.ValidationFailureReason) StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) UserMapping(com.emc.storageos.security.authorization.BasePermissionsHelper.UserMapping) URI(java.net.URI) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 3 with StorageOSUserDAO

use of com.emc.storageos.db.client.model.StorageOSUserDAO in project coprhd-controller by CoprHD.

the class StorageOSLdapPersonAttributeDao method getStorageOSUserAndTenants.

private UserAndTenants getStorageOSUserAndTenants(String username, ValidationFailureReason[] failureReason, URI tenantURI, List<UserMapping> usermapping) {
    BasePermissionsHelper permissionsHelper = new BasePermissionsHelper(_dbClient, false);
    final String[] userDomain = username.split("@");
    if (userDomain.length < 2) {
        _log.error("Illegal username {} missing domain", username);
        failureReason[0] = ValidationFailureReason.USER_OR_GROUP_NOT_FOUND_FOR_TENANT;
        return null;
    }
    final String domain = userDomain[1];
    final String ldapQuery = LdapFilterUtil.getPersonFilterWithValues(_filter, username);
    if (ldapQuery == null) {
        _log.error("Null query filter from string {} for username", _filter, username);
        failureReason[0] = ValidationFailureReason.USER_OR_GROUP_NOT_FOUND_FOR_TENANT;
        return null;
    }
    StringSet authnProviderDomains = getAuthnProviderDomains(domain);
    List<String> attrs = new ArrayList<String>();
    Map<URI, List<UserMapping>> tenantToMappingMap = permissionsHelper.getAllUserMappingsForDomain(authnProviderDomains);
    if (_searchControls.getReturningAttributes() != null) {
        Collections.addAll(attrs, _searchControls.getReturningAttributes());
    }
    if (tenantURI != null) {
        tenantToMappingMap.put(tenantURI, usermapping);
    }
    printTenantToMappingMap(tenantToMappingMap);
    // Add attributes that need to be released for tenant mapping
    for (List<UserMapping> mappings : tenantToMappingMap.values()) {
        if (mappings == null) {
            continue;
        }
        for (UserMapping mapping : mappings) {
            if (mapping.getAttributes() != null && !mapping.getAttributes().isEmpty()) {
                for (UserMappingAttribute mappingAttribute : mapping.getAttributes()) {
                    attrs.add(mappingAttribute.getKey());
                }
            }
        }
    }
    // Now get the returning attributes from the userGroup table.
    getReturningAttributesFromUserGroups(permissionsHelper, domain, attrs);
    // Create search controls with the additional attributes to return
    SearchControls dnSearchControls = new SearchControls(_searchControls.getSearchScope(), _searchControls.getCountLimit(), _searchControls.getTimeLimit(), attrs.toArray(new String[attrs.size()]), _searchControls.getReturningObjFlag(), _searchControls.getDerefLinkFlag());
    Map<String, List<String>> userMappingAttributes = new HashMap<String, List<String>>();
    StorageOSUserMapper userMapper = new StorageOSUserMapper(username, getDistinguishedNameAttribute(), userMappingAttributes);
    // Execute the query
    @SuppressWarnings("unchecked") final List<StorageOSUserDAO> storageOSUsers = safeLdapSearch(_baseDN, ldapQuery, dnSearchControls, userMapper, failureReason);
    if (null == storageOSUsers) {
        _log.error("Query for user {} failed", username);
        return null;
    }
    StorageOSUserDAO storageOSUser = null;
    try {
        storageOSUser = DataAccessUtils.requiredUniqueResult(storageOSUsers);
        if (null == storageOSUser) {
            _log.error("Query for user {} yielded no results", username);
            failureReason[0] = ValidationFailureReason.USER_OR_GROUP_NOT_FOUND_FOR_TENANT;
            return null;
        }
    } catch (IncorrectResultSizeDataAccessException ex) {
        _log.error("Query for user {} yielded incorrect number of results.", username, ex);
        failureReason[0] = ValidationFailureReason.USER_OR_GROUP_NOT_FOUND_FOR_TENANT;
        return null;
    }
    // If the type is AD then fetch the users tokenGroups
    if (_type == AuthnProvider.ProvidersType.ad) {
        List<String> groups = queryTokenGroups(ldapQuery, storageOSUser);
        StringBuilder groupsString = new StringBuilder("[ ");
        for (String group : groups) {
            groupsString.append(group + " ");
            storageOSUser.addGroup(group);
        }
        groupsString.append("]");
        _log.debug("User {} adding groups {}", username, groupsString);
    } else {
        if (!updateGroupsAndRootGroupsInLDAPByMemberAttribute(storageOSUser, failureReason)) {
            // null means Exception has been thrown and error logged already, empty means no group found in LDAP/AD
            _log.info("User {} is not in any AD/LDAP groups.", storageOSUser.getDistinguishedName());
        }
    }
    // Add the user's group based on the attributes.
    addUserGroupsToUserGroupList(permissionsHelper, domain, storageOSUser);
    return new UserAndTenants(storageOSUser, mapUserToTenant(authnProviderDomains, storageOSUser, userMappingAttributes, tenantToMappingMap, failureReason));
}
Also used : UserMappingAttribute(com.emc.storageos.security.authorization.BasePermissionsHelper.UserMappingAttribute) URI(java.net.URI) StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) UserMapping(com.emc.storageos.security.authorization.BasePermissionsHelper.UserMapping) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) StringSet(com.emc.storageos.db.client.model.StringSet) LdapServerList(com.emc.storageos.auth.impl.LdapServerList) URIQueryResultList(com.emc.storageos.db.client.constraint.URIQueryResultList) SearchControls(javax.naming.directory.SearchControls) BasePermissionsHelper(com.emc.storageos.security.authorization.BasePermissionsHelper)

Example 4 with StorageOSUserDAO

use of com.emc.storageos.db.client.model.StorageOSUserDAO in project coprhd-controller by CoprHD.

the class CustomAuthenticationManager method getUserDetails.

@Override
public UserDetails getUserDetails(final String username) {
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, "");
    for (AuthenticationProvider provider : getAuthenticationProviders()) {
        if (!provider.getHandler().supports(creds)) {
            continue;
        }
        ValidationFailureReason[] reason = new ValidationFailureReason[] { ValidationFailureReason.USER_OR_GROUP_NOT_FOUND_FOR_TENANT };
        StorageOSUserDAO user = provider.getAttributeRepository().getStorageOSUser(creds, reason);
        if (user != null) {
            UserDetails userDetails = new UserDetails();
            userDetails.setUsername(username);
            userDetails.getUserGroupList().addAll(user.getGroups());
            userDetails.setTenant(user.getTenantId());
            return userDetails;
        } else {
            switch(reason[0]) {
                case LDAP_CONNECTION_FAILED:
                    throw SecurityException.fatals.communicationToLDAPResourceFailed();
                case LDAP_MANAGER_AUTH_FAILED:
                    throw SecurityException.fatals.ldapManagerAuthenticationFailed();
                default:
                case USER_OR_GROUP_NOT_FOUND_FOR_TENANT:
                    throw APIException.badRequests.principalSearchFailed(username);
            }
        }
    }
    throw APIException.badRequests.principalSearchFailed(username);
}
Also used : StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) UserDetails(com.emc.storageos.security.resource.UserInfoPage.UserDetails) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 5 with StorageOSUserDAO

use of com.emc.storageos.db.client.model.StorageOSUserDAO in project coprhd-controller by CoprHD.

the class CassandraTokenManager method getToken.

/**
 * Persist/Update the StorageOSUserDAO record
 * generates a new token or reuses an existing token.
 *
 * @return token as a String
 */
@Override
public String getToken(StorageOSUserDAO userDAO) {
    try {
        // always use lower case username for comparing/saving to db
        userDAO.setUserName(userDAO.getUserName().toLowerCase());
        // find an active user record, if there is one with an active token
        List<StorageOSUserDAO> userRecords = getUserRecords(userDAO.getUserName());
        StorageOSUserDAO user = updateDBWithUser(userDAO, userRecords);
        // do we have a user account to use?
        if (user == null) {
            // No, create one
            userDAO.setId(URIUtil.createId(StorageOSUserDAO.class));
            _dbClient.persistObject(userDAO);
            user = userDAO;
        } else {
            // check count
            List<Token> tokensForUserId = getTokensForUserId(user.getId());
            int maxTokens = user.getUserName().equalsIgnoreCase(PROXY_USER) ? _maxTokensForProxyUser : _maxTokensPerUserId;
            double alertTokensSize = (maxTokens * TOKEN_WARNING_EIGHTY_PERCENT);
            if (tokensForUserId.size() >= maxTokens) {
                throw APIException.unauthorized.maxNumberOfTokenExceededForUser();
            } else if (tokensForUserId.size() == (int) alertTokensSize) {
                _log.warn("Prior to creating new token, user {} had {} tokens.", user.getUserName(), tokensForUserId.size());
            }
        }
        return _tokenEncoder.encode(TokenOnWire.createTokenOnWire(createNewToken(user)));
    } catch (DatabaseException ex) {
        _log.error("Exception while persisting user information {}", userDAO.getUserName(), ex);
    } catch (SecurityException e) {
        _log.error("Token encoding exception. ", e);
    }
    return null;
}
Also used : StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) ProxyToken(com.emc.storageos.db.client.model.ProxyToken) Token(com.emc.storageos.db.client.model.Token) SecurityException(com.emc.storageos.security.exceptions.SecurityException) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) DecommissionedConstraint(com.emc.storageos.db.client.constraint.DecommissionedConstraint)

Aggregations

StorageOSUserDAO (com.emc.storageos.db.client.model.StorageOSUserDAO)37 Token (com.emc.storageos.db.client.model.Token)15 ProxyToken (com.emc.storageos.db.client.model.ProxyToken)12 Test (org.junit.Test)12 TokenOnWire (com.emc.storageos.security.authentication.TokenOnWire)11 URI (java.net.URI)10 BaseToken (com.emc.storageos.db.client.model.BaseToken)9 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)9 SignedToken (com.emc.storageos.security.authentication.Base64TokenEncoder.SignedToken)8 CassandraTokenManager (com.emc.storageos.auth.impl.CassandraTokenManager)7 Base64TokenEncoder (com.emc.storageos.security.authentication.Base64TokenEncoder)7 TokenKeyGenerator (com.emc.storageos.security.authentication.TokenKeyGenerator)7 TokenMaxLifeValuesHolder (com.emc.storageos.security.authentication.TokenMaxLifeValuesHolder)7 CoordinatorClient (com.emc.storageos.coordinator.client.service.CoordinatorClient)6 DbClient (com.emc.storageos.db.client.DbClient)6 AlternateIdConstraint (com.emc.storageos.db.client.constraint.AlternateIdConstraint)5 ContainmentConstraint (com.emc.storageos.db.client.constraint.ContainmentConstraint)5 UnauthorizedException (com.emc.storageos.svcs.errorhandling.resources.UnauthorizedException)5 StringSet (com.emc.storageos.db.client.model.StringSet)4 DatabaseException (com.emc.storageos.db.exceptions.DatabaseException)4