django - 注销后销毁令牌
问题描述
我想在用户注销时销毁身份验证令牌。用户在我提供的视图中成功注销。但是当用户注销时我需要销毁令牌。
views.py
class UserLoginViewSet(viewsets.ViewSet):
def create(self,request):
try:
data=request.data
email=data.get('email')
password=data.get('password')
date_of_birth=data.get('date_of_birth')
if not all([email,password,date_of_birth]):
raise Exception('all fields are mandetory')
user=authenticate(username=email,password=password)
if user is not None:
token=generate_token()
user_info=MyUser.objects.get(email=email)
data=({
'email':user_info.email,
'password':user_info.password,
#'data_of_birth':user_info.data_of_birth
})
return Response({"message": "You are successfully logged in",
"user_info":data,"token": token, "success": True},status=status.HTTP_200_OK)
else :
raise Exception('not authorised')
except Exception as error:
traceback.print_exc()
return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK)
def delete(self,request):
logout(request)
return Response({'successfull':True})```
#my user is logging out correctly,but i want to doi this by deleting token
解决方案
你可以这样做
class UserLoginViewSet(viewsets.ViewSet):
def create(self,request):
try:
data=request.data
email=data.get('email')
password=data.get('password')
date_of_birth=data.get('date_of_birth')
if not all([email,password,date_of_birth]):
raise Exception('all fields are mandetory')
user=authenticate(username=email,password=password)
if user is not None:
token=generate_token()
user_info=MyUser.objects.get(email=email)
data=({
'email':user_info.email,
'password':user_info.password,
#'data_of_birth':user_info.data_of_birth
})
return Response({"message": "You are successfully logged in",
"user_info":data,"token": token, "success": True},status=status.HTTP_200_OK)
else :
raise Exception('not authorised')
except Exception as error:
traceback.print_exc()
return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK)
class LogoutView(APIView):
permission_classes = (permissions.IsAuthenticated,)
def get(self, request):
request.user.auth_token.delete()
logout(request)
return Response({"message": "success", 'code': status.HTTP_200_OK, 'detail': "logout success"})
在应用程序 urls.py 添加新的 url:
path('logout/',LogoutView.as_view()),
推荐阅读
- linux - Wget:如何保持 cookie 会话活动以进行递归或镜像下载(--keep-session-cookies 不起作用)
- javascript - 汉堡下拉菜单如何停止工作?
- android - onReceive BroadcastReceiver 从不要求明确的意图 Android android Pie
- r - 使用聚合函数创建多个列并在 data.table 中分组
- java - 无法从 Firebase 实时数据库中删除数据
- postgresql - Postgres 是否按主键存储?
- javascript - 我可以在 React 中修改 CSS 伪元素吗?
- c++ - 我需要一些帮助来删除向量中的一些元素。或者也许交换 c++
- sql - PostGreSql 使用拥有 Max 子句获取两列的唯一组合
- regex - 如何评估由 Julia 中的正则表达式替换的函数?