lib.itmens/mastodon/auth.py

33 lines
1.3 KiB
Python
Raw Normal View History

2020-05-05 23:50:48 +08:00
from django.contrib.auth.backends import ModelBackend, UserModel
2022-04-01 20:03:37 -04:00
from .api import verify_account
2020-05-05 23:50:48 +08:00
class OAuth2Backend(ModelBackend):
2023-01-11 19:11:31 -05:00
"""Used to glue OAuth2 and Django User model"""
2020-05-05 23:50:48 +08:00
# "authenticate() should check the credentials it gets and returns
# a user object that matches those credentials."
# arg request is an interface specification, not used in this implementation
2022-04-01 03:07:56 -04:00
2023-12-31 08:32:19 -05:00
def authenticate(self, request, username=None, password=None, **kwargs):
2023-01-11 19:11:31 -05:00
"""when username is provided, assume that token is newly obtained and valid"""
2023-12-31 08:32:19 -05:00
token = kwargs.get("token", None)
site = kwargs.get("site", None)
2020-10-22 21:45:05 +02:00
if token is None or site is None:
2020-05-05 23:50:48 +08:00
return
mastodon_username = None
2020-05-05 23:50:48 +08:00
if username is None:
2022-04-01 03:07:56 -04:00
code, user_data = verify_account(site, token)
if code == 200 and user_data:
mastodon_username = user_data.get("username")
if not mastodon_username:
return None
2020-05-05 23:50:48 +08:00
try:
2023-01-11 19:11:31 -05:00
user = UserModel._default_manager.get(
mastodon_username__iexact=mastodon_username, mastodon_site__iexact=site
2023-01-11 19:11:31 -05:00
)
return user if self.user_can_authenticate(user) else None
2020-05-05 23:50:48 +08:00
except UserModel.DoesNotExist:
return None