0

I don't know how to return token if user is present in my database. I have User model with login and password fields and I have created some users from dajngo admin site. In Urls i have registered slug:

 path('api-token/', AuthToken, name = 'api-token')

Auth token class looks like that ( this is exapmple from rest-framework documentation).

class AuthToken(ObtainAuthToken):

def post(self, request, *args, **kwargs):
    serializer = self.serializer_class(data=request.data,
                                       context={'request': request})
    serializer.is_valid(raise_exception=True)
    user = serializer.validated_data['user']
    token, created = Token.objects.get_or_create(user=user)
    return Response({
        'token': token.key,
    })

I want to check if user exist in mu sql-lite database and if so, return the token. Unfortunattly I don't understand this code. Can somebody explain me what is it doing and how can I change it to meet my requirements.

Another issue is that I have User view which returns users from my db

class UserView(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

It is reqistered this way

router = routers.DefaultRouter()
router.register('users', views.UserView)

urlpatterns = [
    path('',include(router.urls)),
]

Is this going to work? I'm not sure because there is no checking if somebody pass a token and if token is correct

pythonBeginer
  • 41
  • 1
  • 8

1 Answers1

0

If you don't use custom token authentication, then you should use build in auth.

https://www.django-rest-framework.org/api-guide/authentication/#by-exposing-an-api-endpoint

Just use the view provided by DRF

from rest_framework.authtoken import views
urlpatterns += [
    url(r'^api-token-auth/', views.obtain_auth_token)
]

Regarding authorization on your UserView, see: https://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme

you can just add

permission_classes = [IsAuthenticated]

It allows only authenticated users to use that endpoint

ImEagle
  • 83
  • 7
  • I think I can't use build in view because I have my own User model. I have to check by myself if user exist in dtabase and then provide a token in response – pythonBeginer Apr 04 '20 at 16:31
  • That's view also works perfect with custom User models. Just make sure you updated your settings `AUTH_USER_MODEL` – ImEagle Apr 06 '20 at 09:40
  • I don't understand. I have added permission_classes = [IsAuthenticated] to my view but it doesn't work. Do You know where can I find an example of auth based on my user model? – pythonBeginer Apr 18 '20 at 19:44