<commit_before>import facebook
from django.conf import settings
from django.shortcuts import reverse
from urllib.parse import urlencode
from django.contrib.auth import login
from django.contrib import messages


app_id = settings.FACEBOOK_KEY
app_secret = settings.FACEBOOK_SECRET


def get_graph():
    """Get App Graph Object.

    returns a graph object containing an app token from the registered facebook app
    """
    graph = facebook.GraphAPI(version='2.7')
    graph.access_token = graph.get_app_access_token(app_id, app_secret)
    return graph


def canv_url(request):
    """Return Canvas URL.

    Generates the canvas_url used by facebook to redirect after auth
    """
    # Check whether the last call was secure and use its protocol
    if request.is_secure():
        return 'https://' + request.get_host() + reverse('custom_auth:facebook_login_response')
    else:
        return 'https://' + request.get_host() + reverse('custom_auth:facebook_login_response')


def auth_url(request):
    """Auth URL.

    Returns the facebook auth url using the current app's domain
    """
    canvas_url = canv_url(request)

    # Permissions set by user. Default is none
    perms = settings.FACEBOOK_PERMISSIONS

    url = "https://www.facebook.com/dialog/oauth?"

    # Payload
    kvps = {'client_id': app_id, 'redirect_uri': canvas_url}

    # Add 'next' as state if provided
    next_param = f"next_url={request.GET.get('next', False)}"
    # Add 'redirected' as state if provided
    redirected_param = f"redirected={request.GET.get('redirected', False)}"
    if request.GET.get('next', False):
        kvps['state'] = next_param
        redirected_param = f',{redirected_param}'
    if request.GET.get('redirected', False):
        kvps['state'] = kvps.get('state', '') + redirected_param

    # Format permissions if needed
    if perms:
        kvps['scope'] = ",".join(perms)

    # Return the url
    return url + urlencode(kvps)


def debug_token(token):
    """Debug Token.

    Returns debug string from token
    """
    return get_graph().debug_access_token(token, app_id, app_secret)


def login_successful(code, request):
    """Login Successful.

    Process successful login by creating or updating an user using Facebook's response
    """
    canvas_url = canv_url(request)
    graph = get_graph()

    # Get token info from user
    try:
        token_info = graph.get_access_token_from_code(code, canvas_url, app_id, app_secret)
    except facebook.GraphAPIError:
        # For some reason, the auth code has already been used, redirect to login again
        return 'auth code used'

    # Extract token from token info
    access_token = token_info['access_token']

    # Token may never expire, so set its expire time to something big if needed
    try:
        token_expires = token_info['expires_in']
    except KeyError:
        token_expires = 9999999

    # Debug the token, as per documentation
    debug = debug_token(access_token)['data']

    # Get the user's scope ID from debug data
    social_id = debug['user_id']

    # Get some user info like name and url
    extra_data = graph.get_object(str(social_id) + '/?fields=name,first_name,link')
    name = extra_data['name']
    first_name = extra_data['first_name']
    link = extra_data['link']

    # Call FacebookUser's method to create or update based on social_id, that returns an facebookuser object
    from .models import FacebookUser
    new = FacebookUser.create_or_update(social_id, access_token, token_expires, first_name, name, link)

    # Try to login the user
    if new.user.is_active:
        login(request, new.user)
        messages.add_message(request, messages.SUCCESS, 'Olá, ' + first_name + '!')
    else:
        messages.add_message(request, messages.ERROR, 'Essa conta foi desativada!')

    return request


def login_canceled(request):

    # If the user has canceled the login process, or something else happened, do nothing and display error message
    messages.add_message(request, messages.ERROR, 'Oops! Algo de errado aconteceu :( Se isso se repetir, fale conosco!')

    return request


def decode_state_data(state):
    if not state:
        return {}
    parts = state.split(',')
    data = {}
    for part in parts:
        p = part.split('=')
        data[p[0]] = p[1]<commit_msg>facebook does not provide user link by default anymore<commit_after>import facebook
from django.conf import settings
from django.shortcuts import reverse
from urllib.parse import urlencode
from django.contrib.auth import login
from django.contrib import messages


app_id = settings.FACEBOOK_KEY
app_secret = settings.FACEBOOK_SECRET


def get_graph():
    """Get App Graph Object.

    returns a graph object containing an app token from the registered facebook app
    """
    graph = facebook.GraphAPI(version='2.7')
    graph.access_token = graph.get_app_access_token(app_id, app_secret)
    return graph


def canv_url(request):
    """Return Canvas URL.

    Generates the canvas_url used by facebook to redirect after auth
    """
    # Check whether the last call was secure and use its protocol
    if request.is_secure():
        return 'https://' + request.get_host() + reverse('custom_auth:facebook_login_response')
    else:
        return 'https://' + request.get_host() + reverse('custom_auth:facebook_login_response')


def auth_url(request):
    """Auth URL.

    Returns the facebook auth url using the current app's domain
    """
    canvas_url = canv_url(request)

    # Permissions set by user. Default is none
    perms = settings.FACEBOOK_PERMISSIONS

    url = "https://www.facebook.com/dialog/oauth?"

    # Payload
    kvps = {'client_id': app_id, 'redirect_uri': canvas_url}

    # Add 'next' as state if provided
    next_param = f"next_url={request.GET.get('next', False)}"
    # Add 'redirected' as state if provided
    redirected_param = f"redirected={request.GET.get('redirected', False)}"
    if request.GET.get('next', False):
        kvps['state'] = next_param
        redirected_param = f',{redirected_param}'
    if request.GET.get('redirected', False):
        kvps['state'] = kvps.get('state', '') + redirected_param

    # Format permissions if needed
    if perms:
        kvps['scope'] = ",".join(perms)

    # Return the url
    return url + urlencode(kvps)


def debug_token(token):
    """Debug Token.

    Returns debug string from token
    """
    return get_graph().debug_access_token(token, app_id, app_secret)


def login_successful(code, request):
    """Login Successful.

    Process successful login by creating or updating an user using Facebook's response
    """
    canvas_url = canv_url(request)
    graph = get_graph()

    # Get token info from user
    try:
        token_info = graph.get_access_token_from_code(code, canvas_url, app_id, app_secret)
    except facebook.GraphAPIError:
        # For some reason, the auth code has already been used, redirect to login again
        return 'auth code used'

    # Extract token from token info
    access_token = token_info['access_token']

    # Token may never expire, so set its expire time to something big if needed
    try:
        token_expires = token_info['expires_in']
    except KeyError:
        token_expires = 9999999

    # Debug the token, as per documentation
    debug = debug_token(access_token)['data']

    # Get the user's scope ID from debug data
    social_id = debug['user_id']

    # Get some user info like name and url
    extra_data = graph.get_object(str(social_id) + '/?fields=name,first_name,link')
    name = extra_data['name']
    first_name = extra_data['first_name']
    link = extra_data.get('link', '')

    # Call FacebookUser's method to create or update based on social_id, that returns an facebookuser object
    from .models import FacebookUser
    new = FacebookUser.create_or_update(social_id, access_token, token_expires, first_name, name, link)

    # Try to login the user
    if new.user.is_active:
        login(request, new.user)
        messages.add_message(request, messages.SUCCESS, 'Olá, ' + first_name + '!')
    else:
        messages.add_message(request, messages.ERROR, 'Essa conta foi desativada!')

    return request


def login_canceled(request):

    # If the user has canceled the login process, or something else happened, do nothing and display error message
    messages.add_message(request, messages.ERROR, 'Oops! Algo de errado aconteceu :( Se isso se repetir, fale conosco!')

    return request


def decode_state_data(state):
    if not state:
        return {}
    parts = state.split(',')
    data = {}
    for part in parts:
        p = part.split('=')
        data[p[0]] = p[1]
{'fraction_non_alphanumeric': 0.09740932642487046, 'fraction_numerical': 0.0025331030512377663, 'mean_word_length': 3.406900050735667, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 6, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3928017', 'n_tokens_mistral': 2651, 'n_tokens_neox': 2544, 'n_words': 797}