Example #1
0
def get_user(request):
    from django.contrib.auth.models import AnonymousUser

    user = authenticate(request=request)
    if user is None:
        user = AnonymousUser()
        user.email, user.first_name = request["From"]
    return user
Example #2
0
    def process_request(self, request):
        django_user = get_user(request)
        google_user = users.get_current_user()

        # Check to see if the user is authenticated with a different backend, if so, just set
        # request.user and bail
        if django_user.is_authenticated():
            backend_str = request.session.get(BACKEND_SESSION_KEY)
            if (not backend_str) or not isinstance(
                    load_backend(backend_str), BaseAppEngineUserAPIBackend):
                request.user = django_user
                return

        if django_user.is_anonymous() and google_user:
            # If there is a google user, but we are anonymous, log in!
            # Note that if DJANGAE_FORCE_USER_PRE_CREATION is True then this may not authenticate
            django_user = authenticate(
                google_user=google_user) or AnonymousUser()
            if django_user.is_authenticated():
                login(request, django_user)

        if django_user.is_authenticated():
            if not google_user:
                # If we are logged in with django, but not longer logged in with Google
                # then log out
                logout(request)
                django_user = AnonymousUser()
            elif django_user.username != google_user.user_id():
                # If the Google user changed, we need to log in with the new one
                logout(request)
                django_user = authenticate(
                    google_user=google_user) or AnonymousUser()
                if django_user.is_authenticated():
                    login(request, django_user)

        # Note that the logic above may have logged us out, hence new `if` statement
        if django_user.is_authenticated():
            # Now make sure we update is_superuser and is_staff appropriately
            is_superuser = users.is_current_user_admin()
            resave = False

            if is_superuser != django_user.is_superuser:
                django_user.is_superuser = django_user.is_staff = is_superuser
                resave = True

            # for users which already exist, we want to verify that their email is still correct
            # users are already authenticated with their user_id, so we can save their real email
            # not the lowercased version
            if django_user.email != google_user.email():
                django_user.email = google_user.email()
                resave = True

            if resave:
                django_user.save()

        request.user = django_user
Example #3
0
    def process_request(self, request):
        django_user = get_user(request)
        google_user = users.get_current_user()

        # Check to see if the user is authenticated with a different backend, if so, just set
        # request.user and bail
        if django_user.is_authenticated():
            backend_str = request.session.get(BACKEND_SESSION_KEY)
            if (not backend_str) or not isinstance(load_backend(backend_str), BaseAppEngineUserAPIBackend):
                request.user = django_user
                return

        if django_user.is_anonymous() and google_user:
            # If there is a google user, but we are anonymous, log in!
            # Note that if DJANGAE_CREATE_UNKNOWN_USER=False then this may not authenticate
            django_user = authenticate(google_user=google_user) or AnonymousUser()
            if django_user.is_authenticated():
                login(request, django_user)

        if django_user.is_authenticated():
            if not google_user:
                # If we are logged in with django, but not longer logged in with Google
                # then log out
                logout(request)
                django_user = AnonymousUser()
            elif django_user.username != google_user.user_id():
                # If the Google user changed, we need to log in with the new one
                logout(request)
                django_user = authenticate(google_user=google_user) or AnonymousUser()
                if django_user.is_authenticated():
                    login(request, django_user)

        # Note that the logic above may have logged us out, hence new `if` statement
        if django_user.is_authenticated():
            # Now make sure we update is_superuser and is_staff appropriately
            is_superuser = users.is_current_user_admin()
            resave = False

            if is_superuser != django_user.is_superuser:
                django_user.is_superuser = django_user.is_staff = is_superuser
                resave = True

            # for users which already exist, we want to verify that their email is still correct
            # users are already authenticated with their user_id, so we can save their real email
            # not the lowercased version
            if django_user.email != google_user.email():
                django_user.email = google_user.email()
                resave = True

            if resave:
                django_user.save()

        request.user = django_user
Example #4
0
def get_user(request):
    """
    Return the user model instance associated with the given request session.
    If no user is retrieved, return an instance of `AnonymousUser`.
    """

    user = AnonymousUser()

    token = request.META.get('HTTP_AUTHORIZATION')
    if not token:
        return (user, 'token不存在', 400, ResCode.Token_Missing)

    start = time.time()
    try:
        result = requests.get(settings.SSO_VERIFY,
                              verify=False,
                              headers={'Authorization': token})
        status_code = result.status_code
        result = result.json()
    except Exception as ex:
        logger.error('SSO登录授权验证失败:' + str(ex))
        return (user, '服务器异常,登录授权验证失败', 500, ResCode.Token_Missing)
    end = time.time()
    logger.debug('sso verify time:{} ms'.format((end - start) * 1000))

    rescode = result.get('rescode')
    if rescode == res_code['success']:
        user_data = result.get('data')
        user = User()
        user.id = user_data.get('id')
        user.username = user_data.get('username')
        user.mobile = user_data.get('mobile')
        user.email = user_data.get('email')
        user.user_type = user_data.get('user_type')
        user.is_subuser = user_data.get('is_subuser')
        user.main_user_id = user_data.get('main_user_id')
        user.permissions = user_data.get('permissions')

    return (user, result.get('msg'), status_code, rescode)
Example #5
0
    def authenticate(self, token=None, request=None):
        """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """
        
        #rebuild redirect_uri for user id or next url
        redirect_uri = request.build_absolute_uri('/facebook/authentication_callback')
        redirect_args = {}
        if request.GET.get('next'):
            redirect_args['next'] = request.GET.get('next')            
        if request.GET.get('user'): 
            redirect_args['user'] = str(request.user.id)
        
        if len(redirect_args) != 0:
            redirect_uri = redirect_uri + '?' + urllib.urlencode(redirect_args)
        
        args = {
            'client_id': settings.FACEBOOK_APP_ID,
            'client_secret': settings.FACEBOOK_APP_SECRET,
            'redirect_uri': redirect_uri,
            'code': token,
        }

        # Get a legit access token
        target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read()
        response = cgi.parse_qs(target)
        access_token = response['access_token'][-1]

        # Read the user's profile information
        fb_profile = urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % access_token)
        fb_profile = json.load(fb_profile)
        
        #if user is just trying to connect facebook not full login
        if request.GET.get('user'):
            user = request.user
            try:
                # Try and find existing user
                fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id'])
                user = fb_user.user
                
                if request.user.id != user.id:                    
                    return None                
                
            except FacebookProfile.DoesNotExist:
                fb_user = FacebookProfile(
                        user=user,
                        facebook_id=fb_profile['id'],
                        access_token=access_token
                )                
                fb_user.save()
            return user                
        
        #full login
        try:
            # Try and find existing user
            fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id'])
            user = fb_user.user

            # Update access_token
            fb_user.access_token = access_token
            fb_user.save()
        except FacebookProfile.DoesNotExist:
            # Not all users have usernames
            username = fb_profile.get('username', fb_profile['email'].split('@')[0])

            if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False):
                user = AnonymousUser()
                user.signup_required = True
                user.username = username
                user.first_name = fb_profile['first_name']
                user.last_name = fb_profile['last_name']
                fb_user = FacebookProfile(
                        facebook_id=fb_profile['id'],
                        access_token=access_token
                )
                user.facebookprofile = fb_user

            else:
                if getattr(settings, 'FACEBOOK_FORCE_VERIFICATION', False) and \
                        User.objects.filter(email__iexact=fb_profile['email']).exists():
                    user = AnonymousUser()
                    user.verification_required = True
                    user.email = fb_profile['email']
                    user.facebookprofile = FacebookProfile(
                            facebook_id=fb_profile['id'],
                            access_token=access_token
                    )
                else:
                    try:
                        user = User.objects.create_user(username, fb_profile['email'])
                    except IntegrityError:
                        # Username already exists, make it unique
                        user = User.objects.create_user(username + fb_profile['id'], fb_profile['email'])
                        user.first_name = fb_profile['first_name']
                        user.last_name = fb_profile['last_name']
                        user.save()

                    # Create the FacebookProfile
                    fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token)
                    fb_user.save()
        return user