matthiask / django-authlib

Utilities for passwordless authentication (using magic links, Google, Facebook and Twitter OAuth currently)
https://django-authlib.readthedocs.io/
MIT License
61 stars 11 forks source link

Feature request: Add flag to identify whether a user was logged in via SSO #15

Open jkgenser opened 4 months ago

jkgenser commented 4 months ago

I would like to add a flag to the session like request.session["is_sso"] to indicate to other parts of my app that the user's session was established via SSO.

In order to support this feature, you could simply add a flag to the request that tells us that it was authenticated via SSO or via username/password.

This would allow us to use a django signal on login to then set the field.

Another option is to add ability to pass an on_logged_in callback so users of your library can modify the session immediately on establishment with arbitrary logic.

matthiask commented 4 months ago

Hi @jkgenser

I don't think it's documented anywhere but you could maybe achieve this already with the user.backend attribute: https://github.com/django/django/blob/cbf1e87398a58737e27e1b680283903caf661f90/django/contrib/auth/__init__.py#L87 This wouldn't work if you wanted to differentiate between uses of the django-authlib ModelBackend of course.

You could also write your own email_login helper:

from functools import partial
from authlib.views import email_login, oauth2
def my_email_login(request, **kwargs):
    user, created = email_login(request, **kwargs)
    if user:
        request.session["is_sso"] = True
    return user, created

my_oauth2 = partial(oauth2, email_login=email_login)

Or maybe even better, override post_login_response with your own callable which does all the things you want? https://github.com/matthiask/django-authlib/blob/8c47aea03d8cedb2cf494d320c60db6a33283b9d/authlib/views.py#L79

I'm not against adding additional functionality to django-authlib, e.g. a signal or something, if there are good reasons why the existing hooks aren't sufficient?

Thanks!