Hook in oauth2 code with DRF
<p>I am trying to build an app which has user login and signup functionality.<br>I can create login and signup both from django, and DRF but could not hook in oAuth2 with DRF to make it functional.<br>I have no idea where should i use it.<br><br>Should I generate token on signup or login?<br>How can I make it functional?</p>

<p>Here is my code </p>

<p><strong>serializers.py</strong></p>

<pre><code>class UserSerializer(ModelSerializer):
    class Meta:
        model = User


class UserCreateSerializer(ModelSerializer):
    email = EmailField()
    username =  CharField()
    first_name = CharField(required=False)
    last_name = CharField(required=False)
    password = CharField()
    confirm_password = CharField()
    class Meta:
        model = User
        fields = [
            'username',
            'email',
            'first_name',
            'last_name',
            'password',
            'confirm_password'
        ]
        extra_kwargs = {"password": {"write_only": True}}


    def create(self, validated_data):
        username = validated_data['username']
        first_name = validated_data['first_name']
        last_name = validated_data['last_name']
        email = validated_data['email']
        password = validated_data['password']
        confirm_password = validated_data['password']
        user_obj = User(
                username = username,
                first_name = first_name,
                last_name = last_name,
                email = email
            )
        user_obj.set_password(password)
        user_obj.save()
        return validated_data



class UserLoginSerializer(ModelSerializer):
    username = CharField()
    class Meta:
        model = User
        fields = [
            'username',
            # 'email',
            'password',
            # 'token',

        ]
        extra_kwargs = {"password":
                            {"write_only": True}
                            }
    def validate(self, data):
        return data
</code></pre>

<p><strong>views.py</strong></p>

<pre><code>class UserCreateAPI(CreateAPIView):
    serializer_class = UserCreateSerializer
    queryset = User.objects.all()
    permission_classes = [AllowAny]

class UserLoginAPI(APIView):
    permission_classes = [AllowAny]
    serializer_class = UserLoginSerializer

    def post(self, request, *args, **kwargs):
        data = request.data
        print('data',data)
        serializer = UserLoginSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            if new_data:
                try:
                    user = User.objects.get(username=data['username'])
                    print ('user',user)
                except ObjectDoesNotExist:
                    return HttpResponse("Can't find this user")
                login(request, user)
            return Response(new_data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code></pre>

<p><strong>tools.py</strong></p>

<pre><code>def get_token_json(access_token):
    return JsonResponse({
        'access_token':access_token.token,
        'expires_in':datetime.now() + timedelta(days=365),
        'token_type':'Bearer',
        'refresh_token':access_token.refresh_token.token,
        'scope':access_token.scope
    })


def get_access_token(user):
    application = Application.objects.get(name="Foodie")
    try:
        old_access_token = AccessToken.objects.get(user=user, application=application)
        old_refresh_token = RefreshToken.objects.get(user=user, access_token=old_access_token)
    except ObjectDoesNotExist:
        return HttpResponse('Have not set any token')
    else:
        old_access_token.delete()
        old_refresh_token.delete()
    new_token = generate_token()
    refresh_token = generate_token()
    access_token=AccessToken.objects.create(user=user, application=app, expires=datetime.now() + timedelta(days=365),token=new_token)
    RefreshToken.objects.create(user=user, application=app, token=refresh_token, access_token=access_token)
    print('aceess',AccessToken)
    return get_token_json(access_token)
</code></pre>

<p><strong>How can i bridge the gap between DRF and oAuth2 to make login and user registration functional?</strong></p>

<p>Try using python social auth.</p>

<p>Add <code>social.apps.django_app.default</code> to <code>INSTALLED_APPS</code></p>

<p>Add <code>social.backends.facebook.FacebookOAuth2</code> to <code>AUTHENTICATION_BACKENDS</code></p>

<p>Add <code>url(r'^auth/', include('social.apps.django_app.urls', namespace='social'))</code> to your <code>urls.py</code></p>

<p>However this will work if you have session authentication in your app. If you want to use token based only, then either add a pipe to create the token and send it or take a look at <a href="https://github.com/PhilipGarnero/django-rest-framework-social-oauth2" rel="nofollow">https://github.com/PhilipGarnero/django-rest-framework-social-oauth2</a></p>

python django python-3.x oauth-2.0 django-rest-framework