Debian Codegraph @

allauth/socialaccount/providers/dataporten/provider.py

raw
1 from __future__ import annotations
2
3 from allauth.socialaccount.providers.base import ProviderAccount
4 from allauth.socialaccount.providers.dataporten.views import DataportenOAuth2Adapter
5 from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
6
7
8 class DataportenAccount(ProviderAccount):
9 def get_avatar_url(self):
10 """
11 Returns a valid URL to an 128x128 .png photo of the user
12 """
13 # Documentation for user profile photos can be found here:
14 # https://docs.dataporten.no/docs/oauth-authentication/
15 photo = self.account.extra_data["profilephoto"]
16 return f"https://api.dataporten.no/userinfo/v1/user/media/{photo}"
17
18
19 class DataportenProvider(OAuth2Provider):
20 id = "dataporten"
21 name = "Dataporten"
22 account_class = DataportenAccount
23 oauth2_adapter_class = DataportenOAuth2Adapter
24
25 def extract_uid(self, data):
26 """
27 Returns the primary user identifier, an UUID string
28 See: https://docs.dataporten.no/docs/userid/
29 """
30 return data["userid"]
31
32 def extract_extra_data(self, data):
33 """
34 Extracts fields from `data` that will be stored in
35 `SocialAccount`'s `extra_data` JSONField.
36
37 All the necessary data extraction has already been done in the
38 complete_login()-view, so we can just return the data.
39 PS: This is default behaviour, so we did not really need to define
40 this function, but it is included for documentation purposes.
41
42 Typical return dict:
43 {
44 "userid": "76a7a061-3c55-430d-8ee0-6f82ec42501f",
45 "userid_sec": ["feide:[email protected]"],
46 "name": "Andreas \u00c5kre Solberg",
47 "email": "[email protected]",
48 "profilephoto": "p:a3019954-902f-45a3-b4ee-bca7b48ab507",
49 }
50 """
51 return data
52
53 def extract_common_fields(self, data):
54 """
55 This function extracts information from the /userinfo endpoint which
56 will be consumed by allauth.socialaccount.adapter.populate_user().
57 Look there to find which key-value pairs that should be saved in the
58 returned dict.
59
60 Typical return dict:
61 {
62 "userid": "76a7a061-3c55-430d-8ee0-6f82ec42501f",
63 "userid_sec": ["feide:[email protected]"],
64 "name": "Andreas \u00c5kre Solberg",
65 "email": "[email protected]",
66 "profilephoto": "p:a3019954-902f-45a3-b4ee-bca7b48ab507",
67 "username": "andreas",
68 }
69 """
70 # Make shallow copy to prevent possible mutability issues
71 data = dict(data)
72
73 # If a Feide username is available, use it. If not, use the "username"
74 # of the email-address
75 for userid in data.get("userid_sec"):
76 usertype, username = userid.split(":")
77 if usertype == "feide":
78 data["username"] = username.split("@")[0]
79 break
80 else:
81 # Only entered if break is not executed above
82 data["username"] = data.get("email").split("@")[0]
83
84 return data
85
86
87 provider_classes = [DataportenProvider]