Debian Codegraph @

allauth/socialaccount/providers/shopify/provider.py

raw
1 from __future__ import annotations
2
3 from typing import Any
4
5 from django.conf import settings
6 from django.http import HttpRequest
7
8 from allauth.account.models import EmailAddress
9 from allauth.socialaccount.providers.base import ProviderAccount
10 from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
11 from allauth.socialaccount.providers.shopify.views import ShopifyOAuth2Adapter
12
13
14 class ShopifyAccount(ProviderAccount):
15 def get_user_data(self):
16 return self.account.extra_data.get("shop", {})
17
18
19 class ShopifyProvider(OAuth2Provider):
20 id = "shopify"
21 name = "Shopify"
22 account_class = ShopifyAccount
23 oauth2_adapter_class = ShopifyOAuth2Adapter
24
25 @property
26 def is_per_user(self):
27 grant_options = (
28 getattr(settings, "SOCIALACCOUNT_PROVIDERS", {})
29 .get("shopify", {})
30 .get("AUTH_PARAMS", {})
31 .get("grant_options[]", "")
32 )
33 return grant_options.lower().strip() == "per-user"
34
35 def get_auth_params_from_request(self, request: HttpRequest, action):
36 ret = super().get_auth_params_from_request(request, action)
37 shop = request.GET.get("shop", None)
38 if shop:
39 ret.update({"shop": shop})
40 return ret
41
42 def get_default_scope(self):
43 return ["read_orders", "read_products"]
44
45 def extract_uid(self, data):
46 if self.is_per_user:
47 return str(data["associated_user"]["id"])
48 else:
49 return str(data["shop"]["id"])
50
51 def extract_common_fields(self, data):
52 if self.is_per_user:
53 return dict(
54 email=data["associated_user"]["email"],
55 first_name=data["associated_user"]["first_name"],
56 last_name=data["associated_user"]["last_name"],
57 )
58 else:
59 # See: https://docs.shopify.com/api/shop
60 # Without online mode, User is only available with Shopify Plus,
61 # email is the only common field
62 return dict(email=data["shop"]["email"])
63
64 def extract_email_addresses(self, data: dict[str, Any]) -> list[EmailAddress]:
65 ret = []
66 email = None
67 email_verified = False
68 if self.is_per_user:
69 if associated_user := data.get("associated_user"):
70 email = associated_user.get("email")
71 email_verified = associated_user.get("email_verified", False)
72 else:
73 # The documentation of Shopify does not state anything about
74 # verified email addresses.
75 email = (data.get("shop") or {}).get("email")
76 email_verified = False
77 if email:
78 ret.append(
79 EmailAddress(
80 email=email,
81 verified=email_verified,
82 primary=True,
83 )
84 )
85 return ret
86
87
88 provider_classes = [ShopifyProvider]