Django, Secure Login with Ajax from Http page

2019-04-15 23:15发布

问题:

I log in users from a Http page via ajax. I'm making the request to a secure (https) page. My issue is that I'm not receiving a response because (I assume) my view function is returning an HttpResponse object to the https page (my user is still at http).

Here is the code

  @secure_required      
  def login_async(request):
      if request.method=='POST':
         email=request.POST.get('email', '')
          try:
            user=User.objects.get(email__exact=email)
            username=user.username

          except User.DoesNotExist:
             username=''

      password=request.POST.get('password', '')


      user=auth.authenticate(username=username, password=password)
      if user is not None:
        auth.login(request,user)
        user_status=1
        user_fname=user.first_name


       user_data=[{'user_status':user_status, 'user_fname':user_fname,'user_favorite':user_favorite,'flag_record':flag_record, 'message_sent':message_sent,'is_post_owner':is_post_owner}]
       json_data=json.dumps(user_data)
       response=HttpResponse()
       response['Content-Type']="text/javascript"
       response.write(json_data)
       return response  
     else:  
        user_data=[{'user_status':user_status}]
        json_data=json.dumps(user_data)
        response=HttpResponse()
        response['Content-Type']="text/javascript"
        response.write(json_data)
        return response 

  else:
    user_data=[{'user_status':"0"}]                         

           json_data=json.dumps(user_data)
        response=HttpResponse()
        response['Content-Type']="text/javascript"
        response.write(json_data)
        return response 

Why not just make the whole page https, you ask? Good question. I was having some issues with making the Tweet Button https compatible.

Thanks

回答1:

If you'd check what your browser is sending over the net you'd see that it's not POST as you wanted but OPTIONS request. It's caused because https XHTTPRequest (AJAX) from http page is treated same way as cross-domain, check jQuery: I get OPTIONS request instead of GET for answer on handling that.

And one more thing, whole:

json_data=json.dumps(user_data)
response=HttpResponse()
response['Content-Type']="text/javascript"
response.write(json_data)
return response

Could be replaced just by:

return HttpResponse(json.dumps(user_data), mimetype='text/javascript')