Search code examples
djangodjango-rest-frameworksetcookiedjango-sessionsdjango-permissions

Can I get cookies value or session value inside the has_permission method of django rest framework?


I am working on a project where i have to check the user whether they belong the company or not.i am already put check while login user. how i can use company id inside the has_permission() method?

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

Solution

  • 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