| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import uuid |
| 4 |
from requests import RequestException |
| 5 |
|
| 6 |
from django.http import HttpRequest |
| 7 |
|
| 8 |
from allauth.socialaccount.adapter import get_adapter |
| 9 |
from allauth.socialaccount.providers.oauth2.views import ( |
| 10 |
OAuth2Adapter, |
| 11 |
OAuth2CallbackView, |
| 12 |
OAuth2LoginView, |
| 13 |
) |
| 14 |
from allauth.utils import get_request_param |
| 15 |
|
| 16 |
|
| 17 |
class VKOAuth2Adapter(OAuth2Adapter): |
| 18 |
provider_id = "vk" |
| 19 |
access_token_url = "https://id.vk.ru/oauth2/auth" # nosec |
| 20 |
authorize_url = "https://id.vk.ru/authorize" |
| 21 |
profile_url = "https://id.vk.ru/oauth2/user_info" |
| 22 |
|
| 23 |
def get_access_token_data( |
| 24 |
self, request: HttpRequest, app, client, pkce_code_verifier=None |
| 25 |
): |
| 26 |
code = get_request_param(self.request, "code") |
| 27 |
device_id = get_request_param(self.request, "device_id") |
| 28 |
extra_data = { |
| 29 |
# "state" isn't strictly necessary for now, but since VK ID documentation doesn't |
| 30 |
# specify required vs optional parameters at all, we still add this (now optional) |
| 31 |
# param to make the code less fragile for future, when they may start requiring it |
| 32 |
"state": str(uuid.uuid4()), |
| 33 |
"device_id": device_id, |
| 34 |
} |
| 35 |
data = client.get_access_token( |
| 36 |
code, pkce_code_verifier=pkce_code_verifier, extra_data=extra_data |
| 37 |
) |
| 38 |
self.did_fetch_access_token = True |
| 39 |
return data |
| 40 |
|
| 41 |
def complete_login(self, request: HttpRequest, app, token, **kwargs): |
| 42 |
req_data = { |
| 43 |
"access_token": token.token, |
| 44 |
"client_id": app.client_id, |
| 45 |
} |
| 46 |
with get_adapter().get_requests_session() as sess: |
| 47 |
resp = sess.post(self.profile_url, data=req_data) |
| 48 |
resp.raise_for_status() |
| 49 |
resp_data = resp.json() |
| 50 |
if "error" in resp_data or "user" not in resp_data: |
| 51 |
raise RequestException( |
| 52 |
"Could not get basic data for user being authenticated" |
| 53 |
) |
| 54 |
return self.get_provider().sociallogin_from_response(request, resp_data["user"]) |
| 55 |
|
| 56 |
|
| 57 |
oauth2_login = OAuth2LoginView.adapter_view(VKOAuth2Adapter) |
| 58 |
oauth2_callback = OAuth2CallbackView.adapter_view(VKOAuth2Adapter) |