4

我有基于源和目标规则的转换装饰器在django-fsm(有限状态机)中运行良好。现在我正在尝试添加权限处理。这看起来很简单,但似乎无论我做什么,都会执行转换,而不管用户的权限或缺乏权限。lambda根据文档,我尝试过使用 Django 权限字符串,并且尝试过使用。我已经尝试了所有这些:

@transition(field=state, source='prog', target='appr', permission='claims.change_claim')

@transition(field=state, source='prog', target='appr', permission=lambda instance, user: not user.has_perm('claims.change_claim'),)

并且,作为一个双重检查,因为permission应该响应任何返回 True/False 的可调用,简单地说:

@transition(field=state, source='prog', target='appr', permission=False)
def approve(self):

在访问转换时,应该TransitionNotAllowed为所有用户提出一个。但是不——即使是没有权限的基本用户仍然可以执行转换(claim.approve())。

为了证明我有正确的权限字符串:

print(has_transition_perm(claim.approve, request.user))

打印错误。我正在进行如下验证(适用于源/目标):

class ClaimEditForm(forms.ModelForm):
    '''
    Some users can transition claims through allowable states
    '''

    def clean_state(self):
        state = self.cleaned_data['state']
        if state == 'appr':
            try:
                self.instance.approve()
            except TransitionNotAllowed:
                raise forms.ValidationError("Claim could not be approved")
        return state

    class Meta:
        model = Claim
        fields = (
            'state',
        )

视图处理程序是标准:

if request.method == "POST":
    claim_edit_form = ClaimEditForm(request.POST, instance=claim)
    if claim_edit_form.is_valid():  # Validate transition rules

我错过了什么?谢谢。

4

1 回答 1

1

事实证明,该permission属性的验证方式与源/目标验证器不同。您必须评估在代码中其他地方的装饰器中建立的权限,而不是装饰器引发错误。因此,要从表单执行权限验证,您需要传入用户对象,在表单的 中接收用户init,然后与 的结果进行比较has_transition_perm。所以这有效:

# model
@transition(field=state, source='prog', target='appr', permission='claims.change_claim')
def approve(self):
....

# view
if request.method == "POST":
    claim_edit_form = ClaimEditForm(request.user, request.POST, instance=claim)
        ....

# form
from django_fsm import has_transition_perm

class ClaimEditForm(forms.ModelForm):
    '''
    Some users can transition claims through allowable states
    (see permission property on claim.approve() decorator)
    '''

    def __init__(self, user, *args, **kwargs):
        # We need to pass the user into the form to validate permissions
        self.user = user
        super(ClaimEditForm, self).__init__(*args, **kwargs)

    def clean_state(self):
        state = self.cleaned_data['state']
        if state == 'appr':
            if not has_transition_perm(self.instance.approve, self.user):
                raise forms.ValidationError("You do not have permission for this transition")
于 2017-06-17T15:53:36.967 回答