Django中间件,用于确定会话中的用户组

时间:2009-12-11 17:30:06

标签: django django-middleware django-sessions

我有一个使用django.contrib.auth的应用程序,但没有使用Django的内置权限系统。相反,视图具有@login_required装饰器,然后检查用户所属的组,并根据组在视图中遵循不同的代码执行分支。

用户只能属于一个群组。

每次检查用户的组似乎太多了,所以我正在尝试编写一个Django中间件,它会让我知道会话中用户的组。

查看下面的代码,我的中间件是否会像我想要的那样工作?

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

然后我打算在需要的地方检查request.session ['thegroup']。

需要您的建议和意见。如果以这种方式处理会话是否安全?这会起作用吗?我是Django,Python和一般编程的新手。

感谢。

3 个答案:

答案 0 :(得分:1)

总的来说它看起来不错。你可以让它更像Pythonic:

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 :(得分:0)

看起来大致正确(没有测试过)。需要注意的一点是,您的中间件必须在MIDDLEWARE_CLASSES列表中 django.contrib.sessions.middleware.SessionMiddleware之后发生,否则在您尝试引用它时将不会为您设置会话。

答案 2 :(得分:0)

好吧,正如我在Steve Losh's answer中所评论的那样,该代码无法正常运行。

我修改如下,直到现在似乎还可以: -

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)