middlewares.py 3.51 KB
Newer Older
ynerant's avatar
ynerant committed
1
2
3
4
from authlib.integrations.base_client import OAuthError
from authlib.integrations.django_client import OAuth
from authlib.oauth2.rfc6749 import OAuth2Token
from django.conf import settings
ynerant's avatar
ynerant committed
5
from django.contrib.auth import login
ynerant's avatar
ynerant committed
6
7
8
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin

ynerant's avatar
ynerant committed
9
10
from lg.models import DiscordUser

ynerant's avatar
ynerant committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

class OAuthMiddleware(MiddlewareMixin):

    def __init__(self, get_response=None):
        super().__init__(get_response)
        self.oauth = OAuth()

    def process_request(self, request):
        if settings.OAUTH_URL_WHITELISTS is not None:
            for w in settings.OAUTH_URL_WHITELISTS:
                if request.path.startswith(w):
                    return self.get_response(request)

        def update_token(token, refresh_token, access_token):
            request.session['token'] = token
            return None

        sso_client = self.oauth.register(
            settings.OAUTH_CLIENT_NAME, overwrite=True, **settings.OAUTH_CLIENT, update_token=update_token
        )

        if request.path.startswith('/oauth/callback'):
            self.clear_session(request)
            request.session['token'] = sso_client.authorize_access_token(request)
            if self.get_current_user(sso_client, request) is not None:
                redirect_uri = request.session.pop('redirect_uri', None)
                if redirect_uri is not None:
                    return redirect(redirect_uri)
                return redirect("index")

        if request.session.get('token', None) is not None:
            current_user = self.get_current_user(sso_client, request)
ynerant's avatar
ynerant committed
43
            login(request, current_user)
ynerant's avatar
ynerant committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
            if current_user is not None:
                return self.get_response(request)

        # remember redirect URI for redirecting to the original URL.
        request.session['redirect_uri'] = request.path
        return sso_client.authorize_redirect(request, settings.OAUTH_CLIENT['redirect_uri'])

    # fetch current login user info
    # 1. check if it's in cache
    # 2. fetch from remote API when it's not in cache
    @staticmethod
    def get_current_user(sso_client, request):
        token = request.session.get('token', None)
        if token is None or 'access_token' not in token:
            return None

        if not OAuth2Token.from_dict(token).is_expired() and 'user' in request.session:
ynerant's avatar
ynerant committed
61
            return DiscordUser.objects.get(discord_id=request.session['user'])
ynerant's avatar
ynerant committed
62
63
64
65

        try:
            res = sso_client.get(settings.OAUTH_CLIENT['userinfo_endpoint'], token=OAuth2Token(token))
            if res.ok:
ynerant's avatar
ynerant committed
66
67
68
69
70
71
72
                user_json = res.json()
                discord_id = user_json['id']
                user, _ = DiscordUser.objects.get_or_create(discord_id=discord_id)
                user.username = user_json['username']
                user.discriminator = user_json['discriminator']
                user.email = user_json['email']
                user.avatar_id = user_json['avatar']
ynerant's avatar
ynerant committed
73
                user.is_staff = user.is_superuser = f"{user.username}#{user.discriminator}" in settings.SUPERUSERS
ynerant's avatar
ynerant committed
74
75
76
                user.save()
                request.session['user'] = user.discord_id
                return user
ynerant's avatar
ynerant committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
            raise Exception(res, str(res.__dict__))
        except OAuthError as e:
            print(e)
        return None

    @staticmethod
    def clear_session(request):
        try:
            del request.session['user']
            del request.session['token']
        except KeyError:
            pass

    def __del__(self):
        print('destroyed')