jazzband / django-oauth-toolkit

OAuth2 goodies for the Djangonauts!
https://django-oauth-toolkit.readthedocs.io
Other
3.16k stars 793 forks source link

Emit a user_logged_in signal much like in django.contrib.auth #632

Open hetsch opened 6 years ago

hetsch commented 6 years ago

I have the situation where I have to post-process a valid login and enriching the User object with some custom data. In the backend, I listen for the user_logged_in signal of the django.contrib.auth framework. This works great so far, but if a user logs via the frontend (REST and django-oauth-tookit), the user_logged_in signal is not emitted. My question would be if you think it would be worthwhile or even possible to implement the user_logged_in signal dispatching logic in this great package? Thank's for your thoughts and help!

NAveeN4416 commented 4 years ago

Hello hetch, we shouldn't use login function i.e.., from django.contrib.auth, because in REST we use different authentication methods like token or basic authentication techniques right. i think it's better to send signal explicitly when ever you try to generate token or authenticate with the credentials. Still we can make that happen for triggering signal user ### login function and the remove those user credentials from the sessions table that's it

paulchoix commented 1 year ago

Based on this Stackoverflow post, I used the following to solve this issue:

from django.contrib.auth.signals import user_logged_in

from oauth2_provider.signals import app_authorized
from oauth2_provider.models import AccessToken

def handle_app_authorized(sender, request, token, **kwargs):
    if not AccessToken.objects.filter(token=token).exists():
        return

    access_token = AccessToken.objects.get(token=token)

    if access_token.user:
        user_logged_in.send(sender=sender, request=request,
                            user=access_token.user)

app_authorized.connect(handle_app_authorized)

I was then able to use @receiver(user_logged_in) to receive the log in signal from django-oauth-toolkit.