# -*- coding: utf-8 -*-

from django.contrib.auth.models import User

from kfet.backends import KFetBackend


class KFetAuthenticationMiddleware(object):
    """Authenticate another user for this request if KFetBackend succeeds.

    By the way, if a user is authenticated, we refresh its from db to add
    values from CofProfile and Account of this user.

    """
    def process_request(self, request):
        if request.user.is_authenticated():
            # avoid multiple db accesses in views and templates
            user_pk = request.user.pk
            request.user = (
                User.objects
                .select_related('profile__account_kfet')
                .get(pk=user_pk)
            )

        kfet_backend = KFetBackend()
        temp_request_user = kfet_backend.authenticate(request)
        if temp_request_user:
            request.real_user = request.user
            request.user = temp_request_user
