简体   繁体   English

在 django rest 框架中实现角色

[英]Implement roles in django rest framework

I am building an API that should have the following kind of users我正在构建一个应具有以下类型用户的 API

super_user - create/manage admins super_user - 创建/管理管理员

admin - manage events(model) and event participants admin - 管理事件(模型)和事件参与者

participants - participate in events, invited to events by admins participants - 参加活动,受管理员邀请参加活动

Additional i want to have each type of user to have phone number field另外我想让每种类型的用户都有电话号码字段

I tried试过了

class SuperUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone_number = models.CharField(max_length=20)

class Admin(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone_number = models.CharField(max_length=20)


class Participant(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone_number = models.CharField(max_length=20)

But gut is telling me its a wrong way to handle this.但是直觉告诉我这是一种错误的处理方式。 Can someone please help.有人可以帮忙吗。

One possible solution is:一种可能的解决方案是:

    1. Have only one User Model with role field, which defines what user role is.只有一个带有角色字段的用户模型,它定义了用户角色是什么。
    1. Create a User Group and add each group needed permissions.创建一个用户组并添加每个组所需的权限。
    1. Add User to User Group将用户添加到用户组
    1. Limit access using a Django REST Framework (later DRF) Permission Class.使用 Django REST Framework(后来的 DRF)权限类限制访问。

Explanation:解释:

  1. Using only one user model is a more simple and flexible solution.仅使用一个用户模型是一种更简单灵活的解决方案。 You can query all users, or filtered by feature (like user role).您可以查询所有用户,或按功能(如用户角色)过滤。 Standart Django auth system expects one UserModel.标准 Django 身份验证系统需要一个 UserModel。

  2. Read more about Django user groups.阅读有关 Django 用户组的更多信息。 See " Django Permissions Docs #1 " and " Django Groups Docs #2 ".请参阅“ Django 权限文档#1 ”和“ Django 组文档#2 ”。 Also useful is " User groups and permissions ".同样有用的是“ 用户组和权限”。

You need to create a group for each user role, and add needed permissions for each group.您需要为每个用户角色创建一个组,并为每个组添加所需的权限。 (Django has a default model permission, created automatically, look at the docs on the given links) or create the needed permission manually in the model definition. (Django 有一个默认的模型权限,自动创建,查看给定链接上的文档)或在模型定义中手动创建所需的权限。

  1. Manually or using a script, add User to the needed group by defining his role when a user is created or manually by Django Admin interface.手动或使用脚本,通过在创建用户时定义他的角色或通过 Django 管理界面手动将用户添加到所需的组。

  2. Now everything should be ready for limited access by the user's role.现在一切都应该准备就绪,可以通过用户角色进行有限访问。 You can easily limit access to the DRF View using a permission class.您可以使用权限类轻松限制对 DRF 视图的访问。 See more information in the " DRF Permission Docs ".在“ DRF 权限文档”中查看更多信息。

Let's define our own:让我们定义我们自己的:

from rest_framework.permissions import DjangoModelPermissions
# Using DjangoModelPermissions we can limit access by checking user permissions.

# Rights need only for CreateUpdateDelete actions.
class CUDModelPermissions(DjangoModelPermissions):
  perms_map = {
      'GET': [],
      'OPTIONS': [],
      'HEAD': ['%(app_label)s.read_%(model_name)s'],
      'POST': ['%(app_label)s.add_%(model_name)s'],
      'PUT': ['%(app_label)s.change_%(model_name)s'],
      'PATCH': ['%(app_label)s.change_%(model_name)s'],
      'DELETE': ['%(app_label)s.delete_%(model_name)s'],
  }

# Or you can inherit from BasePermission class and define your own rule for access
from rest_framework.permissions import BasePermission

class AdminsPermissions(BasePermission):
    allowed_user_roles = (User.SUPERVISOR, User.ADMINISTRATOR)

    def has_permission(self, request, view):
        is_allowed_user = request.user.role in self.allowed_user_roles
        return is_allowed_user

# ----
# on views.py

from rest_framework import generics
from .mypermissions import CUDModelPermissions, AdminsPermissions

class MyViewWithPermissions(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [CUDModelPermissions, ]
    queryset = SomeModel.objects.all()
    serializer_class = MyModelSerializer

You can add additional permission class to combine access limitation.您可以添加额外的权限类来组合访问限制。

So in Django any user has a flag is_superuser that corresponds to your 'superuser'.所以在 Django 中,任何用户都有一个标志is_superuser对应于你的“超级用户”。 So just use that - eg User.objects.create(is_superuser=True) .所以只需使用它 - 例如User.objects.create(is_superuser=True)

For the rest you can simply use a field for a normal User model to differentiate between subroles of a normal user.对于其余部分,您可以简单地使用普通用户模型的字段来区分普通用户的子角色。

class User(AbstractBaseUser):
    can_participate_event = models.Boolean(default=False)
    can_create_event = models.Boolean(default=False)

Or或者

class User(AbstractBaseUser):
    permissions = models.CharField(default='')  # and populate with e.g. 'create_event,participate_event'

Still you will need to check all those fields in your view probably.您仍然可能需要检查视图中的所有这些字段。 The more you add to your application, the hairier this becomes so I would suggest using a 3rd party library like rest-framework-roles (I'm the author) or guardian.你添加到你的应用程序中越多,它就会变得越多,所以我建议使用像rest-framework-roles (我是作者)或监护人这样的 3rd 方库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django Rest Framework:如何实现嵌套逻辑? - Django Rest Framework: How to implement a nested logic? 限制 Django Rest Framework 中 Company 对象内用户管理的角色 - Restrict roles for users management inside a Company object in Django Rest Framework 在Django 1.11和django _rest框架中的嵌套序列化程序上实现更新方法 - Implement update method on a Nested Serializer in Django 1.11 and django _rest framework 我应该在 django 之上实现 django rest 框架吗? - Should I implement the django rest framework above django? 如何在Django中实现多个角色? - How to implement multiple roles in Django? 使用Django Rest Framework实现视图或方法的干净方法 - Clean way to implement views or methods with Django Rest Framework 如何在不使用 REST 框架的情况下在 Django 和 React 应用程序中实现分页? - How to implement pagination in a Django and React app without using the REST framework? django rest框架中文章最后访问功能的实现方法 - How to implement last visited functionality for articles in django rest framework Django REST 框架: 网站开发完成后可以实现吗? - Django REST Framework: Is it possible to implement after the complete development of a website? Django 或 Django Rest 框架 - Django or Django Rest Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM