【问题标题】:Django middleware to determine user's group in a sessionDjango 中间件确定会话中的用户组
【发布时间】:2010-12-25 18:23:24
【问题描述】:

我有一个使用 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 和一般编程方面的新手。

谢谢。

【问题讨论】:

    标签: django django-middleware django-sessions


    【解决方案1】:

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

    【讨论】:

    • 那么如果这发生在 SessionMiddleware 之后,我是否需要明确地将会话标记为脏?还是会话框架会自动检测并保存这些信息?
    • 因为是直接修改会话,所以不需要显式保存。见:docs.djangoproject.com/en/dev/topics/http/sessions/…
    【解决方案2】:

    总的来说,它看起来不错。不过你可以让它更 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
    

    【讨论】:

    • Peter Rowell 关于中间件顺序的回答非常重要,但我会将您的回答标记为已接受的回答,因为您已经改进了我的(显然是新手)代码。
    • 好吧,如果用户一开始是匿名的(大多数情况下都是如此),那么使用当前代码 request.session['thegroup'] 在登录时不会得到更新。我会尝试调试它,如果可以的话,我会在这里发布。
    【解决方案3】:

    好吧,正如我在 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 2022-06-12
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 1970-01-01
      相关资源
      最近更新 更多