Django Rest Framework 如何对is_active为False的访客用户完成身份验证?
可行实现方案
你遇到的限制本质是默认的Token认证逻辑会强制校验用户is_active字段为True,只要自定义认证逻辑跳过对应校验即可实现需求,以下是可落地的实现步骤:
1. 自定义Token认证类,允许is_active=False的用户通过校验
以Django REST Framework(DRF)的默认TokenAuthentication为例,你可以继承原有类重写校验逻辑,移除或修改is_active的校验规则:
from rest_framework.authentication import TokenAuthentication from rest_framework.exceptions import AuthenticationFailed class GuestCompatibleTokenAuthentication(TokenAuthentication): def authenticate_credentials(self, key): token_model = self.get_model() try: token = token_model.objects.select_related('user').get(key=key) except token_model.DoesNotExist: raise AuthenticationFailed("无效的访问凭证") # 仅当用户不属于访客分组且is_active为False时拦截 if not token.user.is_active and not token.user.groups.filter(name="访客").exists(): raise AuthenticationFailed("用户已被禁用") return (token.user, token)
你可以把这个自定义认证类配置到全局认证列表,或者仅给任务相关的视图单独指定,不影响原有注册用户的认证逻辑。
2. 新增权限类实现业务限制
个人资料页面访问限制
自定义权限类仅允许is_active=True的正式用户访问个人资料相关接口:
from rest_framework.permissions import BasePermission class OnlyFormalUserAccess(BasePermission): def has_permission(self, request, view): return request.user.is_authenticated and request.user.is_active
把该权限类绑定到个人资料对应的视图上即可。
访客任务创建数量限制
自定义权限类限制访客最多创建10个任务,正式用户不受限:
from rest_framework.permissions import BasePermission from yourapp.models import Task class GuestTaskCreationLimit(BasePermission): def has_permission(self, request, view): # 正式用户无数量限制 if request.user.is_active: return True # 访客创建任务前校验已有数量 if view.action == "create": created_task_count = Task.objects.filter(creator=request.user).count() return created_task_count < 10 # 非创建操作(删改查)不限制 return True
把该权限类绑定到任务相关的视图上即可。
备选轻量方案
如果你的访客用户量较大,不想维护大量is_active=False的无效用户实体,也可以用匿名会话实现访客功能:访客的任务数据临时存在前端localStorage或后端session中,不需要生成用户和Token,当访客注册为正式用户时再把临时数据迁移到正式用户名下,减少无效数据占用。
内容的提问来源于stack exchange,提问作者Luka Reeson
相关产品推荐
相关产品推荐

