Debian Codegraph @

allauth/socialaccount/providers/dataporten/views.py

raw
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.base import ProviderException
7 from allauth.socialaccount.providers.oauth2.views import (
8 OAuth2Adapter,
9 OAuth2CallbackView,
10 OAuth2LoginView,
11 )
12
13
14 class DataportenOAuth2Adapter(OAuth2Adapter):
15 provider_id = "dataporten"
16 access_token_url = "https://auth.dataporten.no/oauth/token" # nosec
17 authorize_url = "https://auth.dataporten.no/oauth/authorization"
18 profile_url = "https://auth.dataporten.no/userinfo"
19 groups_url = "https://groups-api.dataporten.no/groups/"
20
21 def complete_login(self, request: HttpRequest, app, token, **kwargs):
22 """
23 Arguments:
24 request - The get request to the callback URL
25 /accounts/dataporten/login/callback.
26 app - The corresponding SocialApp model instance
27 token - A token object with access token given in token.token
28 Returns:
29 Should return a dict with user information intended for parsing
30 by the methods of the DataportenProvider view, i.e.
31 extract_uid(), extract_extra_data(), and extract_common_fields()
32 """
33 # The authentication header
34 headers = {"Authorization": f"Bearer {token.token}"}
35
36 # Userinfo endpoint, for documentation see:
37 # https://docs.dataporten.no/docs/oauth-authentication/
38 with get_adapter().get_requests_session() as sess:
39 resp = sess.get(self.profile_url, headers=headers)
40 resp.raise_for_status()
41 response_json = resp.json()
42 extra_data = response_json["user"]
43
44 # Finally test that the audience property matches the client id
45 # for validification reasons, as instructed by the Dataporten docs
46 # if the userinfo-response is used for authentication
47 if response_json["audience"] != app.client_id:
48 raise ProviderException(
49 "Dataporten returned a user with an audience field \
50 which does not correspond to the client id of the \
51 application."
52 )
53
54 return self.get_provider().sociallogin_from_response(request, extra_data)
55
56
57 oauth2_login = OAuth2LoginView.adapter_view(DataportenOAuth2Adapter)
58 oauth2_callback = OAuth2CallbackView.adapter_view(DataportenOAuth2Adapter)