2024-07-03 00:07:07 -04:00
|
|
|
from django.contrib.auth.backends import ModelBackend
|
2024-07-01 17:29:38 -04:00
|
|
|
from django.http import HttpRequest
|
2023-08-10 11:27:31 -04:00
|
|
|
|
2024-07-01 17:29:38 -04:00
|
|
|
from mastodon.models.common import SocialAccount
|
|
|
|
|
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
|
|
|
|
2024-07-01 17:29:38 -04:00
|
|
|
def authenticate(
|
|
|
|
self, request: HttpRequest | None, 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"""
|
2024-07-01 17:29:38 -04:00
|
|
|
account: SocialAccount = kwargs.get("social_account", None)
|
|
|
|
if not account or not account.user:
|
2020-05-05 23:50:48 +08:00
|
|
|
return None
|
2024-07-01 17:29:38 -04:00
|
|
|
return account.user if self.user_can_authenticate(account.user) else None
|