<commit_before>import logging
from random import randint
import sys

from django.contrib import auth
from django.contrib.auth import authenticate, login
from django.db import transaction
from django.db.utils import IntegrityError
from django.utils import simplejson as json
from django.conf import settings

from utils import get_profile_class

from django_facebook import settings as facebook_settings
from django_facebook import exceptions as facebook_exceptions
from django_facebook import signals
from django_facebook.api import get_facebook_graph, FacebookUserConverter
from django_facebook.utils import get_registration_backend, get_form_class

logger = logging.getLogger(__name__)


class CONNECT_ACTIONS:
    class LOGIN:
        pass

    class CONNECT(LOGIN):
        pass

    class REGISTER:
        pass


def connect_user(request, access_token=None, facebook_graph=None):
    '''
    Given a request either

    - (if authenticated) connect the user
    - login
    - register
    '''
    user = None
    graph = facebook_graph or get_facebook_graph(request, access_token)
    facebook = FacebookUserConverter(graph)

    assert facebook.is_authenticated()
    facebook_data = facebook.facebook_profile_data()
    force_registration = request.REQUEST.get('force_registration') or\
        request.REQUEST.get('force_registration_hard')

    logger.debug('force registration is set to %s', force_registration)
    if request.user.is_authenticated() and not force_registration:
        action = CONNECT_ACTIONS.CONNECT
        user = _connect_user(request, facebook)
    else:
        email = facebook_data.get('email', False)
        email_verified = facebook_data.get('verified', False)
        kwargs = {}
        if email and email_verified:
            kwargs = {'facebook_email': email}
        auth_user = authenticate(facebook_id=facebook_data['id'], **kwargs)
        if auth_user and not force_registration:
            action = CONNECT_ACTIONS.LOGIN

            # Has the user registered without Facebook, using the verified FB
            # email address?
            # It is after all quite common to use email addresses for usernames
            if not auth_user.get_profile().facebook_id:
                update = True
            else:
                update = getattr(auth_user, 'fb_update_required', False)
            user = _login_user(request, facebook, auth_user, update=update)
        else:
            action = CONNECT_ACTIONS.REGISTER
            #when force registration is active we should clearout the old profile
            user = _register_user(request, facebook, remove_old_connections=force_registration)

    #store likes and friends if configured
    sid = transaction.savepoint()
    try:
        if facebook_settings.FACEBOOK_STORE_LIKES:
            facebook.get_and_store_likes(user)
        if facebook_settings.FACEBOOK_STORE_FRIENDS:
            facebook.get_and_store_friends(user)
        transaction.savepoint_commit(sid)
    except IntegrityError, e:
        logger.warn(u'Integrity error encountered during registration, '
                'probably a double submission %s' % e,
            exc_info=sys.exc_info(), extra={
            'request': request,
            'data': {
                 'body': unicode(e),
             }
        })
        transaction.savepoint_rollback(sid)

    profile = user.get_profile()
    #store the access token for later usage if the profile model supports it
    if hasattr(profile, 'access_token'):
        #only update the access token if it is long lived and not equal to the current token
        if not graph.expires and graph.access_token != profile.access_token:
            #TODO, maybe we should just always do this.
            profile.access_token = graph.access_token
            profile.save()

    return action, user


def _login_user(request, facebook, authenticated_user, update=False):
    login(request, authenticated_user)

    if update:
        _connect_user(request, facebook)

    return authenticated_user


def _connect_user(request, facebook):
    '''
    Update the fields on the user model and connects it to the facebook account

    '''
    if not request.user.is_authenticated():
        raise ValueError('Connect user can only be used on authenticated users')
    if not facebook.is_authenticated():
        raise ValueError('Facebook needs to be authenticated for connect flows')

    user = _update_user(request.user, facebook)

    return user


def _register_user(request, facebook, profile_callback=None, remove_old_connections=False):
    '''
    Creates a new user and authenticates
    The registration form handles the registration and validation
    Other data on the user profile is updates afterwards
    
    if remove_old_connections = True we will disconnect old profiles from their 
    facebook flow
    '''
    if not facebook.is_authenticated():
        raise ValueError('Facebook needs to be authenticated for connect flows')
    


    #get the backend on new registration systems, or none if we are on an older version
    backend = get_registration_backend()

    #gets the form class specified in FACEBOOK_REGISTRATION_FORM
    form_class = get_form_class(backend, request)

    facebook_data = facebook.facebook_registration_data()

    data = request.POST.copy()
    for k, v in facebook_data.items():
        if not data.get(k):
            data[k] = v
            
    if remove_old_connections:
        _remove_old_connections(facebook_data['facebook_id'])

    if request.REQUEST.get('force_registration_hard'):
        data['email'] = data['email'].replace('@', '+%s@' % randint(0, 100000))

    form = form_class(data=data, files=request.FILES,
        initial={'ip': request.META['REMOTE_ADDR']})
<commit_msg>more random<commit_after>import logging
from random import randint
import sys

from django.contrib import auth
from django.contrib.auth import authenticate, login
from django.db import transaction
from django.db.utils import IntegrityError
from django.utils import simplejson as json
from django.conf import settings

from utils import get_profile_class

from django_facebook import settings as facebook_settings
from django_facebook import exceptions as facebook_exceptions
from django_facebook import signals
from django_facebook.api import get_facebook_graph, FacebookUserConverter
from django_facebook.utils import get_registration_backend, get_form_class

logger = logging.getLogger(__name__)


class CONNECT_ACTIONS:
    class LOGIN:
        pass

    class CONNECT(LOGIN):
        pass

    class REGISTER:
        pass


def connect_user(request, access_token=None, facebook_graph=None):
    '''
    Given a request either

    - (if authenticated) connect the user
    - login
    - register
    '''
    user = None
    graph = facebook_graph or get_facebook_graph(request, access_token)
    facebook = FacebookUserConverter(graph)

    assert facebook.is_authenticated()
    facebook_data = facebook.facebook_profile_data()
    force_registration = request.REQUEST.get('force_registration') or\
        request.REQUEST.get('force_registration_hard')

    logger.debug('force registration is set to %s', force_registration)
    if request.user.is_authenticated() and not force_registration:
        action = CONNECT_ACTIONS.CONNECT
        user = _connect_user(request, facebook)
    else:
        email = facebook_data.get('email', False)
        email_verified = facebook_data.get('verified', False)
        kwargs = {}
        if email and email_verified:
            kwargs = {'facebook_email': email}
        auth_user = authenticate(facebook_id=facebook_data['id'], **kwargs)
        if auth_user and not force_registration:
            action = CONNECT_ACTIONS.LOGIN

            # Has the user registered without Facebook, using the verified FB
            # email address?
            # It is after all quite common to use email addresses for usernames
            if not auth_user.get_profile().facebook_id:
                update = True
            else:
                update = getattr(auth_user, 'fb_update_required', False)
            user = _login_user(request, facebook, auth_user, update=update)
        else:
            action = CONNECT_ACTIONS.REGISTER
            #when force registration is active we should clearout the old profile
            user = _register_user(request, facebook, remove_old_connections=force_registration)

    #store likes and friends if configured
    sid = transaction.savepoint()
    try:
        if facebook_settings.FACEBOOK_STORE_LIKES:
            facebook.get_and_store_likes(user)
        if facebook_settings.FACEBOOK_STORE_FRIENDS:
            facebook.get_and_store_friends(user)
        transaction.savepoint_commit(sid)
    except IntegrityError, e:
        logger.warn(u'Integrity error encountered during registration, '
                'probably a double submission %s' % e,
            exc_info=sys.exc_info(), extra={
            'request': request,
            'data': {
                 'body': unicode(e),
             }
        })
        transaction.savepoint_rollback(sid)

    profile = user.get_profile()
    #store the access token for later usage if the profile model supports it
    if hasattr(profile, 'access_token'):
        #only update the access token if it is long lived and not equal to the current token
        if not graph.expires and graph.access_token != profile.access_token:
            #TODO, maybe we should just always do this.
            profile.access_token = graph.access_token
            profile.save()

    return action, user


def _login_user(request, facebook, authenticated_user, update=False):
    login(request, authenticated_user)

    if update:
        _connect_user(request, facebook)

    return authenticated_user


def _connect_user(request, facebook):
    '''
    Update the fields on the user model and connects it to the facebook account

    '''
    if not request.user.is_authenticated():
        raise ValueError('Connect user can only be used on authenticated users')
    if not facebook.is_authenticated():
        raise ValueError('Facebook needs to be authenticated for connect flows')

    user = _update_user(request.user, facebook)

    return user


def _register_user(request, facebook, profile_callback=None, remove_old_connections=False):
    '''
    Creates a new user and authenticates
    The registration form handles the registration and validation
    Other data on the user profile is updates afterwards
    
    if remove_old_connections = True we will disconnect old profiles from their 
    facebook flow
    '''
    if not facebook.is_authenticated():
        raise ValueError('Facebook needs to be authenticated for connect flows')
    


    #get the backend on new registration systems, or none if we are on an older version
    backend = get_registration_backend()

    #gets the form class specified in FACEBOOK_REGISTRATION_FORM
    form_class = get_form_class(backend, request)

    facebook_data = facebook.facebook_registration_data()

    data = request.POST.copy()
    for k, v in facebook_data.items():
        if not data.get(k):
            data[k] = v
            
    if remove_old_connections:
        _remove_old_connections(facebook_data['facebook_id'])

    if request.REQUEST.get('force_registration_hard'):
        data['email'] = data['email'].replace('@', '+test%s@' % randint(0, 1000000000))

    form = form_class(data=data, files=request.FILES,
        initial={'ip': request.META['REMOTE_ADDR']})

{'fraction_non_alphanumeric': 0.070995670995671, 'fraction_numerical': 0.0015584415584415584, 'mean_word_length': 3.0931963146704464, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2942846', 'n_tokens_mistral': 3195, 'n_tokens_neox': 2981, 'n_words': 943}