Search in sources :

Example 26 with StorageOSUserDAO

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

the class StorageOSUserMapper method mapFromAttributes.

/*
     * @see org.springframework.ldap.core.AttributesMapper#mapFromAttributes(javax.naming.directory.Attributes)
     * creates StorageOSUserDAO from attributes
     */
@Override
public Object mapFromAttributes(Attributes attributes) throws NamingException {
    StorageOSUserDAO storageOSUser = new StorageOSUserDAO();
    storageOSUser.setUserName(_username);
    NamingEnumeration<? extends Attribute> attributesEnumeration = attributes.getAll();
    while (attributesEnumeration.hasMoreElements()) {
        Attribute attribute = attributesEnumeration.nextElement();
        NamingEnumeration<?> attributeValues = attribute.getAll();
        if (attribute.getID().equals(_distinguishedNameAttribute)) {
            if (null != attribute.get(0)) {
                storageOSUser.setDistinguishedName(attribute.get(0).toString());
            }
        }
        List<String> values = new ArrayList<String>();
        while (attributeValues.hasMoreElements()) {
            values.add(attributeValues.nextElement().toString());
        }
        _attrKeyValueMap.put(attribute.getID(), values);
        // Add the returned attributes from the AD/LDAP to the user.
        UserAttributeParam userAttributeParam = new UserAttributeParam(attribute.getID(), new HashSet(values));
        String attributeString = userAttributeParam.toString();
        storageOSUser.addAttribute(attributeString);
        _log.debug("Adding attribute {} to user", attributeString);
    }
    return storageOSUser;
}
Also used : StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) UserAttributeParam(com.emc.storageos.model.usergroup.UserAttributeParam) HashSet(java.util.HashSet)

Example 27 with StorageOSUserDAO

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

the class StorageOSLocalPersonAttributeDao method getStorageOSUser.

@Override
public StorageOSUserDAO getStorageOSUser(final Credentials credentials, ValidationFailureReason[] failureReason) {
    String uid = ((UsernamePasswordCredentials) credentials).getUserName();
    if (uid == null) {
        throw APIException.badRequests.theParametersAreNotValid(Credentials.class.getName());
    }
    String rootTenantId = _permissionsHelper.getRootTenant().getId().toString();
    StorageOSUserDAO storageOSUser = new StorageOSUserDAO();
    storageOSUser.setUserName(uid);
    storageOSUser.setTenantId(rootTenantId);
    storageOSUser.setIsLocal(true);
    return storageOSUser;
}
Also used : StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 28 with StorageOSUserDAO

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

the class AuthenticationResource method formlogin.

/**
 * Authenticates a user with credentials provided in the form data of the request.
 * This method is for internal use by formlogin page.
 *
 * @brief INTERNAL USE
 *
 * @param request the login request from the client.
 * @param servletResponse the response to be sent out to client.
 * @param service to be used to redirect on successful authentication.
 * @param source to be used to identify if the request is coming from portal
 *               or some other client.
 * @param fragment to used to identify the service catalog to redirect on
 *                 successful authentication.
 *
 * @return On successful authentication the client will be redirected to the provided service.
 * @throws IOException
 */
@POST
@Produces({ MediaType.APPLICATION_XML, MediaType.TEXT_HTML })
@Consumes("application/x-www-form-urlencoded")
@Path("formlogin")
public Response formlogin(@Context HttpServletRequest request, @Context HttpServletResponse servletResponse, @QueryParam("service") String service, @QueryParam("src") String source, @QueryParam("fragment") String fragment, MultivaluedMap<String, String> formData) throws IOException {
    boolean isPasswordExpired = false;
    String loginError = null;
    if (service == null || service.isEmpty()) {
        loginError = FORM_LOGIN_POST_NO_SERVICE_ERROR;
    }
    String updatedService = service;
    if (StringUtils.isNotBlank(service) && StringUtils.isNotBlank(fragment)) {
        updatedService = updatedService + "#" + fragment;
    }
    // Check invalid login count from the client IP
    boolean updateInvalidLoginCount = true;
    String clientIP = _invLoginManager.getClientIP(request);
    _log.debug("Client IP: {}", clientIP);
    if (_invLoginManager.isTheClientIPBlocked(clientIP) == true) {
        _log.error("The client IP is blocked for too many invalid login attempts: " + clientIP);
        int minutes = _invLoginManager.getTimeLeftToUnblock(clientIP);
        loginError = String.format("%s.<br>Will be cleared within %d minutes", FORM_INVALID_LOGIN_LIMIT_ERROR, minutes);
        updateInvalidLoginCount = false;
    }
    if (null == loginError) {
        String rememberMeStr = formData.getFirst("remember");
        boolean rememberMe = StringUtils.isNotBlank(rememberMeStr) && rememberMeStr.equalsIgnoreCase("true");
        // Look for a token passed in the form. If so, validate it and return it back
        // as a cookie if valid. Else, continue with the normal flow of formlogin to validate
        // credentials
        String tokenFromForm = formData.getFirst(AUTH_FORM_LOGIN_TOKEN_PARAM);
        if (StringUtils.isNotBlank(tokenFromForm)) {
            try {
                StorageOSUserDAO userDAOFromForm = _tokenManager.validateToken(tokenFromForm);
                if (userDAOFromForm != null) {
                    _log.debug("Form login was posted with valid token");
                    return buildLoginResponse(updatedService, source, true, rememberMe, new LoginStatus(userDAOFromForm.getUserName(), tokenFromForm, false), request);
                }
                _log.error("Auth token passed to this formlogin could not be validated and returned null user");
                loginError = FORM_INVALID_AUTH_TOKEN_ERROR;
            } catch (APIException ex) {
                // It is possible that validateToken would throw if the passed in token is unparsable
                // Unlike the regular use case for validatetoken which is done inside api calls, here we are
                // building a response to a web page, so we need to catch this and let the rest of this method
                // proceed which will result in requesting new credentials.
                loginError = FORM_INVALID_AUTH_TOKEN_ERROR;
                _log.error("Auth token passed to this formlogin could not be validated.  Exception: ", ex);
            } catch (URISyntaxException e) {
                loginError = SERVICE_URL_FORMAT_ERROR;
            }
        }
        UsernamePasswordCredentials credentials = getFormCredentials(formData);
        if (null == loginError) {
            loginError = FORM_LOGIN_BAD_CREDS_ERROR;
        }
        try {
            if (credentials != null) {
                StorageOSUserDAO user = authenticateUser(credentials);
                if (user != null) {
                    validateLocalUserExpiration(credentials);
                    String token = _tokenManager.getToken(user);
                    if (token == null) {
                        _log.error("Could not generate token for user: {}", user.getUserName());
                        auditOp(null, null, OperationTypeEnum.AUTHENTICATION, false, null, credentials.getUserName());
                        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
                    }
                    _log.debug("Redirecting to the original service: {}", updatedService);
                    _invLoginManager.removeInvalidRecord(clientIP);
                    auditOp(URI.create(user.getTenantId()), URI.create(user.getUserName()), OperationTypeEnum.AUTHENTICATION, true, null, credentials.getUserName());
                    // If remember me check box is on, set the expiration time.
                    return buildLoginResponse(updatedService, source, true, rememberMe, new LoginStatus(user.getUserName(), token, null != credentials), request);
                }
            } else {
                // Do not update the invalid login count for this client IP if credentials are not provided
                updateInvalidLoginCount = false;
            }
        } catch (APIException e) {
            loginError = e.getMessage();
            if (loginError.contains("expired")) {
                isPasswordExpired = true;
            }
        } catch (URISyntaxException e) {
            loginError = SERVICE_URL_FORMAT_ERROR;
        }
    }
    // Mark this invalid login as a failure in ZK from the client IP
    if (updateInvalidLoginCount) {
        _invLoginManager.markErrorLogin(clientIP);
    }
    if (null != loginError) {
        _log.error(loginError);
    }
    String formLP = null;
    if (isPasswordExpired) {
        formLP = getFormChangePasswordPage(updatedService, source, request.getServerName(), MessageFormat.format(FORM_LOGIN_AUTH_ERROR_ENT, loginError));
    } else {
        formLP = getFormLoginPage(updatedService, source, request.getServerName(), MessageFormat.format(FORM_LOGIN_AUTH_ERROR_ENT, loginError));
    }
    auditOp(null, null, OperationTypeEnum.AUTHENTICATION, false, null, getFormCredentials(formData).getUserName());
    if (formLP != null) {
        return Response.ok(formLP).type(MediaType.TEXT_HTML).cacheControl(_cacheControl).header(HEADER_PRAGMA, HEADER_PRAGMA_VALUE).build();
    } else {
        _log.error("Could not generate custom (form) login page");
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }
}
Also used : StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) APIException(com.emc.storageos.svcs.errorhandling.resources.APIException) URISyntaxException(java.net.URISyntaxException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 29 with StorageOSUserDAO

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

the class AuthenticationResource method tryLogin.

/**
 * See if the user is already logged in or try to login the user
 * if credentials were supplied. Return authentication status
 *
 * @param httpRequest
 * @param service
 * @param setCookie
 * @param servletResponse
 * @param tokenOnly false if either token or credentials can be used to attempt the login. True if only token is accepted.
 * @return LoginStatus of the user.
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
private LoginStatus tryLogin(HttpServletRequest httpRequest, String service, boolean setCookie, HttpServletResponse servletResponse, boolean tokenOnly) throws UnsupportedEncodingException, IOException {
    String newToken = null;
    String userName = null;
    _log.debug("Logging in");
    UsernamePasswordCredentials credentials = tokenOnly ? null : getCredentials(httpRequest);
    if (credentials == null) {
        // check if we already have a user context
        StorageOSUser user = getUserFromContext();
        if (user != null) {
            newToken = user.getToken();
            userName = user.getName();
            _log.debug("Logged in with user from context");
        }
    } else {
        StorageOSUserDAO user = authenticateUser(credentials);
        if (user != null) {
            validateLocalUserExpiration(credentials);
            newToken = _tokenManager.getToken(user);
            if (newToken == null) {
                _log.error("Could not generate token for user: {}", user.getUserName());
                throw new IllegalStateException(MessageFormat.format("Could not generate token for user: {}", user.getUserName()));
            }
            userName = user.getUserName();
            auditOp(URI.create(user.getTenantId()), URI.create(user.getUserName()), OperationTypeEnum.AUTHENTICATION, true, null, credentials.getUserName());
        } else {
            auditOp(null, null, OperationTypeEnum.AUTHENTICATION, false, null, credentials.getUserName());
        }
    }
    return new LoginStatus(userName, newToken, null != credentials);
}
Also used : StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) StorageOSUser(com.emc.storageos.security.authentication.StorageOSUser) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 30 with StorageOSUserDAO

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

the class TokenManagerTests method testTokenLocking.

/**
 * proxy token locking tests with multiple threads
 */
@Test
public void testTokenLocking() throws Exception {
    commonDefaultSetupForSingleNodeTests();
    // Mix 3 threads that get a proxy token for root, 3 threads that get a proxy token
    // for proxyuser, and 2 threads that delete for root, and 2 for proxuyuser.
    int numThreadsUserA = 3;
    int numThreadsUserB = 3;
    int numThreadsDeleteRoot = 2;
    int numThreadsDeleteProxyUser = 2;
    int totalThreads = numThreadsUserA + numThreadsUserB + numThreadsDeleteRoot + numThreadsDeleteProxyUser;
    ExecutorService executor = Executors.newFixedThreadPool(totalThreads);
    final CountDownLatch waitA = new CountDownLatch(numThreadsUserA);
    for (int index = 0; index < numThreadsUserA; index++) {
        executor.submit(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                waitA.countDown();
                waitA.await();
                StorageOSUserDAO userDAO = new StorageOSUserDAO();
                userDAO.setUserName("userA");
                userDAO.setIsLocal(true);
                userDAO.setId((URIUtil.createId(StorageOSUserDAO.class)));
                _dbClient.persistObject(userDAO);
                final String proxyToken = _tokenManager.getProxyToken(userDAO);
                Assert.assertNotNull(proxyToken);
                return null;
            }
        });
    }
    final CountDownLatch waitB = new CountDownLatch(numThreadsUserB);
    for (int index = 0; index < numThreadsUserB; index++) {
        executor.submit(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                waitB.countDown();
                waitB.await();
                StorageOSUserDAO userDAO = new StorageOSUserDAO();
                userDAO.setUserName("userB");
                userDAO.setIsLocal(true);
                userDAO.setId((URIUtil.createId(StorageOSUserDAO.class)));
                _dbClient.persistObject(userDAO);
                final String proxyToken = _tokenManager.getProxyToken(userDAO);
                Assert.assertNotNull(proxyToken);
                return null;
            }
        });
    }
    final CountDownLatch waitC = new CountDownLatch(numThreadsDeleteRoot);
    for (int index = 0; index < numThreadsDeleteRoot; index++) {
        executor.submit(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                waitC.countDown();
                waitC.await();
                StorageOSUserDAO userDAO = new StorageOSUserDAO();
                userDAO.setUserName("userA");
                _tokenManager.deleteAllTokensForUser(userDAO.getUserName(), true);
                return null;
            }
        });
    }
    final CountDownLatch waitD = new CountDownLatch(numThreadsDeleteProxyUser);
    for (int index = 0; index < numThreadsDeleteProxyUser; index++) {
        executor.submit(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                waitD.countDown();
                waitD.await();
                StorageOSUserDAO userDAO = new StorageOSUserDAO();
                userDAO.setUserName("userB");
                _tokenManager.deleteAllTokensForUser(userDAO.getUserName(), true);
                return null;
            }
        });
    }
    executor.shutdown();
    Assert.assertTrue(executor.awaitTermination(60, TimeUnit.SECONDS));
    Assert.assertTrue(getProxyTokenCountForUser("root") <= 1);
    Assert.assertTrue(getProxyTokenCountForUser("proxyuser") <= 1);
}
Also used : StorageOSUserDAO(com.emc.storageos.db.client.model.StorageOSUserDAO) ContainmentConstraint(com.emc.storageos.db.client.constraint.ContainmentConstraint) AlternateIdConstraint(com.emc.storageos.db.client.constraint.AlternateIdConstraint) UnauthorizedException(com.emc.storageos.svcs.errorhandling.resources.UnauthorizedException) IOException(java.io.IOException) Test(org.junit.Test)

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