user5278807
user5278807

Reputation:

Django - Settings and Accessing Session Variables in Different Generic Views

We are trying to implement a login through a SSO login page on another site (let's just say as an example: facebook.com).

After a user signs into the SSO login page, they are redirected back to our site, and that domain sets the user_id which was authenticated in the REMOTE_USER request header so that we know they logged in and were authenticated externally. If a user navigates to another page, that request header will no longer be available, so we are trying to store that user_id in a session.

Our existing code base uses a lot of Django generic class views, so we've written a decorator for the views that require a login (profile page, etc), which stores the user_id into a session.

Here's the strange part: the user logs in, we set the user_id in the session in the decorator. The value shows up on the page we set the session on, however on all the other pages, the session value is empty (maybe it was cleared?).

I think this could be an issue with trying to set and access session variables in class based template views.

I've tried for days, but I can't get it to work!

urls.py

from lib.utils import sign_in    

urlpatterns = [
    url(r'^login', sign_in(TemplateView.as_view(template_name='login.html'))),
    url(r'^settings', sign_in(TemplateView.as_view(template_name='settings.html')))
]

utils.py

def sign_in(fn):
    def decorator(request, **kwargs):
        if 'current_user' not in request.session.keys():
            if 'REMOTE_USER' in request.META:
                request.session['current_user'] = request.META['REMOTE_USER']

        else:
            if request.session['current_user'] == '' and request.META['REMOTE_USER'] != '':
                request.session['current_user'] = request.META['REMOTE_USER']

       return fn(request, **kwargs)
   return decorator

Upvotes: 1

Views: 631

Answers (1)

jorlugaqui
jorlugaqui

Reputation: 330

I think you need to login your user internally, after you received your confirmation from the remote service you should do:

login(request, user)

Also you need to specify the appropriate backend, i.e.

 user.backend = ('django.contrib.auth.backends.ModelBackend')

And be sure you have next middlewares in your settings:

'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',

You can use django-braces for decorators in view, is pretty good: https://github.com/brack3t/django-braces

Hope it can help.

Edit: Doing that you should be able to use user.is_authenticated in your views.

Upvotes: 1

Related Questions