Debian Codegraph @

allauth/socialaccount/providers/linkedin_oauth2/provider.py

raw
1 from __future__ import annotations
2
3 from allauth.socialaccount import app_settings
4 from allauth.socialaccount.providers.base import ProviderAccount, ProviderException
5 from allauth.socialaccount.providers.linkedin_oauth2.views import LinkedInOAuth2Adapter
6 from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
7
8
9 def _extract_name_field(data, field_name):
10 ret = ""
11 v = data.get(field_name, {})
12 if v:
13 if isinstance(v, str):
14 # Old V1 data
15 ret = v
16 else:
17 localized = v.get("localized", {})
18 preferred_locale = v.get(
19 "preferredLocale", {"country": "US", "language": "en"}
20 )
21 locale_key = f"{preferred_locale['language']}_{preferred_locale['country']}"
22 if locale_key in localized:
23 ret = localized.get(locale_key)
24 elif localized:
25 ret = next(iter(localized.values()))
26 return ret
27
28
29 def _extract_email(data):
30 """
31 {'elements': [{'handle': 'urn:li:emailAddress:319371470',
32 'handle~': {'emailAddress': '[email protected]'}}]}
33 """
34 ret = ""
35 elements = data.get("elements", [])
36 if len(elements) > 0:
37 ret = elements[0].get("handle~", {}).get("emailAddress", "")
38 return ret
39
40
41 class LinkedInOAuth2Account(ProviderAccount):
42 def to_str(self):
43 ret = super().to_str()
44 if self.account.extra_data.get("emailAddress"):
45 return self.account.extra_data["emailAddress"]
46 first_name = _extract_name_field(self.account.extra_data, "firstName")
47 last_name = _extract_name_field(self.account.extra_data, "lastName")
48 if first_name or last_name:
49 ret = f"{first_name} {last_name}".strip()
50 return ret
51
52 def get_avatar_url(self):
53 """
54 Attempts the load the avatar associated to the avatar.
55
56 Requires the `profilePicture(displayImage~:playableStreams)`
57 profile field configured in settings.py
58
59 :return:
60 """
61 provider_configuration = self.account.get_provider().get_settings()
62 configured_profile_fields = provider_configuration.get("PROFILE_FIELDS", [])
63 # Can't get the avatar when this field is not specified
64 picture_field = "profilePicture(displayImage~:playableStreams)"
65 if picture_field not in configured_profile_fields:
66 return super().get_avatar_url()
67 # Iterate over the fields and attempt to get it by configured size
68 profile_picture_config = provider_configuration.get("PROFILEPICTURE", {})
69 req_size = profile_picture_config.get("display_size_w_h", (100.0, 100.0))
70 req_auth_method = profile_picture_config.get("authorization_method", "PUBLIC")
71 # Iterate over the data returned by the provider
72 profile_elements = (
73 self.account.extra_data.get("profilePicture", {})
74 .get("displayImage~", {})
75 .get("elements", [])
76 )
77 for single_element in profile_elements:
78 if not req_auth_method == single_element["authorizationMethod"]:
79 continue
80 # Get the dimensions from the payload
81 image_data = (
82 single_element.get("data", {})
83 .get("com.linkedin.digitalmedia.mediaartifact.StillImage", {})
84 .get("displaySize", {})
85 )
86 if not image_data:
87 continue
88 width, height = image_data["width"], image_data["height"]
89 if not width or not height:
90 continue
91 if not width == req_size[0] or not height == req_size[1]:
92 continue
93 # Get the uri since actual size matches the requested size.
94 to_return = single_element.get(
95 "identifiers",
96 [
97 {},
98 ],
99 )[
100 0
101 ].get("identifier")
102 if to_return:
103 return to_return
104 return super().get_avatar_url()
105
106
107 class LinkedInOAuth2Provider(OAuth2Provider):
108 id = "linkedin_oauth2"
109 # Name is displayed to ordinary users -- don't include protocol
110 name = "LinkedIn"
111 account_class = LinkedInOAuth2Account
112 oauth2_adapter_class = LinkedInOAuth2Adapter
113
114 def extract_uid(self, data):
115 if "id" not in data:
116 raise ProviderException(
117 "LinkedIn encountered an internal error while logging in. \
118 Please try again."
119 )
120 return str(data["id"])
121
122 def get_profile_fields(self):
123 default_fields = [
124 "id",
125 "firstName",
126 "lastName",
127 # This would be needed to in case you need access to the image
128 # URL. Not enabling this by default due to the amount of data
129 # returned.
130 #
131 # 'profilePicture(displayImage~:playableStreams)'
132 ]
133 fields = self.get_settings().get("PROFILE_FIELDS", default_fields)
134 return fields
135
136 def get_default_scope(self):
137 scope = ["r_liteprofile"]
138 if app_settings.QUERY_EMAIL:
139 scope.append("r_emailaddress")
140 return scope
141
142 def extract_common_fields(self, data):
143 return dict(
144 first_name=_extract_name_field(data, "firstName"),
145 last_name=_extract_name_field(data, "lastName"),
146 email=_extract_email(data),
147 )
148
149
150 provider_classes = [LinkedInOAuth2Provider]