限制用户对Django中不同应用程序的访问 [英] Restricting User access to different apps in Django

查看:33
本文介绍了限制用户对Django中不同应用程序的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有两个模型.两者都引用User类(我使用User模型来访问诸如authenticate和login_required之类的方法)

I have two models in my project. Both of which reference the User class (I used the User model to gain access to methods such as authenticate and login_required)

class Customer(models.Model):
    Customer = models.OneToOneField(User)
    CustomerID = models.CharField(max_length = 15)
    phone_regex = RegexValidator(regex = r'\d{10}', message = 'Enter your 10 digit Mobile number')
    Phone_no = models.CharField(max_length = 10,validators = [phone_regex],blank = True)
    Customer_wallet = models.IntegerField(default = 100)


class Merchants(models.Model):
    merchant = models.OneToOneField(User)
    MerchantID = models.CharField(max_length = 15)
    Storename = models.CharField(max_length = 25)

当前,任何用户(无论他是商人还是客户)都可以访问整个网站.我该怎么使用以将客户限制为/Customer URL,将商人限制为/Merchant URL?

Currently any user(regardless of him being a merchant or a customer) has access to the entire site. What do I use to restrict a customer to /Customer url and a merchant to a /Merchant url?

def check_if_merchant(user):
    try:
        user.__getattribute__('merchants')
    except AttributeError:
        return False

我尝试了user_passes_test装饰器来检查用户是否具有商家或客户属性.但它似乎会自动重定向到尚未在urls.py中设置的/accounts/Merchants等.

I tried the user_passes_test decorator to check if the user has a merchant or a customer attribute. But it seems to be automatically redirecting to /accounts/Merchants etc which hasnt been set up in urls.py.

推荐答案

user_passes_test 只是一个简单的修饰符,是的,它确实重定向至记录的URL.

user_passes_test is just a simple decorator, and yes it does redirect to the login url as documented.

现在,由于 user_passes_test 调用了您自己的测试函数,因此,如果您要返回 403 Forbidden ,则只需提高 PermissionDenied 即可返回 False :

Now since user_passes_test calls your own test function, if you want to return a 403 Forbidden instead you just have to raise PermissionDenied instead of returning False:

from django.core.exceptions import PermissionDenied, ObjectDoesNotExist

def check_if_merchant(user):
    try:
        user.merchants
    except (AttributeError, ObjectDoesNotExist):
        raise PermissionDenied
    else:
        return True

或者,您可以首先检查您是否有登录用户,如果没有,则返回False,以将未登录的用户重定向到登录页面:

Alternatively you can first check if you have a logged in user and return False if not, to redirect non logged in users to the login page:

from django.core.exceptions import PermissionDenied, ObjectDoesNotExist

def check_if_merchant(user):
    if user.is_anonymous():
        return False
    try:
        user.merchants
    except (AttributeError, ObjectDoesNotExist):
        raise PermissionDenied
    else:
        return True

这篇关于限制用户对Django中不同应用程序的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆