Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest-auth registration. How to return user_id with the key when using token authentication

I am using Djando rest_auth.registration.

My corresponding entry in urls.py is

url(r'^rest-auth/registration/', include('rest_auth.registration.urls'))

My authentication class is rest_framework.authentication.TokenAuthentication

This rest API call works perfectly well.

When I register via this API I get the below response.

{
  "key": "3735f13cd69051579156f98ffda338a2d7a89bb5"
}

I also want to include the user_id field in the response. How do I go about doing that. I tried extending the method get_response_data from class RegisterView(CreateAPIView): but unable to do so. Can someone please advise the best practice to achieve this. Code would be ideal. Thanks.

I want to use the rest-auth/registration/ url provided out of box by rest_auth.registration. I do not want to create a separate new URL for this.

My Settings.py as follows

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'sdAPI.apps.SdapiConfig',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_framework_swagger',
'rest_auth.registration',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'django_extensions',
]

# auth and allauth settings
LOGIN_REDIRECT_URL = '/'
SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
    'SCOPE': ['email', 'publish_stream'],
    'METHOD': 'oauth2'  # instead of 'oauth2'
    }
}

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
    ),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
)
}

SITE_ID = 1
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' 
REST_SESSION_LOGIN = False

My urls.py as follows

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^user/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/',include('rest_auth.registration.urls')),
]
like image 457
Dilip Khemani Avatar asked Jul 07 '17 08:07

Dilip Khemani


1 Answers

I think you only need to override the TOKEN_SERIALIZER option in your REST_AUTH_SERIALIZERS configuration.

from rest_framework.authtoken.models import Token

class TokenSerializer(serializers.ModelSerializer):

    class Meta:
        model = Token
        fields = ('key', 'user')

Then, set it in your settings.py as shown in the docs,

REST_AUTH_SERIALIZERS = {
    'LOGIN_SERIALIZER': 'path.to.custom.LoginSerializer',
    'TOKEN_SERIALIZER': 'path.to.custom.TokenSerializer',
    ...
}
like image 53
zaidfazil Avatar answered Oct 17 '22 04:10

zaidfazil