How to limit field access on a model based on user type on Graphene/Django?

前端 未结 2 1050
暖寄归人
暖寄归人 2021-02-02 16:30

Let\'s say I have a model:

class Employee(models.Model):
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=60)
    sal         


        
2条回答
  •  北海茫月
    2021-02-02 17:01

    Great response @MarkChackerian. However personally, I believe that returning a null value for a field on unauthorised access can be ambiguous, so I personally raise an exception from resolve method like that:

    class UnauthorisedAccessError(GraphQLError):
        def __init__(self, message, *args, **kwargs):
            super(UnauthorisedAccessError, self).__init__(message, *args, **kwargs)
    
    def resolve_salary(self, info):
            if info.context.user.has_perm('myapp.can_view_salary'):
                return self.salary
            raise UnauthorisedAccessError(message='No permissions to see the salary!')
    

提交回复
热议问题