DRFSAMV — Django Rest Framework + Social Auth + Mongo + VueJS (Part 5)

Bartek Dobrowolski
5 min readJan 22, 2018

--

Part 1 — Setting up Django with databases — PostgreSQL and MongoDB
Part 2 — Setting up VueJS
Part 3 — Configure Google API
Part 4 — Setting up backend social auth API
Part 5 — Communicate with API from VueJS
Part 6 — Raw project ready to use

Here in the 5th part, I’ll show how to use Postman, very useful tool to test API requests and getting responses. If you are familiar with this tool and the way how to find small bugs through the Postman, then just pass this step and jump into next part [link to part related with fixing files]

Try to log in with our created button “auth Google”

First test of auth Google

and hit the button, F12 to look what’s behind:

Result in console

but this error doesn’t say a lot. We know that’s 500 Internal Server Error, so it means something is wrong with our scripts, configurations or not sending proper data.

Detective time

Change tab from Console to Network, so you’ll notice that our frontend tries to communicate with server on http://localhost:8000/api/login/social/token_user/google

and scrollind down the headers lists in the bottom, you can spot that we’re sending three datas:

  • cliendId
  • code
  • redirectUri
Data sent o the backend to try to authenticate

so following the documentation we see that part:

{       
"provider": "facebook",
"code": "AQBPBBTjbdnehj51"
}

We don’t have the provider in our request. Let’s take a look into the console:

Can’t authorize in any way. So basically there aren’t any authorization method, even when we implemented the requests, we don’t have a “core” to process all to register the user and authenticate him, and also, we don’t have proper datas to send.

Using POSTMAN

With postman we can create own request and test if result’s are satisfying. From:

copy clientId, code and redirectUri to create own request. We can consume our API by sending POST requests so, let’s do it:

Seting up POSTMAN for sending test request

and send this stuff.

Response after sending testing POST request

Now the error changed. It’s not 500, but 400, which means that server doesn’t understand what we’ve sent. We’re also sure we sent all what’s needed, so, the bigger problem is on the server side.

Fixing authentication

The first thing, we need to deliver to backed proper datas, so we can assure that all is delivering properly.

Modify the frontend/src/mixins/mixin.js by adding {provider: “google-oauth2”}:

import VueAxios from 'vue-axios'
import axios from 'axios';
import Vue from 'vue'
export const authMixin = {
methods: {
checkToken: function(provider, redirect){
axios.post("http://localhost:8000/api/check/", {"token": localStorage.getItem("vue-authenticate.vueauth_token")}).then((response) => {
var path = (response.data.status)? true : "/";
redirect({ path: path});
}).catch((error) => {
});
},
authenticate: function(provider) {
this.$auth.authenticate('google', {provider: "google-oauth2"}).then(function (response) {
console.log("Works!");
}).catch(function(error) {
console.log(error);
});
}
}
}

Save the file and test:

The right way to deliver data with provider and code

so, we’re filling the requirements to send all needed data to authenticate user. Now let’s fix processing the server side error.

Fixing Django

We need to add two urls for our purposes — registering user and checking if he already logged in:

from django.conf.urls import url, include
from django.contrib import admin
from .views import check_token
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/login/', include('rest_social_auth.urls_jwt')),
url(r'^api/login/', include('rest_social_auth.urls_token')),
url(r'^api/login/', include('rest_social_auth.urls_session')),
url(r'^auth/', include('rest_framework_social_oauth2.urls')),
url(r'api/check/', check_token),
]

and in the backend/_main/ create views.py file and add code:

from django.shortcuts import render, redirect
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_exempt
from rest_framework.decorators import api_view
from django.http import HttpResponse, JsonResponse
import json
from rest_framework.authtoken.models import Token
@csrf_exempt
@api_view(['POST'])
def check_token(request, format=None):
token = Token.objects.filter(key = request.data['token']).exists()
return JsonResponse({"status": token})

Here we’re getting token from frontend, saved in the local storage under parameter “vue-authenticate.vueauth_token”. Everytime when we want to perform an action, which needs to be logged in, we always get the token, send to the server to check. In return we’re getting two responses as “True” or “False” and after that we can decide what to do — pass user to desired url, allow him to make an action.

Testing

Now you can test it, try to log in with the button again and after every made steps, you should see this:

Dashboard page after sucessfull login

But what if we will delete the token? Hit F12, go to the Application, Local Storage aaaand there:

Removing authentication token

just select vue-authenticate.vueauth_token and delete. Refresh the page and… yes, you’re be redirected to the “/” url, which means our Home page:

Result after deleting the token from localstorage

so all is working well.

Now you know how everything works (basically). In the last part, I’m giving you ready to use template if you’ll forget or delete current one. You can download it anytime + some suggestions to dig deeper.

Next part:
Part 6 — Raw project ready to reuse

Previous part:
Part 4 — Setting up backend social auth API

--

--