<commit_before>from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.contrib.auth import authenticate, logout
from django.contrib.auth import BACKEND_SESSION_KEY

import facebook

from django_facebook.auth import login
from django_facebook.utils import get_access_token, is_fb_logged_in

auth = facebook.Auth(settings.FACEBOOK_APP_ID,
    settings.FACEBOOK_APP_SECRET, settings.FACEBOOK_REDIRECT_URI)

class FacebookAccessor(object):
    """ Simple accessor object for the Facebook user. Non-existing properties 
    will return None instead of raising a AttributeError."""

    def __init__(self, request):
        if is_fb_logged_in(request):
            self.user_id = request.user.username
        # lazy acces token, if if no user is logged is
        self.access_token = get_access_token(request)
        self.auth = auth
        self.graph = facebook.GraphAPI(self.access_token)
        
    def __getattr__(self, name):
        return None


class FacebookLoginMiddleware(object):
    """
    Transparently integrate Django accounts with Facebook. You need to add
    ``auth.FacebookModelBackend`` to ``AUTHENTICATION_BACKENDS`` for this to
    work.

    If the user presents with a valid facebook cookie, or there is a
    signed_request in request.POST (see ``auth.get_facebook_user``), then we
    want them to be automatically logged in as that user. We rely on the
    authentication backend to create the user if it does not exist.

    If you do not want to persist the facebook login, also enable
    FacebookLogOutMiddleware so that if they log out via a fb:login-button
    they are also logged out of Django.

    We also allow people to log in with other backends, so we only log someone
    in if their not already logged in.
    """
    def __init__(self, force_validate=False):
        self.force_validate = force_validate

    def process_request(self, request):
        # AuthenticationMiddleware is required so that request.user exists.
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The FacebookCookieLoginMiddleware requires the"
                " authentication middleware to be installed. Edit your"
                " MIDDLEWARE_CLASSES setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the FacebookCookieLoginMiddleware class.")
        if request.user.is_anonymous():
            user = authenticate(request=request,
                                force_validate=self.force_validate)
            if user:
                login(request, user)


class FacebookLogOutMiddleware(object):
    """
    When a user logs out of facebook (on our page!), we won't get notified,
    but the fbsr_ cookie wil be cleared. So this middleware checks if that
    cookie is still present, and if not, logs the user out.

    This works only if the user is logged in with the
    ``auth.FacebookModelBackend``.
    """

    def process_request(self, request):
        # AuthenticationMiddleware is required so that request.user exists.
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The FacebookLogOutMiddleware requires the"
                " authentication middleware to be installed. Edit your"
                " MIDDLEWARE_CLASSES setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the FacebookLogOutMiddleware class.")
        if request.user.is_authenticated() and request.session.get(
                BACKEND_SESSION_KEY) == \
                    'django_facebook.auth.FacebookModelBackend':
            try:
                cookie_data = auth.get_user_from_cookie(request.COOKIES)
            except facebook.AuthError:
                # TODO Log this
                return

            if not cookie_data:
               logout(request)
               return

            if not cookie_data.get('user_id') == request.user.username:
                logout(request)


class FacebookHelperMiddleware(object):
    """
    This middleware sets the ``facebook`` attribute on the request, which
    contains the user id and a graph accessor.
    """

    def process_request(self, request):
        request.facebook = FacebookAccessor(request)


class FacebookMiddleware(object):
    """
    This middleware implements the basic behaviour:

    - Log someone in if we can authenticate them (see ``auth``)
    - Log someone out if we can't authenticate them anymore
    - Add a ``facebook`` attribute to the request with a graph accessor.
    """
    def process_request(self, request):
        FacebookHelperMiddleware().process_request(request)
        FacebookLoginMiddleware().process_request(request)<commit_msg>Add middleware to set cached user data on the request.facebook attribute on every request<commit_after>from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.contrib.auth import authenticate, logout
from django.contrib.auth import BACKEND_SESSION_KEY
from django.core.cache import cache

import facebook

from django_facebook.auth import login
from django_facebook.utils import (get_access_token, is_fb_logged_in, 
    FB_DATA_CACHE_KEY)

auth = facebook.Auth(settings.FACEBOOK_APP_ID,
    settings.FACEBOOK_APP_SECRET, settings.FACEBOOK_REDIRECT_URI)

class FacebookAccessor(object):
    """ Simple accessor object for the Facebook user. Non-existing properties 
    will return None instead of raising a AttributeError."""

    def __init__(self, request):
        if is_fb_logged_in(request):
            self.user_id = request.user.username
        # lazy acces token, if if no user is logged is
        self.access_token = get_access_token(request)
        self.auth = auth
        self.graph = facebook.GraphAPI(self.access_token)
        
    def __getattr__(self, name):
        return None


class FacebookLoginMiddleware(object):
    """
    Transparently integrate Django accounts with Facebook. You need to add
    ``auth.FacebookModelBackend`` to ``AUTHENTICATION_BACKENDS`` for this to
    work.

    If the user presents with a valid facebook cookie, or there is a
    signed_request in request.POST (see ``auth.get_facebook_user``), then we
    want them to be automatically logged in as that user. We rely on the
    authentication backend to create the user if it does not exist.

    If you do not want to persist the facebook login, also enable
    FacebookLogOutMiddleware so that if they log out via a fb:login-button
    they are also logged out of Django.

    We also allow people to log in with other backends, so we only log someone
    in if their not already logged in.
    """
    def __init__(self, force_validate=False):
        self.force_validate = force_validate

    def process_request(self, request):
        # AuthenticationMiddleware is required so that request.user exists.
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The FacebookCookieLoginMiddleware requires the"
                " authentication middleware to be installed. Edit your"
                " MIDDLEWARE_CLASSES setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the FacebookCookieLoginMiddleware class.")
        if request.user.is_anonymous():
            user = authenticate(request=request,
                                force_validate=self.force_validate)
            if user:
                login(request, user)


class FacebookLogOutMiddleware(object):
    """
    When a user logs out of facebook (on our page!), we won't get notified,
    but the fbsr_ cookie wil be cleared. So this middleware checks if that
    cookie is still present, and if not, logs the user out.

    This works only if the user is logged in with the
    ``auth.FacebookModelBackend``.
    """

    def process_request(self, request):
        # AuthenticationMiddleware is required so that request.user exists.
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The FacebookLogOutMiddleware requires the"
                " authentication middleware to be installed. Edit your"
                " MIDDLEWARE_CLASSES setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the FacebookLogOutMiddleware class.")
        if request.user.is_authenticated() and request.session.get(
                BACKEND_SESSION_KEY) == \
                    'django_facebook.auth.FacebookModelBackend':
            try:
                cookie_data = auth.get_user_from_cookie(request.COOKIES)
            except facebook.AuthError:
                # TODO Log this
                return

            if not cookie_data:
               logout(request)
               return

            if not cookie_data.get('user_id') == request.user.username:
                logout(request)


class FacebookHelperMiddleware(object):
    """
    This middleware sets the ``facebook`` attribute on the request, which
    contains the user id and a graph accessor.
    """

    def process_request(self, request):
        request.facebook = FacebookAccessor(request)
        
        
class FacebookCacheMiddleware(object):
    """
    This middleware loads tries to load user data from the cache. If found, it
    populates request.facebook with it.
    
    This middleware MUST come after the FacebookHelperMiddleware!
    """
    
    def process_request(self, request):
        if request.facebook.user_id:
            fb_data = cache.get(FB_DATA_CACHE_KEY % request.facebook.user_id)
            if fb_data:
                for k, v in fb_data.iteritems():
                    setattr(request.facebook, k, v)


class FacebookMiddleware(object):
    """
    This middleware implements the basic behaviour:

    - Log someone in if we can authenticate them (see ``auth``)
    - Log someone out if we can't authenticate them anymore
    - Add a ``facebook`` attribute to the request with a graph accessor.
    """
    def process_request(self, request):
        FacebookHelperMiddleware().process_request(request)
        FacebookLoginMiddleware().process_request(request)
{'fraction_non_alphanumeric': 0.06588622291021672, 'fraction_numerical': 0.0, 'mean_word_length': 2.6578202406227884, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 38, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3718506', 'n_tokens_mistral': 2678, 'n_tokens_neox': 2578, 'n_words': 912}