<commit_before>package uk.ac.ox.oucs.oauth.service;

import net.oauth.*;
import net.oauth.server.OAuthServlet;
import uk.ac.ox.oucs.oauth.domain.Accessor;
import uk.ac.ox.oucs.oauth.domain.Consumer;
import uk.ac.ox.oucs.oauth.exception.ExpiredAccessorException;
import uk.ac.ox.oucs.oauth.exception.InvalidAccessorException;
import uk.ac.ox.oucs.oauth.exception.InvalidConsumerException;
import uk.ac.ox.oucs.oauth.exception.RevokedAccessorException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @author <NAME>
 */
public class OAuthHttpServiceImpl implements OAuthHttpService {
    private OAuthService oAuthService;
    private OAuthValidator oAuthValidator;

    public void setoAuthValidator(OAuthValidator oAuthValidator) {
        this.oAuthValidator = oAuthValidator;
    }

    public void setoAuthService(OAuthService oAuthService) {
        this.oAuthService = oAuthService;
    }

    @Override
    public boolean isValidOAuthRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            OAuthMessage message = OAuthServlet.getMessage(request, null);
            OAuthConsumer oAuthConsumer = Util.convertToOAuthConsumer(oAuthService.getConsumer(message.getConsumerKey()));
            String token = message.getToken();
            OAuthAccessor oAuthAccessor;
            if (token != null)
                oAuthAccessor = Util.convertToOAuthAccessor(oAuthService.getAccessor(message.getToken(), Accessor.Type.ACCESS), oAuthConsumer);
            else
                oAuthAccessor = new OAuthAccessor(oAuthConsumer);

            oAuthValidator.validateMessage(message, oAuthAccessor);
        } catch (InvalidConsumerException e) {
            handleException(new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN), request, response, true);
        } catch (ExpiredAccessorException e) {
            handleException(new OAuthProblemException(OAuth.Problems.TOKEN_EXPIRED), request, response, true);
        } catch (RevokedAccessorException e) {
            handleException(new OAuthProblemException(OAuth.Problems.TOKEN_REVOKED), request, response, true);
        } catch (InvalidAccessorException e) {
            handleException(new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED), request, response, true);
        } catch (OAuthException e) {
            handleException(new OAuthProblemException(), request, response, true);
        } catch (URISyntaxException e) {
            handleException(e, request, response, true);
        }
        return true;
    }

    @Override
    public String getOAuthAccessToken(HttpServletRequest request) throws IOException {
        OAuthMessage message = OAuthServlet.getMessage(request, null);
        return message.getToken();
    }

    @Override
    public void handleRequestToken(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            OAuthMessage oAuthMessage = OAuthServlet.getMessage(request, null);
            Consumer consumer = oAuthService.getConsumer(oAuthMessage.getConsumerKey());
            OAuthConsumer oAuthConsumer = Util.convertToOAuthConsumer(consumer);
            oAuthValidator.validateMessage(oAuthMessage, new OAuthAccessor(oAuthConsumer));

            String secret = oAuthMessage.getParameter(OAuthConsumer.ACCESSOR_SECRET);
            String callback = oAuthMessage.getParameter(OAuth.OAUTH_CALLBACK);
            Accessor accessor = oAuthService.createRequestAccessor(consumer.getId(), secret, callback);
            OAuthAccessor oAuthAccessor = Util.convertToOAuthAccessor(accessor, oAuthConsumer);

            sendOAuthResponse(response, OAuth.newList(
                    OAuth.OAUTH_TOKEN, oAuthAccessor.requestToken,
                    OAuth.OAUTH_TOKEN_SECRET, oAuthAccessor.tokenSecret,
                    OAuth.OAUTH_CALLBACK_CONFIRMED, "true"));
        } catch (uk.ac.ox.oucs.oauth.exception.OAuthException e) {
            handleException(convertException(e), request, response, true);
        } catch (OAuthException e) {
            handleException(new OAuthProblemException(), request, response, true);
        } catch (URISyntaxException e) {
            handleException(e, request, response, true);
        }
    }

    @Override
    public void handleGetAccessToken(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            OAuthMessage oAuthMessage = OAuthServlet.getMessage(request, null);
            Accessor requestAccessor = oAuthService.getAccessor(oAuthMessage.getToken(), Accessor.Type.REQUEST_AUTHORISED);
            Consumer consumer = oAuthService.getConsumer(requestAccessor.getConsumerId());
            OAuthConsumer oAuthConsumer = Util.convertToOAuthConsumer(consumer);
            OAuthAccessor oAuthAccessor = Util.convertToOAuthAccessor(requestAccessor, oAuthConsumer);
            oAuthValidator.validateMessage(oAuthMessage, oAuthAccessor);

            Accessor accessAccessor = oAuthService.createAccessAccessor(requestAccessor.getToken());
            sendOAuthResponse(response, OAuth.newList(
                    OAuth.OAUTH_TOKEN, accessAccessor.getToken(),
                    OAuth.OAUTH_TOKEN_SECRET, accessAccessor.getSecret()));
        } catch (uk.ac.ox.oucs.oauth.exception.OAuthException e) {
            handleException(convertException(e), request, response, true);
        } catch (OAuthException e) {
            handleException(new OAuthProblemException(), request, response, true);
        } catch (URISyntaxException e) {
            handleException(e, request, response, true);
        }
    }

    @Override
    public void handleRequestAuthorisation(HttpServletRequest request, HttpServletResponse response, boolean authorised, String token, String verifier, String userId) throws IOException {
        Accessor accessor = oAuthService.getAccessor(token, Accessor.Type.REQUEST_AUTHORISING);
        Consumer consumer = oAuthService.getConsumer(accessor.getConsumerId());
        if (authorised) {
            accessor = oAuthService.authoriseToken(accessor.getToken(), verifier, userId);
            if (accessor.getCallbackUrl().equals(OAuthService.OUT_OF_BAND_CALLBACK)) {
                response.setContentType("text/plain");
                PrintWriter out = response.getWriter();
                out.println("You have successfully authorized '" + consumer.getName() + "'.\n" +
                        "The authorisation token is: " + accessor.getToken() + "\n" +
                        "Please close this browser window and click continue in the client.");
                out.flush();
                out.close();
            } else {
                String callbackUrl = OAuth.addParameters(accessor.getCallbackUrl(),
                        OAuth.OAUTH_TOKEN, accessor.getToken(),
                        OAuth.OAUTH_VERIFIER, OAuth.OAUTH_VERIFIER);

                response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
                response.setHeader("Location", callbackUrl);
            }
        } else {
            if (accessor.getCallbackUrl().equals(OAuthService.OUT_OF_BAND_CALLBACK)) {
                response.setContentType("text/plain");
                PrintWriter out = response.getWriter();
                out.println("You have not  authorized '" + consumer.getName() + "'.\n" +
                        "Please close this browser window and click continue in the client.");
                out.flush();
                out.close();
            } else {
                response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
                response.setHeader("Location", accessor.getCallbackUrl());
            }

        }
    }

    /**
     * Sends a response respecting the OAuth format
     * <p>
     * The content type of the response is "application/x-www-form-urlencoded"
     * </p>
     *
     * @param response   HttpServletResponse used to send the response
     * @param parameters List of parameters in the form of key/value
     * @throws IOException
     */
    private static void sendOAuthResponse(HttpServletResponse response, List<OAuth.Parameter> parameters) throws IOException {<commit_msg>In case of invalid token authorisation, return to consumer<commit_after>package uk.ac.ox.oucs.oauth.service;

import net.oauth.*;
import net.oauth.server.OAuthServlet;
import uk.ac.ox.oucs.oauth.domain.Accessor;
import uk.ac.ox.oucs.oauth.domain.Consumer;
import uk.ac.ox.oucs.oauth.exception.ExpiredAccessorException;
import uk.ac.ox.oucs.oauth.exception.InvalidAccessorException;
import uk.ac.ox.oucs.oauth.exception.InvalidConsumerException;
import uk.ac.ox.oucs.oauth.exception.RevokedAccessorException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @author <NAME>
 */
public class OAuthHttpServiceImpl implements OAuthHttpService {
    private OAuthService oAuthService;
    private OAuthValidator oAuthValidator;

    public void setoAuthValidator(OAuthValidator oAuthValidator) {
        this.oAuthValidator = oAuthValidator;
    }

    public void setoAuthService(OAuthService oAuthService) {
        this.oAuthService = oAuthService;
    }

    @Override
    public boolean isValidOAuthRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            OAuthMessage message = OAuthServlet.getMessage(request, null);
            OAuthConsumer oAuthConsumer = Util.convertToOAuthConsumer(oAuthService.getConsumer(message.getConsumerKey()));
            String token = message.getToken();
            OAuthAccessor oAuthAccessor;
            if (token != null)
                oAuthAccessor = Util.convertToOAuthAccessor(oAuthService.getAccessor(message.getToken(), Accessor.Type.ACCESS), oAuthConsumer);
            else
                oAuthAccessor = new OAuthAccessor(oAuthConsumer);

            oAuthValidator.validateMessage(message, oAuthAccessor);
        } catch (InvalidConsumerException e) {
            handleException(new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN), request, response, true);
        } catch (ExpiredAccessorException e) {
            handleException(new OAuthProblemException(OAuth.Problems.TOKEN_EXPIRED), request, response, true);
        } catch (RevokedAccessorException e) {
            handleException(new OAuthProblemException(OAuth.Problems.TOKEN_REVOKED), request, response, true);
        } catch (InvalidAccessorException e) {
            handleException(new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED), request, response, true);
        } catch (OAuthException e) {
            handleException(new OAuthProblemException(), request, response, true);
        } catch (URISyntaxException e) {
            handleException(e, request, response, true);
        }
        return true;
    }

    @Override
    public String getOAuthAccessToken(HttpServletRequest request) throws IOException {
        OAuthMessage message = OAuthServlet.getMessage(request, null);
        return message.getToken();
    }

    @Override
    public void handleRequestToken(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            OAuthMessage oAuthMessage = OAuthServlet.getMessage(request, null);
            Consumer consumer = oAuthService.getConsumer(oAuthMessage.getConsumerKey());
            OAuthConsumer oAuthConsumer = Util.convertToOAuthConsumer(consumer);
            oAuthValidator.validateMessage(oAuthMessage, new OAuthAccessor(oAuthConsumer));

            String secret = oAuthMessage.getParameter(OAuthConsumer.ACCESSOR_SECRET);
            String callback = oAuthMessage.getParameter(OAuth.OAUTH_CALLBACK);
            Accessor accessor = oAuthService.createRequestAccessor(consumer.getId(), secret, callback);
            OAuthAccessor oAuthAccessor = Util.convertToOAuthAccessor(accessor, oAuthConsumer);

            sendOAuthResponse(response, OAuth.newList(
                    OAuth.OAUTH_TOKEN, oAuthAccessor.requestToken,
                    OAuth.OAUTH_TOKEN_SECRET, oAuthAccessor.tokenSecret,
                    OAuth.OAUTH_CALLBACK_CONFIRMED, "true"));
        } catch (uk.ac.ox.oucs.oauth.exception.OAuthException e) {
            handleException(convertException(e), request, response, true);
        } catch (OAuthException e) {
            handleException(new OAuthProblemException(), request, response, true);
        } catch (URISyntaxException e) {
            handleException(e, request, response, true);
        }
    }

    @Override
    public void handleGetAccessToken(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            OAuthMessage oAuthMessage = OAuthServlet.getMessage(request, null);
            Accessor requestAccessor = oAuthService.getAccessor(oAuthMessage.getToken(), Accessor.Type.REQUEST_AUTHORISED);
            Consumer consumer = oAuthService.getConsumer(requestAccessor.getConsumerId());
            OAuthConsumer oAuthConsumer = Util.convertToOAuthConsumer(consumer);
            OAuthAccessor oAuthAccessor = Util.convertToOAuthAccessor(requestAccessor, oAuthConsumer);
            oAuthValidator.validateMessage(oAuthMessage, oAuthAccessor);

            Accessor accessAccessor = oAuthService.createAccessAccessor(requestAccessor.getToken());
            sendOAuthResponse(response, OAuth.newList(
                    OAuth.OAUTH_TOKEN, accessAccessor.getToken(),
                    OAuth.OAUTH_TOKEN_SECRET, accessAccessor.getSecret()));
        } catch (uk.ac.ox.oucs.oauth.exception.OAuthException e) {
            handleException(convertException(e), request, response, true);
        } catch (OAuthException e) {
            handleException(new OAuthProblemException(), request, response, true);
        } catch (URISyntaxException e) {
            handleException(e, request, response, true);
        }
    }

    @Override
    public void handleRequestAuthorisation(HttpServletRequest request, HttpServletResponse response, boolean authorised, String token, String verifier, String userId) throws IOException, ServletException {
        try {
            Accessor accessor = oAuthService.getAccessor(token, Accessor.Type.REQUEST_AUTHORISING);
            Consumer consumer = oAuthService.getConsumer(accessor.getConsumerId());
            if (authorised) {
                accessor = oAuthService.authoriseAccessor(accessor.getToken(), verifier, userId);
                if (accessor.getCallbackUrl().equals(OAuthService.OUT_OF_BAND_CALLBACK)) {
                    response.setContentType("text/plain");
                    PrintWriter out = response.getWriter();
                    out.println("You have successfully authorized '" + consumer.getName() + "'.\n" +
                            "The authorisation token is: " + accessor.getToken() + "\n" +
                            "Please close this browser window and click continue in the client.");
                    out.flush();
                    out.close();
                } else {
                    String callbackUrl = OAuth.addParameters(accessor.getCallbackUrl(),
                            OAuth.OAUTH_TOKEN, accessor.getToken(),
                            OAuth.OAUTH_VERIFIER, OAuth.OAUTH_VERIFIER);

                    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
                    response.setHeader("Location", callbackUrl);
                }
            } else {
                if (accessor.getCallbackUrl().equals(OAuthService.OUT_OF_BAND_CALLBACK)) {
                    response.setContentType("text/plain");
                    PrintWriter out = response.getWriter();
                    out.println("You have not  authorized '" + consumer.getName() + "'.\n" +
                            "Please close this browser window and click continue in the client.");
                    out.flush();
                    out.close();
                } else {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    response.setHeader("Location", accessor.getCallbackUrl());
                }

            }
        } catch (uk.ac.ox.oucs.oauth.exception.OAuthException e) {
            handleException(convertException(e), request, response, true);
        }
    }

    /**
     * Sends a response respecting the OAuth format
     * <p>
     * The content type of the response is "application/x-www-form-urlencoded"
     * </p>
     *
     * @param response   HttpServletResponse used to send the response
     * @param parameters List of parameters in the form of key/value
     * @throws IOException
     */
    private static void sendOAuthResponse(HttpServletResponse response, List<OAuth.Parameter> parameters) throws IOException {
{'fraction_non_alphanumeric': 0.08722741433021806, 'fraction_numerical': 0.0, 'mean_word_length': 2.8937556154537285, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '3111267', 'n_tokens_mistral': 4455, 'n_tokens_neox': 4364, 'n_words': 889}