javascript - Django REST API Logout request -
for logging in, i'm doing like:
function setheader(xhr) { // per http authentication spec [2], credentials must // encoded in base64. lets utilize window.btoa [3] xhr.setrequestheader("authorization", "basic " + btoa(username + ':' + password)); } $.ajax({type: "post", url: auth_url, beforesend: setheader}). fail(function(resp){ console.log('bad credentials.') }). done(function(resp){ });
after which, i'm storing session in local storage.
however, logging out, i'm unable figure out how utilize session send request header, django's : request.logout()
logs out user having session id
for login can add together view similar one:
import json import requests django.shortcuts import render_to_response django.http import httpresponseredirect @csrf_protect def login(request): if request.method == "post": login = requests.post('http://your_url/api-token-auth/', data={'username': request.post['username'], 'password': request.post['password']}) response = json.loads(login.text) if response.status_code == 200: token = response['token'] request.session.flush() request.session['user'] = request.post['username'] if request.session.test_cookie_worked(): request.session.delete_test_cookie() homecoming httpresponseredirect("/") else: error = "error" request.session.set_test_cookie() homecoming render_to_response("login.html", {"error": error}, requestcontext(request))
for logout have in view is:
def logout(request): request.session.flush() homecoming httpresponseredirect('/')
on api side, have define api-token-auth in urls: here tutorial more informations
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')
this way token communication api. beside tokenauthentication can define , sessionauthentication. more can find in above tutorial
javascript django django-rest-framework django-users django-sessions
No comments:
Post a Comment