<commit_before>package org.jivesoftware.openfire.clearspace;

import org.dom4j.Element;
import static org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.StringUtils;

import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import java.util.StringTokenizer;

/**
 * Implements the CLEARSPACE server-side SASL mechanism.
 *
 * @author <NAME>
 */
public class ClearspaceSaslServer implements SaslServer {
    private boolean completed;
    private String jid;

    public ClearspaceSaslServer() {
        this.completed = false;
    }

    /**
     * Returns the mechanism name of this SASL server.
     * (e.g. "CRAM-MD5", "GSSAPI").
     *
     * @return A non-null string representing the mechanism name.
     */
    public String getMechanismName() {
        return "CLEARSPACE";
    }

    /**
     * Evaluates the response data and generates a challenge.
     * <p/>
     * If a response is received from the client during the authentication
     * process, this method is called to prepare an appropriate next
     * challenge to submit to the client. The challenge is null if the
     * authentication has succeeded and no more challenge data is to be sent
     * to the client. It is non-null if the authentication must be continued
     * by sending a challenge to the client, or if the authentication has
     * succeeded but challenge data needs to be processed by the client.
     * <tt>isComplete()</tt> should be called
     * after each call to <tt>evaluateResponse()</tt>,to determine if any further
     * response is needed from the client.
     *
     * @param response The non-null (but possibly empty) response sent
     *                 by the client.
     * @return The possibly null challenge to send to the client.
     *         It is null if the authentication has succeeded and there is
     *         no more challenge data to be sent to the client.
     * @throws javax.security.sasl.SaslException
     *          If an error occurred while processing
     *          the response or generating a challenge.
     */
    public byte[] evaluateResponse(byte[] response) throws SaslException {
        ClearspaceManager csManager = ClearspaceManager.getInstance();
        String responseStr = new String(response);

        // Parse data and obtain jid & random string
        StringTokenizer tokens = new StringTokenizer(responseStr, "\u0000");
        if (tokens.countTokens() != 2) {
            // Info was not provided correctly
            completed = false;
            return null;
        }

        jid = tokens.nextToken();

        try {
            responseStr = StringUtils.encodeBase64(responseStr);
            Element resultElement = csManager.executeRequest(GET, "groupChatAuthService/isAuthTokenValid/" + responseStr);
            if ("true".equals(WSUtils.getReturn(resultElement))) {
                completed = true;
            }
            else {
                // Failed to authenticate the user so throw an error so SASL failure is returned
                throw new SaslException("SASL CLEARSPACE: user not authorized: " + jid);
            }
        } catch (Exception e) {
            Log.error("Failed communicating with Clearspace" , e);
            throw new SaslException("SASL CLEARSPACE: user not authorized due to an error: " + jid);
        }

        return null;
    }

    /**
     * Determines whether the authentication exchange has completed.
     * This method is typically called after each invocation of
     * <tt>evaluateResponse()</tt> to determine whether the
     * authentication has completed successfully or should be continued.
     *
     * @return true if the authentication exchange has completed; false otherwise.
     */<commit_msg>Better handling of exceptions.<commit_after>package org.jivesoftware.openfire.clearspace;

import org.dom4j.Element;
import static org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.StringUtils;

import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import java.util.StringTokenizer;

/**
 * Implements the CLEARSPACE server-side SASL mechanism.
 *
 * @author <NAME>
 */
public class ClearspaceSaslServer implements SaslServer {
    private boolean completed;
    private String jid;

    public ClearspaceSaslServer() {
        this.completed = false;
    }

    /**
     * Returns the mechanism name of this SASL server.
     * (e.g. "CRAM-MD5", "GSSAPI").
     *
     * @return A non-null string representing the mechanism name.
     */
    public String getMechanismName() {
        return "CLEARSPACE";
    }

    /**
     * Evaluates the response data and generates a challenge.
     * <p/>
     * If a response is received from the client during the authentication
     * process, this method is called to prepare an appropriate next
     * challenge to submit to the client. The challenge is null if the
     * authentication has succeeded and no more challenge data is to be sent
     * to the client. It is non-null if the authentication must be continued
     * by sending a challenge to the client, or if the authentication has
     * succeeded but challenge data needs to be processed by the client.
     * <tt>isComplete()</tt> should be called
     * after each call to <tt>evaluateResponse()</tt>,to determine if any further
     * response is needed from the client.
     *
     * @param response The non-null (but possibly empty) response sent
     *                 by the client.
     * @return The possibly null challenge to send to the client.
     *         It is null if the authentication has succeeded and there is
     *         no more challenge data to be sent to the client.
     * @throws javax.security.sasl.SaslException
     *          If an error occurred while processing
     *          the response or generating a challenge.
     */
    public byte[] evaluateResponse(byte[] response) throws SaslException {
        ClearspaceManager csManager = ClearspaceManager.getInstance();
        String responseStr = new String(response);

        // Parse data and obtain jid & random string
        StringTokenizer tokens = new StringTokenizer(responseStr, "\u0000");
        if (tokens.countTokens() != 2) {
            // Info was not provided correctly
            completed = false;
            return null;
        }

        jid = tokens.nextToken();

        try {
            responseStr = StringUtils.encodeBase64(responseStr);
            Element resultElement =
                    csManager.executeRequest(GET, "groupChatAuthService/isAuthTokenValid/" + responseStr);
            if ("true".equals(WSUtils.getReturn(resultElement))) {
                completed = true;
            }
            else {
                // Failed to authenticate the user so throw an error so SASL failure is returned
                throw new SaslException("SASL CLEARSPACE: user not authorized: " + jid);
            }
        } catch (SaslException e) {
            // rethrow exception
            throw e;
        } catch (Exception e) {
            Log.error("Failed communicating with Clearspace", e);
            throw new SaslException("SASL CLEARSPACE: user not authorized due to an error: " + jid);
        }

        return null;
    }

    /**
     * Determines whether the authentication exchange has completed.
     * This method is typically called after each invocation of
     * <tt>evaluateResponse()</tt> to determine whether the
     * authentication has completed successfully or should be continued.
     *
     * @return true if the authentication exchange has completed; false otherwise.
     */
{'fraction_non_alphanumeric': 0.07532133676092545, 'fraction_numerical': 0.002313624678663239, 'mean_word_length': 2.4736607142857143, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1090279', 'n_tokens_mistral': 2012, 'n_tokens_neox': 1971, 'n_words': 738}