Java Code Examples for org.wso2.carbon.identity.core.util.IdentityUtil#isUserStoreInUsernameCaseSensitive()

The following examples show how to use org.wso2.carbon.identity.core.util.IdentityUtil#isUserStoreInUsernameCaseSensitive() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JDBCIdentityDataStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void updateUserDataValue(String userName, int tenantId, String key, String value) throws SQLException {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(userName, tenantId);
        try {
            String query;
            if (isUsernameCaseSensitive) {
                query = SQLQuery.UPDATE_USER_DATA;
            } else {
                query = SQLQuery.UPDATE_USER_DATA_CASE_INSENSITIVE;
            }
            prepStmt = connection.prepareStatement(query);
            prepStmt.setString(1, value);
            prepStmt.setInt(2, tenantId);
            prepStmt.setString(3, userName);
            prepStmt.setString(4, key);
            prepStmt.executeUpdate();
            connection.commit();
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }

    }
 
Example 2
Source File: JDBCIdentityDataStore.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private boolean isExistingUserDataValue(String userName, int tenantId, String key) throws SQLException {

        Connection connection = IdentityDatabaseUtil.getDBConnection(false);
        PreparedStatement prepStmt = null;
        ResultSet results;
        boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(userName, tenantId);
        try {
            String query;
            if (isUsernameCaseSensitive) {
                query = SQLQuery.CHECK_EXIST_USER_DATA;
            } else {
                query = SQLQuery.CHECK_EXIST_USER_DATA_CASE_INSENSITIVE;
            }
            prepStmt = connection.prepareStatement(query);
            prepStmt.setInt(1, tenantId);
            prepStmt.setString(2, userName);
            prepStmt.setString(3, key);
            results = prepStmt.executeQuery();
            if (results.next()) {
                return true;
            }
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
        return false;
    }
 
Example 3
Source File: JDBCIdentityDataStore.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void updateUserDataValue(String userName, int tenantId, String key, String value) throws SQLException {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(userName, tenantId);
        try {
            String query;
            if (isUsernameCaseSensitive) {
                query = SQLQuery.UPDATE_USER_DATA;
            } else {
                query = SQLQuery.UPDATE_USER_DATA_CASE_INSENSITIVE;
            }
            prepStmt = connection.prepareStatement(query);
            prepStmt.setString(1, value);
            prepStmt.setInt(2, tenantId);
            prepStmt.setString(3, userName);
            prepStmt.setString(4, key);
            prepStmt.executeUpdate();
            IdentityDatabaseUtil.commitTransaction(connection);
        } catch (SQLException e) {
            IdentityDatabaseUtil.rollbackTransaction(connection);
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }

    }
 
Example 4
Source File: JDBCIdentityDataStore.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String userName, UserStoreManager userStoreManager) throws IdentityException {

    super.remove(userName, userStoreManager);
    String domainName = ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).
            getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
    userName = UserCoreUtil.addDomainToName(userName, domainName);
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    try {
        int tenantId = userStoreManager.getTenantId();
        boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(userName, tenantId);
        String query;
        if (isUsernameCaseSensitive) {
            query = SQLQuery.DELETE_USER_DATA;
        } else {
            query = SQLQuery.DELETE_USER_DATA_CASE_INSENSITIVE;
        }
        prepStmt = connection.prepareStatement(query);
        prepStmt.setInt(1, tenantId);
        prepStmt.setString(2, userName);
        prepStmt.execute();
        IdentityDatabaseUtil.commitTransaction(connection);
    } catch (SQLException | UserStoreException e) {
        IdentityDatabaseUtil.rollbackTransaction(connection);
        throw IdentityException.error("Error while reading user identity data", e);
    } finally {
        IdentityDatabaseUtil.closeStatement(prepStmt);
        IdentityDatabaseUtil.closeConnection(connection);
    }
}
 
Example 5
Source File: JDBCIdentityDataStore.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private boolean isExistingUserDataValue(String userName, int tenantId, String key) throws SQLException {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        ResultSet results;
        boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(userName, tenantId);
        try {
            String query;
            if (isUsernameCaseSensitive) {
                query = SQLQuery.CHECK_EXIST_USER_DATA;
            } else {
                query = SQLQuery.CHECK_EXIST_USER_DATA_CASE_INSENSITIVE;
            }
            prepStmt = connection.prepareStatement(query);
            prepStmt.setInt(1, tenantId);
            prepStmt.setString(2, userName);
            prepStmt.setString(3, key);
            results = prepStmt.executeQuery();
            if (results.next()) {
                return true;
            }
            connection.commit();
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
        return false;
    }
 
Example 6
Source File: JDBCIdentityDataStore.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String userName, UserStoreManager userStoreManager) throws IdentityException {

    super.remove(userName, userStoreManager);
    String domainName = ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).
            getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
    userName = UserCoreUtil.addDomainToName(userName, domainName);
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    try {
        int tenantId = userStoreManager.getTenantId();
        boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(userName, tenantId);
        String query;
        if (isUsernameCaseSensitive) {
            query = SQLQuery.DELETE_USER_DATA;
        } else {
            query = SQLQuery.DELETE_USER_DATA_CASE_INSENSITIVE;
        }
        prepStmt = connection.prepareStatement(query);
        prepStmt.setInt(1, tenantId);
        prepStmt.setString(2, userName);
        prepStmt.execute();
        connection.commit();
    } catch (SQLException | UserStoreException e) {
        throw IdentityException.error("Error while reading user identity data", e);
    } finally {
        IdentityDatabaseUtil.closeStatement(prepStmt);
        IdentityDatabaseUtil.closeConnection(connection);
    }
}
 
Example 7
Source File: OAuthCacheRemoveListener.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void entryRemoved(CacheEntryEvent<? extends OAuthCacheKey, ? extends CacheEntry> cacheEntryEvent)
        throws CacheEntryListenerException {

    CacheEntry cacheEntry = cacheEntryEvent.getValue();
    if(cacheEntry == null || !(cacheEntry instanceof AccessTokenDO)){
        return;
    }
    AccessTokenDO accessTokenDO = (AccessTokenDO) cacheEntryEvent.getValue();

    if (accessTokenDO != null) {

        if (log.isDebugEnabled()) {
            log.debug("OAuth cache removed for consumer id : " + accessTokenDO.getConsumerKey());
        }

        boolean isUsernameCaseSensitive = IdentityUtil
                .isUserStoreInUsernameCaseSensitive(accessTokenDO.getAuthzUser().getUserName());
        String cacheKeyString;
        if (isUsernameCaseSensitive){
            cacheKeyString = accessTokenDO.getConsumerKey() + ":" + accessTokenDO.getAuthzUser().getUserName() + ":"
                    + OAuth2Util.buildScopeString(accessTokenDO.getScope());
        }else {
            cacheKeyString =
                    accessTokenDO.getConsumerKey() + ":" + accessTokenDO.getAuthzUser().getUserName().toLowerCase()
                            + ":" + OAuth2Util.buildScopeString(accessTokenDO.getScope());
        }

        OAuthCacheKey oauthcacheKey = new OAuthCacheKey(cacheKeyString);
        OAuthCache oauthCache = OAuthCache.getInstance();

        oauthCache.clearCacheEntry(oauthcacheKey);
        oauthcacheKey = new OAuthCacheKey(accessTokenDO.getAccessToken());

        oauthCache.clearCacheEntry(oauthcacheKey);

    }
}
 
Example 8
Source File: OAuthUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static void clearOAuthCache(String consumerKey, String authorizedUser) {
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authorizedUser);
    if (!isUsernameCaseSensitive) {
        authorizedUser = authorizedUser.toLowerCase();
    }
    clearOAuthCache(consumerKey + ":" + authorizedUser);
}
 
Example 9
Source File: OAuthUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static void clearOAuthCache(String consumerKey, String authorizedUser, String scope) {
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authorizedUser);
    if (!isUsernameCaseSensitive) {
        authorizedUser = authorizedUser.toLowerCase();
    }
    clearOAuthCache(consumerKey + ":" + authorizedUser + ":" + scope);
}
 
Example 10
Source File: OAuthAppDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private boolean isDuplicateApplication(String username, int tenantId, String userDomain, OAuthAppDO consumerAppDTO)
        throws IdentityOAuthAdminException {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet rSet = null;

    boolean isDuplicateApp = false;
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(username, tenantId);

    try {
        String sql = SQLQueries.OAuthAppDAOSQLQueries.CHECK_EXISTING_APPLICATION;
        if (!isUsernameCaseSensitive) {
            sql = sql.replace("USERNAME", "LOWER(USERNAME)");
        }
        prepStmt = connection.prepareStatement(sql);
        if (isUsernameCaseSensitive) {
            prepStmt.setString(1, username);
        } else {
            prepStmt.setString(1, username.toLowerCase());
        }
        prepStmt.setInt(2, tenantId);
        prepStmt.setString(3, userDomain);
        prepStmt.setString(4, consumerAppDTO.getApplicationName());

        rSet = prepStmt.executeQuery();
        if (rSet.next()) {
            isDuplicateApp = true;
        }
        connection.commit();
    } catch (SQLException e) {
        throw new IdentityOAuthAdminException("Error when executing the SQL : " + SQLQueries.OAuthAppDAOSQLQueries.CHECK_EXISTING_APPLICATION, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, rSet, prepStmt);
    }
    return isDuplicateApp;
}
 
Example 11
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param authenticatedUser
 * @return
 * @throws IdentityOAuth2Exception
 */
public Set<String> getAuthorizationCodesForUser(AuthenticatedUser authenticatedUser) throws
        IdentityOAuth2Exception {

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;
    Set<String> authorizationCodes = new HashSet<>();
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authenticatedUser.toString());
    try {
        String sqlQuery = SQLQueries.GET_AUTHORIZATION_CODES_BY_AUTHZUSER;
        if (!isUsernameCaseSensitive) {
            sqlQuery = sqlQuery.replace(AUTHZ_USER, LOWER_AUTHZ_USER);
        }
        ps = connection.prepareStatement(sqlQuery);
        if (isUsernameCaseSensitive) {
            ps.setString(1, authenticatedUser.getUserName());
        } else {
            ps.setString(1, authenticatedUser.getUserName().toLowerCase());
        }
        ps.setString(2,Integer.toString(OAuth2Util.getTenantId(authenticatedUser.getTenantDomain())));
        ps.setString(3, authenticatedUser.getUserStoreDomain());
        rs = ps.executeQuery();
        while (rs.next()){
            authorizationCodes.add(rs.getString(1));
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while revoking Access Token with user Name : " +
                authenticatedUser.getUserName() + " tenant ID : " + OAuth2Util.getTenantId(authenticatedUser
                .getTenantDomain()), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
    return authorizationCodes;
}
 
Example 12
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * @param authenticatedUser
 * @return
 * @throws IdentityOAuth2Exception
 */
public Set<String> getAccessTokensForUser(AuthenticatedUser authenticatedUser) throws
        IdentityOAuth2Exception {
    String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;
    Set<String> accessTokens = new HashSet<>();
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authenticatedUser.toString());
    try {
        if (OAuth2Util.checkAccessTokenPartitioningEnabled() &&
                OAuth2Util.checkUserNameAssertionEnabled()) {
            accessTokenStoreTable = OAuth2Util.getAccessTokenStoreTableFromUserId(authenticatedUser.toString());
        }
        String sqlQuery = SQLQueries.GET_ACCESS_TOKEN_BY_AUTHZUSER.replace(
                IDN_OAUTH2_ACCESS_TOKEN, accessTokenStoreTable);
        if (!isUsernameCaseSensitive){
            sqlQuery = sqlQuery.replace(AUTHZ_USER, LOWER_AUTHZ_USER);
        }
        ps = connection.prepareStatement(sqlQuery);
        if (isUsernameCaseSensitive) {
            ps.setString(1, authenticatedUser.getUserName());
        } else {
            ps.setString(1, authenticatedUser.getUserName().toLowerCase());
        }
        ps.setString(2, Integer.toString(OAuth2Util.getTenantId(authenticatedUser.getTenantDomain())));
        ps.setString(3, OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE);
        ps.setString(4, authenticatedUser.getUserStoreDomain());
        rs = ps.executeQuery();
        while (rs.next()){
            accessTokens.add(rs.getString(1));
        }
        connection.commit();
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Error occurred while revoking Access Token with user Name : " +
                authenticatedUser.getUserName() + " tenant ID : " + OAuth2Util.getTenantId(authenticatedUser
                .getTenantDomain()), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, ps);
    }
    return accessTokens;
}
 
Example 13
Source File: TokenMgtDAO.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * This method is to list the application authorized by OAuth resource owners
 *
 * @param authzUser username of the resource owner
 * @return set of distinct client IDs authorized by user until now
 * @throws IdentityOAuth2Exception if failed to update the access token
 */
public Set<String> getAllTimeAuthorizedClientIds(AuthenticatedUser authzUser) throws IdentityOAuth2Exception {

    String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
    PreparedStatement ps = null;
    Connection connection = IdentityDatabaseUtil.getDBConnection();;
    ResultSet rs = null;
    Set<String> distinctConsumerKeys = new HashSet<>();
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authzUser.toString());
    String tenantDomain = authzUser.getTenantDomain();
    String tenantAwareUsernameWithNoUserDomain = authzUser.getUserName();
    String userDomain = authzUser.getUserStoreDomain();
    if ((userDomain != null)){
        userDomain.toUpperCase();
    }
    try {
        int tenantId = OAuth2Util.getTenantId(tenantDomain);
        if (OAuth2Util.checkAccessTokenPartitioningEnabled() &&
                OAuth2Util.checkUserNameAssertionEnabled()) {
            accessTokenStoreTable = OAuth2Util.getAccessTokenStoreTableFromUserId(authzUser.toString());
        }
        String sqlQuery = SQLQueries.GET_DISTINCT_APPS_AUTHORIZED_BY_USER_ALL_TIME.replace(
                IDN_OAUTH2_ACCESS_TOKEN, accessTokenStoreTable);
        if (!isUsernameCaseSensitive) {
            sqlQuery = sqlQuery.replace(AUTHZ_USER, LOWER_AUTHZ_USER);
        }
        ps = connection.prepareStatement(sqlQuery);
        if (isUsernameCaseSensitive) {
            ps.setString(1, tenantAwareUsernameWithNoUserDomain);
        } else {
            ps.setString(1, tenantAwareUsernameWithNoUserDomain.toLowerCase());
        }
        ps.setInt(2, tenantId);
        ps.setString(3, userDomain);
        rs = ps.executeQuery();
        while (rs.next()) {
            String consumerKey = persistenceProcessor.getPreprocessedClientId(rs.getString(1));
            distinctConsumerKeys.add(consumerKey);
        }
    } catch (SQLException e) {
        throw new IdentityOAuth2Exception(
                "Error occurred while retrieving all distinct Client IDs authorized by " +
                        "User ID : " + authzUser + " until now", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, rs, ps);
    }
    return distinctConsumerKeys;
}
 
Example 14
Source File: OAuth2Util.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the OAuth consumer and return the username of user which own the provided client id and client
 * secret.
 *
 * @param clientId             Consumer Key/Id
 * @param clientSecretProvided Consumer Secret issued during the time of registration
 * @return Username of the user which own client id and client secret if authentication is
 * successful. Empty string otherwise.
 * @throws IdentityOAuthAdminException Error when looking up the credentials from the database
 */
public static String getAuthenticatedUsername(String clientId, String clientSecretProvided)
        throws IdentityOAuthAdminException, IdentityOAuth2Exception, InvalidOAuthClientException {

    boolean cacheHit = false;
    String username = null;
    boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(username);

    if (OAuth2Util.authenticateClient(clientId, clientSecretProvided)) {
        // check cache
        if (cacheEnabled) {
            CacheEntry cacheResult = cache.getValueFromCache(new OAuthCacheKey(clientId + ":" + username));
            if (cacheResult != null && cacheResult instanceof ClientCredentialDO) {
                // Ugh. This is fugly. Have to have a generic way of caching a key:value pair
                username = ((ClientCredentialDO) cacheResult).getClientSecret();
                cacheHit = true;
                if (log.isDebugEnabled()) {
                    log.debug("Username was available in the cache : " +
                            username);
                }
            }
        }

        if (username == null) {
            // Cache miss
            OAuthConsumerDAO oAuthConsumerDAO = new OAuthConsumerDAO();
            username = oAuthConsumerDAO.getAuthenticatedUsername(clientId, clientSecretProvided);
            if (log.isDebugEnabled()) {
                log.debug("Username fetch from the database");
            }
        }

        if (username != null && cacheEnabled && !cacheHit) {
            /**
             * Using the same ClientCredentialDO to host username. Semantically wrong since ClientCredentialDo
             * accept a client secret and we're storing a username in the secret variable. Do we have to make our
             * own cache key and cache entry class every time we need to put something to it? Ideal solution is
             * to have a generalized way of caching a key:value pair
             */
            if (isUsernameCaseSensitive) {
                cache.addToCache(new OAuthCacheKey(clientId + ":" + username), new ClientCredentialDO(username));
            } else {
                cache.addToCache(new OAuthCacheKey(clientId + ":" + username.toLowerCase()),
                        new ClientCredentialDO(username));
            }
            if (log.isDebugEnabled()) {
                log.debug("Caching username : " + username);
            }

        }
    }
    return username;
}
 
Example 15
Source File: KeyManagerUserOperationListener.java    From carbon-apimgt with Apache License 2.0 2 votes vote down vote up
protected boolean isUserStoreInUsernameCaseSensitive(String username) {

        return IdentityUtil.isUserStoreInUsernameCaseSensitive(username);
    }