At my serializers.py I have got the following:
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'password')
def create(self, validated_data):
return User.objects.create_user(**validated_data)
at my views.py I have got the following:
import serializers
from rest_framework.decorators import permission_classes, api_view
from rest_framework.permissions import AllowAny
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework import status
import json
from django.http import JsonResponse
from oauth2_provider.models import Application, AccessToken
@permission_classes((AllowAny,))
@csrf_exempt
@api_view(['POST'])
def create_auth(request, format=None):
if request.user.is_authenticated():
return Response({"already_registered": "User with that username has already registered"}, status=701)
data = request.data
print data
serializer = UserSerializer(data=data, partial=True)
if serializer.is_valid():
u=serializer.save(username= data.get(u'username') )
application=Application.objects.create(user=u, client_type="public", authorization_grant_type="password",name="general")
client_id = application.client_id #call the url to get your tokens, use urllib or something similar
client_secret = application.client_secret
return JsonResponse({'client_id': client_id, 'client_password' : client_secret}, status=201)
else:
return JsonResponse({'errors': serializer.errors}, status=400)
I have added following at my urls.py
urlpatterns = patterns(
'',
url(r'^register/', 'social_app.views.create_auth'),
url(r'^auth/', include('rest_framework_social_oauth2.urls')),
)
Testing:
sadaf2605@pavilion-g4:~$ curl -X POST -H "Content-Type: application/json" -d '{"email":"boba@athingy09876.com", "password":"p4ssword", "username": "user100"}' http://localhost:8000/register/
returns:
{"client_password": "EjQKMCAGmsUEm3L26uO7XSKnrZZVSVBQJUuvqfwi63pRB7d5y3ndlbZV0cBgQU7t3lCy078DS0FLqhaYoe9JZF0cQCIAgFKo7lfYU3npP7Eyv1PLk2eLPRnD3lF3OUUP", "client_id": "JhbwqqvE34vVjWiuMPnkV1eE636QQ3SzyQXLjmgs"}
sadaf2605@pavilion-g4:~$ curl -X POST -d "client_id=JhbwqqvE34vVjWiuMPnkV1eE636QQ3SzyQXLjmgs&client;_secret=EjQKMCAGmsUEm3L26uO7XSKnrZZVSVBQJUuvqfwi63pRB7d5y3ndlbZV0cBgQU7t3lCy078DS0FLqhaYoe9JZF0cQCIAgFKo7lfYU3npP7Eyv1PLk2eLPRnD3lF3OUUP&grant;_type=password&username;=user100&password;=p4ssword" http://localhost:8000/auth/token
{"access_token": "bssEYlDNaXefq8TPNRuu8oLolqYJp2", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "fankCVPC3P84pQWI5oWOIhtWLCky4w", "scope": "read write"}