3

How could I get the same functionality as django provides for authenticated user (an user global object to retrieve data for user profile etc.) into vue, for a single page application (using Vue Router, of course).

My point is that I do not know how could I create a middleware for vue equivalently to django middleware for keeping an user logged in once he provided username and password.

I know that I can use django rest framework jwt to implement an endpoint /api-token-auth/ to get the token needed (storing it into localStorge, so I could get it into axios headers) to be able to retrieve information from the api, but I don't have any user session besides the token, I don't have any information about the user passed to templates, of course.

How could I pass an user global object to every template? Is there an easy way to do that?

Thanks in advance.

yierstem
  • 1,933
  • 5
  • 21
  • 42
  • Django provide 'user' context object in each template if appropriate settings exist. https://stackoverflow.com/questions/13713077/get-user-information-in-django-templates . if I understood you well else please explain more – adnanmuttaleb Sep 16 '18 at 14:34
  • @adnanmuttaleb I don't intend to use django templates. I have Vue app separately from django. – yierstem Sep 16 '18 at 14:38

1 Answers1

3

Session Authentication can be implemented with Django REST Frameworks by adding SessionAuthentication class to settings.py as follows.

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

This will use Django's default session backend for Authentication. The catch, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls - PUT, PATCH, POST, DELETE.

For accessing current user, you can create API endpoint /users/current with

class CurrentUserView(APIView):
    def get(self, request):
        serializer = UserSerializer(request.user)
        return Response(serializer.data)
Ganesh
  • 3,128
  • 2
  • 17
  • 27