<commit_before>/*
 *
 *   Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *   WSO2 Inc. licenses this file to you under the Apache License,
 *   Version 2.0 (the "License"); you may not use this file except
 *   in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing,
 *   software distributed under the License is distributed on an
 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *   KIND, either express or implied.  See the License for the
 *   specific language governing permissions and limitations
 *   under the License.
 * /
 */

package org.wso2.carbon.identity.oauth2.dao;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants;
import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.base.IdentityConstants;
import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.oauth.common.OAuthConstants;
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.internal.OAuth2ServiceComponentHolder;
import org.wso2.carbon.identity.oauth2.model.AuthzCodeDO;
import org.wso2.carbon.identity.oauth2.util.OAuth2TokenUtil;
import org.wso2.carbon.identity.oauth2.util.OAuth2Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;

/*
NOTE
This is the very first step of moving to simplified architecture for token persistence. New set of DAO classes  for
each purpose  and factory class to get instance of each DAO classes were introduced  during  this step. Further methods
 on org.wso2.carbon.identity.oauth2.dao.TokenMgtDAO were distributed among new set of classes, each of these method
 need to be reviewed  and refactored  during next step.
 */
public class AuthorizationCodeDAOImpl extends AbstractOAuthDAO implements AuthorizationCodeDAO {

    private final Log log = LogFactory.getLog(AuthorizationCodeDAOImpl.class);

    private static final String IDN_OAUTH2_AUTHORIZATION_CODE = "IDN_OAUTH2_AUTHORIZATION_CODE";
    private boolean isHashDisabled = OAuth2Util.isHashDisabled();

    @Override
    public void insertAuthorizationCode(String authzCode, String consumerKey, String callbackUrl,
                                        AuthzCodeDO authzCodeDO) throws IdentityOAuth2Exception {

        if (!isPersistenceEnabled()) {
            return;
        }

        if (log.isDebugEnabled()) {
            if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.AUTHORIZATION_CODE)) {
                log.debug("Persisting authorization code (hashed): " + DigestUtils.sha256Hex(authzCode) + " for " +
                        "client: " + consumerKey + " user: " + authzCodeDO.getAuthorizedUser().toString());
            } else {
                log.debug("Persisting authorization code for client: " + consumerKey + " user: " + authzCodeDO
                        .getAuthorizedUser().toString());
            }
        }
        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        String userDomain = authzCodeDO.getAuthorizedUser().getUserStoreDomain();
        String authenticatedIDP;
        if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
            if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && authzCodeDO.getAuthorizedUser()
                    .isFederatedUser()) {
                authenticatedIDP = authzCodeDO.getAuthorizedUser().getFederatedIdPName();
                userDomain = OAuth2Util.getFederatedUserDomain(authenticatedIDP);
            } else {
                authenticatedIDP = FrameworkConstants.LOCAL_IDP_NAME;
            }
        } else {
            authenticatedIDP = authzCodeDO.getAuthorizedUser().getFederatedIdPName();
            if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && authzCodeDO.getAuthorizedUser()
                    .isFederatedUser()) {
                userDomain = OAuth2Util.getFederatedUserDomain(authenticatedIDP);
            }
        }

        try {
            String sql;
            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                sql = SQLQueries.STORE_AUTHORIZATION_CODE_WITH_PKCE_IDP_NAME;
            } else {
                sql = SQLQueries.STORE_AUTHORIZATION_CODE_WITH_PKCE;
            }
            prepStmt = connection.prepareStatement(sql);

            prepStmt.setString(1, authzCodeDO.getAuthzCodeId());
            prepStmt.setString(2, getPersistenceProcessor().getProcessedAuthzCode(authzCode));
            prepStmt.setString(3, callbackUrl);
            prepStmt.setString(4, OAuth2Util.buildScopeString(authzCodeDO.getScope()));
            prepStmt.setString(5, authzCodeDO.getAuthorizedUser().getUserName());
            prepStmt.setString(6, OAuth2Util.getSanitizedUserStoreDomain(userDomain));
            int tenantId = OAuth2Util.getTenantId(authzCodeDO.getAuthorizedUser().getTenantDomain());
            prepStmt.setInt(7, tenantId);
            prepStmt.setTimestamp(8, authzCodeDO.getIssuedTime(),
                    Calendar.getInstance(TimeZone.getTimeZone(UTC)));
            prepStmt.setLong(9, authzCodeDO.getValidityPeriod());
            prepStmt.setString(10, authzCodeDO.getAuthorizedUser().getAuthenticatedSubjectIdentifier());
            prepStmt.setString(11, authzCodeDO.getPkceCodeChallenge());
            prepStmt.setString(12, authzCodeDO.getPkceCodeChallengeMethod());
            //insert the hash value of the authorization code
            prepStmt.setString(13, getHashingPersistenceProcessor().getProcessedAuthzCode(authzCode));
            prepStmt.setString(14, getPersistenceProcessor().getProcessedClientId(consumerKey));
            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                prepStmt.setString(15, authenticatedIDP);
                prepStmt.setInt(16, tenantId);
            }

            prepStmt.execute();
            connection.commit();
        } catch (SQLException e) {
            throw new IdentityOAuth2Exception("Error when storing the authorization code for consumer key : " +
                    consumerKey, e);
        } finally {
            IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);<commit_msg>Set userdomain as null for fed user when persisting<commit_after>/*
 *
 *   Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *   WSO2 Inc. licenses this file to you under the Apache License,
 *   Version 2.0 (the "License"); you may not use this file except
 *   in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing,
 *   software distributed under the License is distributed on an
 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *   KIND, either express or implied.  See the License for the
 *   specific language governing permissions and limitations
 *   under the License.
 * /
 */

package org.wso2.carbon.identity.oauth2.dao;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants;
import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.base.IdentityConstants;
import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.oauth.common.OAuthConstants;
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.internal.OAuth2ServiceComponentHolder;
import org.wso2.carbon.identity.oauth2.model.AuthzCodeDO;
import org.wso2.carbon.identity.oauth2.util.OAuth2TokenUtil;
import org.wso2.carbon.identity.oauth2.util.OAuth2Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;

/*
NOTE
This is the very first step of moving to simplified architecture for token persistence. New set of DAO classes  for
each purpose  and factory class to get instance of each DAO classes were introduced  during  this step. Further methods
 on org.wso2.carbon.identity.oauth2.dao.TokenMgtDAO were distributed among new set of classes, each of these method
 need to be reviewed  and refactored  during next step.
 */
public class AuthorizationCodeDAOImpl extends AbstractOAuthDAO implements AuthorizationCodeDAO {

    private final Log log = LogFactory.getLog(AuthorizationCodeDAOImpl.class);

    private static final String IDN_OAUTH2_AUTHORIZATION_CODE = "IDN_OAUTH2_AUTHORIZATION_CODE";
    private boolean isHashDisabled = OAuth2Util.isHashDisabled();

    @Override
    public void insertAuthorizationCode(String authzCode, String consumerKey, String callbackUrl,
                                        AuthzCodeDO authzCodeDO) throws IdentityOAuth2Exception {

        if (!isPersistenceEnabled()) {
            return;
        }

        if (log.isDebugEnabled()) {
            if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.AUTHORIZATION_CODE)) {
                log.debug("Persisting authorization code (hashed): " + DigestUtils.sha256Hex(authzCode) + " for " +
                        "client: " + consumerKey + " user: " + authzCodeDO.getAuthorizedUser().toString());
            } else {
                log.debug("Persisting authorization code for client: " + consumerKey + " user: " + authzCodeDO
                        .getAuthorizedUser().toString());
            }
        }
        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        String userDomain = authzCodeDO.getAuthorizedUser().getUserStoreDomain();
        String authenticatedIDP;
        if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
            if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && authzCodeDO.getAuthorizedUser()
                    .isFederatedUser()) {
                authenticatedIDP = authzCodeDO.getAuthorizedUser().getFederatedIdPName();
            } else {
                authenticatedIDP = FrameworkConstants.LOCAL_IDP_NAME;
            }
        } else {
            authenticatedIDP = authzCodeDO.getAuthorizedUser().getFederatedIdPName();
            if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && authzCodeDO.getAuthorizedUser()
                    .isFederatedUser()) {
                userDomain = OAuth2Util.getFederatedUserDomain(authenticatedIDP);
            }
        }

        try {
            String sql;
            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                sql = SQLQueries.STORE_AUTHORIZATION_CODE_WITH_PKCE_IDP_NAME;
            } else {
                sql = SQLQueries.STORE_AUTHORIZATION_CODE_WITH_PKCE;
            }
            prepStmt = connection.prepareStatement(sql);

            prepStmt.setString(1, authzCodeDO.getAuthzCodeId());
            prepStmt.setString(2, getPersistenceProcessor().getProcessedAuthzCode(authzCode));
            prepStmt.setString(3, callbackUrl);
            prepStmt.setString(4, OAuth2Util.buildScopeString(authzCodeDO.getScope()));
            prepStmt.setString(5, authzCodeDO.getAuthorizedUser().getUserName());

            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled() &&
                    !OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() &&
                    authzCodeDO.getAuthorizedUser().isFederatedUser()) {
                // Setting null as a federated user does not have a user store domain.
                prepStmt.setString(6, null);
            } else {
                prepStmt.setString(6, OAuth2Util.getSanitizedUserStoreDomain(userDomain));
            }

            int tenantId = OAuth2Util.getTenantId(authzCodeDO.getAuthorizedUser().getTenantDomain());
            prepStmt.setInt(7, tenantId);
            prepStmt.setTimestamp(8, authzCodeDO.getIssuedTime(),
                    Calendar.getInstance(TimeZone.getTimeZone(UTC)));
            prepStmt.setLong(9, authzCodeDO.getValidityPeriod());
            prepStmt.setString(10, authzCodeDO.getAuthorizedUser().getAuthenticatedSubjectIdentifier());
            prepStmt.setString(11, authzCodeDO.getPkceCodeChallenge());
            prepStmt.setString(12, authzCodeDO.getPkceCodeChallengeMethod());
            //insert the hash value of the authorization code
            prepStmt.setString(13, getHashingPersistenceProcessor().getProcessedAuthzCode(authzCode));
            prepStmt.setString(14, getPersistenceProcessor().getProcessedClientId(consumerKey));
            if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
                prepStmt.setString(15, authenticatedIDP);
                prepStmt.setInt(16, tenantId);
            }

            prepStmt.execute();
            connection.commit();
        } catch (SQLException e) {
            throw new IdentityOAuth2Exception("Error when storing the authorization code for consumer key : " +
                    consumerKey, e);
        } finally {
            IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
{'fraction_non_alphanumeric': 0.08856264936838512, 'fraction_numerical': 0.010583817002389894, 'mean_word_length': 3.1690862510674638, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2283521', 'n_tokens_mistral': 4140, 'n_tokens_neox': 4020, 'n_words': 803}