| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.http import HttpRequest |
| 4 |
|
| 5 |
from allauth.socialaccount.adapter import get_adapter |
| 6 |
from allauth.socialaccount.providers.oauth2.views import ( |
| 7 |
OAuth2Adapter, |
| 8 |
OAuth2CallbackView, |
| 9 |
OAuth2LoginView, |
| 10 |
) |
| 11 |
|
| 12 |
from .client import WeixinOAuth2Client |
| 13 |
|
| 14 |
|
| 15 |
class WeixinOAuth2Adapter(OAuth2Adapter): |
| 16 |
provider_id = "weixin" |
| 17 |
access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token" # nosec |
| 18 |
profile_url = "https://api.weixin.qq.com/sns/userinfo" |
| 19 |
client_class = WeixinOAuth2Client |
| 20 |
|
| 21 |
@property |
| 22 |
def authorize_url(self): |
| 23 |
settings = self.get_provider().get_settings() |
| 24 |
url = settings.get( |
| 25 |
"AUTHORIZE_URL", "https://open.weixin.qq.com/connect/qrconnect" |
| 26 |
) |
| 27 |
return url |
| 28 |
|
| 29 |
def complete_login(self, request: HttpRequest, app, token, **kwargs): |
| 30 |
openid = kwargs.get("response", {}).get("openid") |
| 31 |
with get_adapter().get_requests_session() as sess: |
| 32 |
params = {"access_token": token.token, "openid": openid} |
| 33 |
resp = sess.get(self.profile_url, params=params) |
| 34 |
resp.raise_for_status() |
| 35 |
extra_data = resp.json() |
| 36 |
nickname = extra_data.get("nickname") |
| 37 |
if nickname: |
| 38 |
extra_data["nickname"] = nickname.encode("raw_unicode_escape").decode( |
| 39 |
"utf-8" |
| 40 |
) |
| 41 |
return self.get_provider().sociallogin_from_response(request, extra_data) |
| 42 |
|
| 43 |
|
| 44 |
oauth2_login = OAuth2LoginView.adapter_view(WeixinOAuth2Adapter) |
| 45 |
oauth2_callback = OAuth2CallbackView.adapter_view(WeixinOAuth2Adapter) |