<commit_before>"""
sudo.utils
~~~~~~~~~~

:copyright: (c) 2014 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
from collections import defaultdict
from django.core.signing import BadSignature
from django.utils.crypto import get_random_string

from sudo.settings import COOKIE_NAME, COOKIE_AGE, COOKIE_SALT


def cookie_name(region):
    if region is None:
        return COOKIE_NAME
    else:
        return '%s-%s' % (COOKIE_NAME, region)

def setup_request(request):

    if not hasattr(request, '_sudo'):
        request._sudo = defaultdict(lambda: None)

    if not hasattr(request, '_sudo_token'):
        request._sudo_token = {}

def grant_sudo_privileges(request, max_age=COOKIE_AGE, region=None):
    """
    Assigns a random token to the user's session
    that allows them to have elevated permissions
    """
    user = getattr(request, 'user', None)

    # If there's not a user on the request, just noop
    if user is None:
        return

    if not user.is_authenticated():
        raise ValueError('User needs to be logged in to be elevated to sudo')

    # Token doesn't need to be unique,
    # just needs to be unpredictable and match the cookie and the session
    token = get_random_string()

    setup_request(request)
    request.session[cookie_name(region)] = token
    request._sudo[region] = True
    request._sudo_token[region] = token
    request._sudo_max_age = max_age
    return token


def revoke_sudo_privileges(request, region=None):
    """
    Revoke sudo privileges from a request explicitly
    """
    setup_request(request)

    request._sudo[region] = False
    if cookie_name(region) in request.session:
        del request.session[cookie_name(region)]


def has_sudo_privileges(request, region=None):
    """
    Check if a request is allowed to perform sudo actions
    """
    setup_request(request)

    if request._sudo[region] is None:
        try:
            request._sudo[region] = (
                request.user.is_authenticated() and
                request.get_signed_cookie(cookie_name(region), salt=COOKIE_SALT, max_age=COOKIE_AGE) ==
                request.session[cookie_name(region)]
            )
        except (KeyError, BadSignature):
            request._sudo[region] = False
    return request._sudo[region]<commit_msg>Fixed cookie key does not allow slashes in key.<commit_after>"""
sudo.utils
~~~~~~~~~~

:copyright: (c) 2014 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
from collections import defaultdict
from django.core.signing import BadSignature
from django.utils.crypto import get_random_string

from sudo.settings import COOKIE_NAME, COOKIE_AGE, COOKIE_SALT


def cookie_name(region):
    if region is None:
        return COOKIE_NAME
    else:
        return str('%s-%s' % (COOKIE_NAME, region.replace('/', '-')))

def setup_request(request):

    if not hasattr(request, '_sudo'):
        request._sudo = defaultdict(lambda: None)

    if not hasattr(request, '_sudo_token'):
        request._sudo_token = {}

def grant_sudo_privileges(request, max_age=COOKIE_AGE, region=None):
    """
    Assigns a random token to the user's session
    that allows them to have elevated permissions
    """
    user = getattr(request, 'user', None)

    # If there's not a user on the request, just noop
    if user is None:
        return

    if not user.is_authenticated():
        raise ValueError('User needs to be logged in to be elevated to sudo')

    # Token doesn't need to be unique,
    # just needs to be unpredictable and match the cookie and the session
    token = get_random_string()

    setup_request(request)
    request.session[cookie_name(region)] = token
    request._sudo[region] = True
    request._sudo_token[region] = token
    request._sudo_max_age = max_age
    return token


def revoke_sudo_privileges(request, region=None):
    """
    Revoke sudo privileges from a request explicitly
    """
    setup_request(request)

    request._sudo[region] = False
    if cookie_name(region) in request.session:
        del request.session[cookie_name(region)]


def has_sudo_privileges(request, region=None):
    """
    Check if a request is allowed to perform sudo actions
    """
    setup_request(request)

    if request._sudo[region] is None:
        try:
            token = request.get_signed_cookie(
                cookie_name(region),
                salt=COOKIE_SALT,
                max_age=COOKIE_AGE
            )
            request._sudo[region] = (
                request.user.is_authenticated() and
                token == request.session[cookie_name(region)]
            )
            request._sudo_token[region] = token
            request._sudo_max_age = COOKIE_AGE
        except (KeyError, BadSignature):
            request._sudo[region] = False
    return request._sudo[region]
{'fraction_non_alphanumeric': 0.09332227291580257, 'fraction_numerical': 0.0016590626296142678, 'mean_word_length': 2.9695473251028806, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, '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': '7435323', 'n_tokens_mistral': 1481, 'n_tokens_neox': 1376, 'n_words': 404}