<commit_before>package org.ctoolkit.restapi.client.identity;

import com.google.api.client.repackaged.com.google.common.base.Strings;
import org.ctoolkit.restapi.client.TokenVerifier;
import org.ctoolkit.restapi.client.UnauthorizedException;

import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * The helper class to wrap identity token verification in to a standalone class.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
@Singleton
public class IdentityTokenResolver
{
    private final TokenVerifier<Identity> tokenVerifier;

    @Inject
    public IdentityTokenResolver( TokenVerifier<Identity> tokenVerifier )
    {

        this.tokenVerifier = tokenVerifier;
    }

    /**
     * Parse identity token taken from given request. It's looking for {@link Identity#GTOKEN} cookie to parse and verify
     * in order to create instance of the {@link Identity}. If no token found or expired, returns <tt>null</tt>.
     *
     * @param httpRequest the current HTTP servlet request
     * @return the parsed token as {@link Identity} instance
     * @throws UnauthorizedException thrown in case of invalid token
     */
    public Identity resolve( HttpServletRequest httpRequest )
    {
        Cookie[] cookies = httpRequest.getCookies();

        if ( cookies == null )
        {
            return null;
        }

        String token = null;

        for ( Cookie cookie : cookies )
        {
            if ( Identity.GTOKEN.equals( cookie.getName() ) )
            {
                token = cookie.getValue();
                break;
            }
        }

        if ( !Strings.isNullOrEmpty( token ) )
        {
            Identity json = tokenVerifier.verifyAndGet( token );

            if ( json.getExpiration().after( new Date() ) )
            {
                return json;
            }
        }

        return null;
    }

    /**
     * Verifies the given token and for positive verification returns an identity instance.
     * Otherwise returns <tt>null</tt>.
     * In case of {@link UnauthorizedException} it will be catched and converted to <tt>null</tt> return value.
     *
     * @param token the token to be verified
     * @return the verified and parsed identity instance or <tt>null</tt> if fails
     */
    public Identity verifyAndGet( @Nullable String token )
    {
        if ( !Strings.isNullOrEmpty( token ) )
        {
            Identity json;
            try
            {
                json = tokenVerifier.verifyAndGet( token );
            }
            catch ( UnauthorizedException e )
            {
                return null;
            }

            if ( json.getExpiration().after( new Date() ) )
            {
                return json;
            }
        }<commit_msg>The identity token resolver helper has been tuned up. Conceptually 2 methods introduced verifyOrThrow and verifyAndGet.<commit_after>package org.ctoolkit.restapi.client.identity;

import com.google.api.client.repackaged.com.google.common.base.Strings;
import org.ctoolkit.restapi.client.TokenVerifier;
import org.ctoolkit.restapi.client.UnauthorizedException;

import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * The helper class to wrap identity token verification in to a standalone class.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
@Singleton
public class IdentityTokenResolver
{
    private final TokenVerifier<Identity> tokenVerifier;

    @Inject
    public IdentityTokenResolver( TokenVerifier<Identity> tokenVerifier )
    {

        this.tokenVerifier = tokenVerifier;
    }

    /**
     * Parse identity token taken from given request. It's looking for {@link Identity#GTOKEN} cookie to parse
     * and verify in order to create instance of the {@link Identity}. If fails throws {@link UnauthorizedException}.
     *
     * @param httpRequest the current HTTP servlet request
     * @return the parsed token as {@link Identity} instance
     * @throws UnauthorizedException thrown in case of missing, invalid, or expired token
     */
    public Identity verifyOrThrow( HttpServletRequest httpRequest )
    {
        String token = getToken( httpRequest );
        if ( Strings.isNullOrEmpty( token ) )
        {
            throw new UnauthorizedException( "No " + Identity.GTOKEN + " cookie has found in the given request!" );
        }

        return internalVerifyAndGet( token, true );
    }

    /**
     * Parse identity token taken from given request. It's looking for {@link Identity#GTOKEN} cookie to parse
     * and verify in order to create instance of the {@link Identity}.
     * If fails for whatever reason returns <tt>null</tt>.
     *
     * @param httpRequest the current HTTP servlet request
     * @return the parsed token as {@link Identity} instance or <tt>null</tt>
     */
    public Identity verifyAndGet( HttpServletRequest httpRequest )
    {
        Identity identity;
        try
        {
            String token = getToken( httpRequest );
            identity = internalVerifyAndGet( token, false );
        }
        catch ( Exception e )
        {
            identity = null;
        }
        return identity;
    }

    private Identity internalVerifyAndGet( String token, boolean throwIfExpired )
    {
        if ( !Strings.isNullOrEmpty( token ) )
        {
            Identity json = tokenVerifier.verifyAndGet( token );

            if ( json.getExpiration().after( new Date() ) )
            {
                return json;
            }
            else
            {
                if ( throwIfExpired )
                {
                    throw new UnauthorizedException( "The given token has expired!" );
                }
            }
        }

        return null;
    }

    private String getToken( HttpServletRequest httpRequest )
    {
        Cookie[] cookies = httpRequest.getCookies();

        if ( cookies == null )
        {
            return null;
        }

        String token = null;

        for ( Cookie cookie : cookies )
        {
            if ( Identity.GTOKEN.equals( cookie.getName() ) )
            {
                token = cookie.getValue();
                break;
            }
        }

        return token;
    }

    /**
     * Verifies the given token and for positive verification returns an identity instance.
     * Otherwise returns <tt>null</tt>.
     * In case of {@link UnauthorizedException} it will be catched and converted to <tt>null</tt> return value.
     *
     * @param token the token to be verified
     * @return the verified and parsed identity instance or <tt>null</tt> if fails
     */
    public Identity verifyAndGet( @Nullable String token )
    {
        if ( !Strings.isNullOrEmpty( token ) )
        {
            Identity json;
            try
            {
                json = tokenVerifier.verifyAndGet( token );
            }
            catch ( UnauthorizedException e )
            {
                return null;
            }

            if ( json.getExpiration().after( new Date() ) )
            {
                return json;
            }
        }
{'fraction_non_alphanumeric': 0.08585247883917775, 'fraction_numerical': 0.00013435442697836894, 'mean_word_length': 2.0558292282430215, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 33, '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': '5532701', 'n_tokens_mistral': 1923, 'n_tokens_neox': 1881, 'n_words': 586}