| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from datetime import timedelta |
| 4 |
|
| 5 |
from django.http import HttpRequest |
| 6 |
from django.utils import timezone |
| 7 |
|
| 8 |
from allauth.socialaccount import app_settings |
| 9 |
from allauth.socialaccount.adapter import get_adapter |
| 10 |
from allauth.socialaccount.models import SocialToken |
| 11 |
from allauth.socialaccount.providers.oauth2.views import ( |
| 12 |
OAuth2Adapter, |
| 13 |
OAuth2CallbackView, |
| 14 |
OAuth2LoginView, |
| 15 |
) |
| 16 |
|
| 17 |
|
| 18 |
class LineOAuth2Adapter(OAuth2Adapter): |
| 19 |
provider_id = "line" |
| 20 |
access_token_url = "https://api.line.me/oauth2/v2.1/token" # nosec |
| 21 |
authorize_url = "https://access.line.me/oauth2/v2.1/authorize" |
| 22 |
profile_url = "https://api.line.me/v2/profile" # https://developers.line.biz/en/reference/line-login/#get-user-profile |
| 23 |
# https://developers.line.biz/en/reference/line-login/#verify-id-token |
| 24 |
id_token_url = "https://api.line.me/oauth2/v2.1/verify" # nosec |
| 25 |
|
| 26 |
def parse_token(self, data): |
| 27 |
""" |
| 28 |
data: access_token data from line |
| 29 |
""" |
| 30 |
settings = app_settings.PROVIDERS.get(self.provider_id, {}) |
| 31 |
if "email" in settings.get("SCOPE", ""): |
| 32 |
token = SocialToken(token=data["id_token"]) |
| 33 |
else: |
| 34 |
token = SocialToken(token=data["access_token"]) |
| 35 |
token.token_secret = data.get("refresh_token", "") |
| 36 |
expires_in = data.get(self.expires_in_key, None) |
| 37 |
if expires_in: |
| 38 |
token.expires_at = timezone.now() + timedelta(seconds=int(expires_in)) |
| 39 |
|
| 40 |
return token |
| 41 |
|
| 42 |
def complete_login(self, request: HttpRequest, app, token, **kwargs): |
| 43 |
settings = app_settings.PROVIDERS.get(self.provider_id, {}) |
| 44 |
with get_adapter().get_requests_session() as sess: |
| 45 |
if "email" in settings.get("SCOPE", ""): |
| 46 |
payload = {"client_id": app.client_id, "id_token": token.token} |
| 47 |
resp = sess.post(self.id_token_url, payload) |
| 48 |
else: |
| 49 |
headers = {"Authorization": f"Bearer {token.token}"} |
| 50 |
resp = sess.get(self.profile_url, headers=headers) |
| 51 |
resp.raise_for_status() |
| 52 |
extra_data = resp.json() |
| 53 |
return self.get_provider().sociallogin_from_response(request, extra_data) |
| 54 |
|
| 55 |
|
| 56 |
oauth2_login = OAuth2LoginView.adapter_view(LineOAuth2Adapter) |
| 57 |
oauth2_callback = OAuth2CallbackView.adapter_view(LineOAuth2Adapter) |