lib.itmens/mastodon/auth.py

30 lines
1.1 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
def authenticate(self, request, token=None, username=None, site=None, **kwargs):
2023-01-11 19:11:31 -05:00
"""when username is provided, assume that token is newly obtained and valid"""
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_id = 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_id = user_data["id"]
if not mastodon_id:
return None
2020-05-05 23:50:48 +08:00
try:
2023-01-11 19:11:31 -05:00
user = UserModel._default_manager.get(
2023-07-08 00:44:22 -04:00
mastodon_id__iexact=mastodon_id, 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