使用UserProfile限制视图中的访问

时间:2012-05-21 00:46:46

标签: django django-views

我有一个应用程序,可以在html发布页面上显示客户端资产。授权使用该系统的每个客户都会分配一个配置文件:

class UserProfile(models.Model):  
    user = models.ForeignKey(User, unique=True)
    fullname = models.CharField(max_length=64, unique=False)
    company = models.CharField(max_length=50, choices=CLIENT_CHOICES)
    position = models.CharField(max_length=64, unique=False, blank=True, null=True)
    ...

    User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

    def __unicode__(self):
        return u'%s' % self.fullname

    class Meta:
        ordering = ['fullname']

    class Admin: 
        pass  

并且有一个帖子页面的模型:

class PostPage(models.Model):
    client = models.CharField(max_length=50, choices=CLIENT_CHOICES)
    job_number = models.CharField(max_length=30, unique=True, blank=False, null=False)
    job_name = models.CharField(max_length=64, unique=False, blank=False, null=False)
    page_type = models.CharField(max_length=50, default='POST')
    create_date = models.DateField(("Date"), default=datetime.date.today)
    contact = models.ForeignKey(UserProfile)
    contact2 = models.ForeignKey(UserProfile, related_name='+', blank=True, null=True)
    contact3 = models.ForeignKey(UserProfile, related_name='+', blank=True, null=True)
    contact4 = models.ForeignKey(UserProfile, related_name='+', blank=True, null=True)

    def __unicode__ (self):
            return u'%s %s %s' % (self.client, self.job_number, self.job_name)

    class Admin: 
            pass

最后,一个非常简单的视图功能来显示页面:

def display_postings(request, job_number):
        records = PostPage.objects.filter(job_number=job_number)
        tpl = 'post_page.html'
        return render_to_response(tpl, { 'records': records })

问题是,如果您从“ACME”公司工作并访问系统,视图中没有逻辑可以阻止您查看“BETAMAX”公司的记录以及您自己的记录。如何修改我的视图,如果说user.profile.company =“ACME”,但请求返回PostPage.client =“BETAMAX”的记录,则拒绝访问记录?另外,我可以拥有一个公司组,比如说user.profile.company =“MY_COMPANY”可以访问所有记录吗?

1 个答案:

答案 0 :(得分:0)

写一个decorator来检查视图的request.user公司。代码看起来像这样:

def belongs_to_company(func):

    def decorator(request, *args, **kwargs):
        has_permissions = False
        # get current company
        ...

        # get user's list of company
        ...

        # if company not in user's list of company

        if not has_permissions:
            url = reverse('no_perms')
            return redirect(url)

        return func(request, *args, **kwargs)
    return decorator

更好的长期解决方案是查看Role Based Access Control

django-guardian