<commit_before>/*
  Copyright 2012 - 2013 <NAME>

   Licensed 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.pac4j.play;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.pac4j.core.client.BaseClient;
import org.pac4j.core.client.Clients;
import org.pac4j.core.context.HttpConstants;
import org.pac4j.core.credentials.Credentials;
import org.pac4j.core.exception.RequiresHttpAction;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.play.java.JavaWebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Results;

/**
 * This controller is the class to finish the authentication process and logout the user.
 * <p />
 * Public methods : {@link #callback()}, {@link #logoutAndOk()} and {@link #logoutAndRedirect()} must be used in the routes file.
 * 
 * @author <NAME>
 * @since 1.0.0
 */
public class CallbackController extends Controller {
    
    protected static final Logger logger = LoggerFactory.getLogger(CallbackController.class);
    
    /**
     * This method handles the callback call from the provider to finish the authentication process. The credentials and then the profile of
     * the authenticated user is retrieved and the originally requested url (or the specific saved url) is restored.
     * 
     * @return the redirection to the saved request
     */
    @SuppressWarnings({
        "rawtypes", "unchecked"
    })
    public static Result callback() {
        // clients group from config
        final Clients clientsGroup = Config.getClients();
        
        // web context
        final JavaWebContext context = new JavaWebContext(request(), response(), session());
        
        // get the client from its type
        final BaseClient client = (BaseClient) clientsGroup.findClient(context);
        logger.debug("client : {}", client);
        
        // get credentials
        Credentials credentials = null;
        try {
            credentials = client.getCredentials(context);
            logger.debug("credentials : {}", credentials);
        } catch (final RequiresHttpAction e) {
            // requires some specific HTTP action
            final int code = context.getResponseStatus();
            logger.debug("requires HTTP action : {}", code);
            if (code == HttpConstants.UNAUTHORIZED) {
                return unauthorized(Config.getErrorPage401()).as(Constants.HTML_CONTENT_TYPE);
            } else if (code == HttpConstants.TEMP_REDIRECT) {
                return Results.status(HttpConstants.TEMP_REDIRECT);
            } else if (code == HttpConstants.OK) {
                final String content = context.getResponseContent();
                logger.debug("render : {}", content);
                return ok(content);
            }
            final String message = "Unsupported HTTP action : " + code;
            logger.error(message);
            throw new TechnicalException(message);
        }
        
        // get user profile
        final CommonProfile profile = client.getUserProfile(credentials);
        logger.debug("profile : {}", profile);
        
        // get or create sessionId
        final String sessionId = StorageHelper.getOrCreationSessionId(session());
        
        if (profile == null) {
            // save that this kind of authentication has already been attempted and returns a null profile
            StorageHelper.save(sessionId, client.getName() + Constants.ATTEMPTED_AUTHENTICATION_SUFFIX, "true");
        } else {
            // save user profile only if it's not null
            StorageHelper.saveProfile(sessionId, profile);
        }
        
        // get requested url
        final String requestedUrl = StorageHelper.getRequestedUrl(sessionId, client.getName());<commit_msg>support non absolute callback urls<commit_after>/*
  Copyright 2012 - 2013 <NAME>

   Licensed 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.pac4j.play;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.pac4j.core.client.BaseClient;
import org.pac4j.core.client.Clients;
import org.pac4j.core.context.HttpConstants;
import org.pac4j.core.credentials.Credentials;
import org.pac4j.core.exception.RequiresHttpAction;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.play.java.JavaWebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Results;

/**
 * This controller is the class to finish the authentication process and logout the user.
 * <p />
 * Public methods : {@link #callback()}, {@link #logoutAndOk()} and {@link #logoutAndRedirect()} must be used in the routes file.
 * 
 * @author <NAME>
 * @since 1.0.0
 */
public class CallbackController extends Controller {
    
    protected static final Logger logger = LoggerFactory.getLogger(CallbackController.class);
    
    /**
     * This method handles the callback call from the provider to finish the authentication process. The credentials and then the profile of
     * the authenticated user is retrieved and the originally requested url (or the specific saved url) is restored.
     * 
     * @return the redirection to the saved request
     */
    @SuppressWarnings({
        "rawtypes", "unchecked"
    })
    public static Result callback() {
        // clients group from config
        final Clients clientsGroup = Config.getClients();
        
        // web context
        final JavaWebContext context = new JavaWebContext(request(), response(), session());
        
        // get the client from its type
        final BaseClient client = (BaseClient) clientsGroup.findClient(context);
        logger.debug("client : {}", client);
        
        // get credentials
        Credentials credentials = null;
        try {
            credentials = client.getCredentials(context);
            logger.debug("credentials : {}", credentials);
        } catch (final RequiresHttpAction e) {
            // requires some specific HTTP action
            final int code = context.getResponseStatus();
            logger.debug("requires HTTP action : {}", code);
            if (code == HttpConstants.UNAUTHORIZED) {
                return unauthorized(Config.getErrorPage401()).as(Constants.HTML_CONTENT_TYPE);
            } else if (code == HttpConstants.TEMP_REDIRECT) {
                return Results.status(HttpConstants.TEMP_REDIRECT);
            } else if (code == HttpConstants.OK) {
                final String content = context.getResponseContent();
                logger.debug("render : {}", content);
                return ok(content);
            }
            final String message = "Unsupported HTTP action : " + code;
            logger.error(message);
            throw new TechnicalException(message);
        }

        // get user profile
        final CommonProfile profile = client.getUserProfile(credentials, context);
        logger.debug("profile : {}", profile);
        
        // get or create sessionId
        final String sessionId = StorageHelper.getOrCreationSessionId(session());
        
        if (profile == null) {
            // save that this kind of authentication has already been attempted and returns a null profile
            StorageHelper.save(sessionId, client.getName() + Constants.ATTEMPTED_AUTHENTICATION_SUFFIX, "true");
        } else {
            // save user profile only if it's not null
            StorageHelper.saveProfile(sessionId, profile);
        }
        
        // get requested url
        final String requestedUrl = StorageHelper.getRequestedUrl(sessionId, client.getName());
{'fraction_non_alphanumeric': 0.08955393718707329, 'fraction_numerical': 0.006827492034592627, 'mean_word_length': 2.711570945945946, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, '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': '1565755', 'n_tokens_mistral': 2249, 'n_tokens_neox': 2211, 'n_words': 728}