I have an app that uses django.contrib.auth but makes no use of Django's built-in permissions system. Instead, views have the @login_required decorator and then check which group the user belongs to, and follow different branches of code execution within the view depending on the group.
A user can belong to only one group.
Checking for the user's group everytime seems to be too much, so I am trying to write a Django middleware that will let me know the user's group in a session.
Looking at the code below, will my middleware work like I want it to?
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
I then intend to check request.session['thegroup'] where needed.
Need your suggestions and opinions. Is the session safe if handled this way? Will this work at all? I am new at Django, Python, and programming in general.
Thanks.