【问题标题】:Can I get cookies value or session value inside the has_permission method of django rest framework?我可以在 django rest 框架的 has_permission 方法中获取 cookie 值或会话值吗?
【发布时间】:2018-07-17 18:01:52
【问题描述】:

我正在做一个项目,我必须检查用户是否属于公司。我已经在登录用户时进行了检查。 如何在 has_permission() 方法中使用公司 ID?

class IsCompanyEmployee(permissions.BasePermission):
    message = 'You are unauthorized to perform any action on this company.'

    def has_permission(self, request, view):
        if request.user.is_authenticated():
            if request.user.is_superuser:
                return True
            else:
                #company_id = request.COOKIES["company_id"]
                             #or
                #company_id = request.session["company_id"]
                return request.user.companyemployee_set.filter(company__id=company_id).exists()
        else:
            return False

【问题讨论】:

  • 你在 DRF 上有 sessionauthentication 吗?
  • 不,我正在使用基于令牌的身份验证
  • 试一试。启用 sessionauthentication,并尝试将公司存储在您的 request.session 中...如果可行,请告诉我,同时我将研究另一种方法。
  • 另一个问题,您在登录时存储的是哪家公司?这是 USER 公司还是任何 COMPANY?
  • 我让用户在登录时选择公司。它的任何公司

标签: django django-rest-framework setcookie django-sessions django-permissions


【解决方案1】:
class IsCompanyEmployee(permissions.BasePermission):

    message = 'You are unauthorized to perform any action on this company.'

    def has_permission(self, request, view):
        if request.user.is_authenticated():
            if request.user.is_superuser:
                return True
            else:
                if 'company_id' in request.session:
                    company_id = request.session.get('company_id')
                    return request.user.companyemployee_set.filter(company__id=company_id).exists()
                else:
                    return False
        else:
            return False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    相关资源
    最近更新 更多