如何检查cookie是否存在并在此基础上允许特定页面的权限?

问题描述

我正在 Django 中使用自定义中间件创建授权,我将令牌保存在 cookie 中,现在我想检查 cookie 是否有效,如果它有效,然后允许用户访问页面,否则应该重定向登录页面

这是我在 views.py 中的登录方法,我在其中获取令牌并将其设置为 cookie

@H_502_4@def loginPage(request): form = AuthenticationForm() if request.method == 'POST': print("login........") username = request.POST.get('username') password = request.POST.get('password') bearerTokenResponse = requests.post( 'http://localhost:8000/auth/login',json={"email": username,"password": password}) print(bearerTokenResponse) code = bearerTokenResponse.json()['code'] # Check if the code is 200 it's successfully get the token if code == 200: token = bearerTokenResponse.json()['token'] print(token) response = HttpResponse("Cookie Set") # Render the home page(patients) response = render(request,'dashboard.html') # Set the cookie with key name 'core-api' response.set_cookie('core-api',token,max_age=3600) # expire in 1 hour return response return render(request,'login.html',{'form': form}) # Get the cookie with the key name 'core-api' def getcookie(request): s = request.COOKIES['core-api'] return HttpResponse(s)

和中间件

@H_502_4@from django.conf import settings class LoginMiddleware: def __init__(self,get_response): #print(get_response) pass def __call__(self,request): #response = self.get_response(request) pass #return response def process_view(self,request,view_func,*view_args,**view_kargs): email = request.COOKIES['core-api'] print('this is the cookie from views.py:') print(email) def process_exception(self,exception): pass def process_template_response(self,response): pass

我想我不需要在登录视图中使用中间件,所以我可以在没有令牌的情况下使用登录。 有什么建议可以实现这一目标吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)