2012-05-21 46 views
0

我有一個應用程序,顯示HTML發佈頁面上的客戶端資產。授權使用系統中的每個客戶端分配一個配置文件:使用UserProfile限制在視圖中的訪問

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」公司的記錄以及y我們自己的。我如何修改我的視圖,以便如果說,user.profile.company =「ACME」,但請求返回的記錄PostPage.client =「BETAMAX」,訪問記錄被拒絕?此外,我可以擁有一個公司組,比如user.profile.company =「MY_COMPANY」,可以訪問所有記錄嗎?

回答

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 

一個更好的長期解決方案是檢查出像django-guardian

Role Based Access Control