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

发布于 2024-08-14 04:51:12 字数 1038 浏览 8 评论 0原文

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

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

呆橘 2024-08-21 04:51:12

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

In general it looks good. You can make it 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
星星的軌跡 2024-08-21 04:51:12

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

It looks approximately correct (not having tested it). One thing to note is that your middleware must occur after django.contrib.sessions.middleware.SessionMiddleware in the MIDDLEWARE_CLASSES list, otherwise the session won't have been setup for you at the time you try to reference it.

掌心的温暖 2024-08-21 04:51:12

好吧,正如我在史蒂夫·洛什的回答<中评论的那样< /a> ,该代码无法按预期工作。

我修改如下,目前看来还可以:-

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)

Well, as I commented in Steve Losh's answer , that code doesn't work as intended.

I modified it as follows and it seems to be OK till now: -

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文