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):
|
|
|
|
""" Used to glue OAuth2 and Django User model """
|
|
|
|
# "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):
|
2020-05-05 23:50:48 +08: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
|
|
|
|
|
|
|
|
if username is None:
|
2022-04-01 03:07:56 -04:00
|
|
|
code, user_data = verify_account(site, token)
|
|
|
|
if code == 200:
|
|
|
|
userid = user_data['id']
|
2020-05-05 23:50:48 +08:00
|
|
|
else:
|
|
|
|
# aquiring user data fail means token is invalid thus auth fail
|
|
|
|
return None
|
|
|
|
|
|
|
|
# when username is provided, assume that token is newly obtained and valid
|
|
|
|
try:
|
2022-04-01 03:07:56 -04:00
|
|
|
user = UserModel._default_manager.get(mastodon_id=userid, mastodon_site=site)
|
2020-05-05 23:50:48 +08:00
|
|
|
except UserModel.DoesNotExist:
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
if self.user_can_authenticate(user):
|
|
|
|
return user
|
|
|
|
return None
|