大家好,关于身份验证,关于重构一些旧的api端点,我有几个问题。例如,我有一个看法...
@csrf_exempt
# PARAMETERS: username, password
def submit_offer(request):
"""Submit an offer"""
username = request.GET.get("username")
password = request.GET.get("password")
# Authenticate user to set instance.user value into BuyerForm
user = authenticate(username=username, password=password)
if not user:
# Always want our potential Buyer to be logged in & authenticated
return JsonResponse({'message': 'Please login to continue.'})
if request.method == 'POST':
form = BuyerForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
# sets current user as Buyer.user
instance.user = user
instance.save()
return JsonResponse({'success': True}, status=200)
else:
data = form.errors.as_json()
return JsonResponse(data, status=400, safe=False)
else:
return JsonResponse(data={'status': 403})
现在每个使用表单的视图都需要抓取instance.user,下面具有相同的代码行...现在我认为使用request.user可以完成这项工作,但是当以这种方式进行测试时,返回AnonymousUser,这让我感到困惑?
username = request.GET.get("username")
password = request.GET.get("password")
# Authenticate user to set instance.user value into BuyerForm
user = authenticate(username=username, password=password)
现在有比在每个视图中手动认证用户更好的方法,例如在使用request.user的常规django视图中认证用户? (已编辑)
答案 0 :(得分:1)
password = request.GET.get("password")
。
这是设计Django应用程序的非常脆弱的方法。
请参阅 Accessing Username and Password in django request header returns None
顺便说一句,编写一个定制的中间件并将您的代码放在此处。
username = get_username_from_header
password = get_password_from_header
# Authenticate user to set instance.user value into BuyerForm
user = authenticate(username=username, password=password)
# Attach user to request
request.user = user
随着每个请求通过中间件传递,您可以从每个视图访问用户。