Django tool to define a user group in a session

I have an application that uses django.contrib.auth but does not use the Django built-in permission system. Instead, the views have the @login_required decoder and then check which group the user belongs to and follow the different branches of code execution in the view depending on the group.

A user can belong to only one group.

Checking a user group at any time seems too big, so I'm trying to write Django middleware that will tell me a user group in a session.

Looking at the code below, will my middleware work the way I want?

class SetGroupMiddleware(object): def process_request(self, request): check_if_already_set = request.session.get('thegroup', 'notset') if check_if_already_set == 'notset': if request.user.id: # User is not AnonymousUser groups = request.user.groups.all() if groups: # actually this will always be True request.session['thegroup'] = str(groups[0].name) # flowchart of the app ensures that the logged in user will only have one group, and that the user will always have a group else: request.session['thegroup'] = 'nogroup' # for completeness 

Then I intend to check request.session ['thegroup'] where necessary.

You need your suggestions and opinions. Is the session safe in this way? Will it even work? I am new to Django, Python, and general programming.

Thanks.

+4
source share
3 answers

All in all, it looks good. You can make this a bit more Pythonic though:

 class SetGroupMiddleware(object): def process_request(self, request): if 'thegroup' not in request.session: if not request.user.is_anonymous(): groups = request.user.groups.all() if groups: request.session['thegroup'] = str(groups[0].name) else: request.session['thegroup'] = None # for completeness 
+1
source

It looks roughly correct (without checking it). It should be noted that your middleware should appear after django.contrib.sessions.middleware.SessionMiddleware in the MIDDLEWARE_CLASSES list, otherwise the session will not be configured for you at the time of its link.

0
source

Well, as I commented in response to Steve Losch , this code does not work properly.

I changed it as follows, and so far it looks fine: -

 class SetGroupMiddleware(object): def process_request(self, request): if not request.user.is_anonymous(): if 'thegroup' not in request.session: groups = request.user.groups.all() if groups: request.session['thegroup'] = str(groups[0].name) 
0
source

All Articles