from django.utils.deprecation import MiddlewareMixin
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import get_user_model
User = get_user_model()


class OauthAdminSessionMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if hasattr(request, 'session') and 'username' in request.session:
            try:
                user = User.objects.get(username=request.session['username'])
                request.user = user
                request._cached_user = user
            except Exception as e:
                print(e)
                request.user = AnonymousUser()
        else:
            request.user = AnonymousUser()
