|
| 1 | +import re |
| 2 | +import requests |
| 3 | + |
| 4 | +from django.http import HttpResponseBadRequest |
| 5 | + |
| 6 | +from allauth.exceptions import ImmediateHttpResponse |
| 7 | +from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, |
| 8 | + OAuth2LoginView, |
| 9 | + OAuth2CallbackView) |
| 10 | +from .provider import ShopifyProvider |
| 11 | + |
| 12 | + |
| 13 | +class ShopifyOAuth2Adapter(OAuth2Adapter): |
| 14 | + provider_id = ShopifyProvider.id |
| 15 | + supports_state = False |
| 16 | + scope_delimiter = ',' |
| 17 | + |
| 18 | + def _shop_domain(self): |
| 19 | + shop = self.request.GET.get('shop', '') |
| 20 | + if '.' not in shop: |
| 21 | + shop = '{}.myshopify.com'.format(shop) |
| 22 | + # Ensure the provided hostname parameter is a valid hostname, |
| 23 | + # ends with myshopify.com, and does not contain characters |
| 24 | + # other than letters (a-z), numbers (0-9), dots, and hyphens. |
| 25 | + if not re.match(r'^[a-z0-9-]+\.myshopify\.com$', shop): |
| 26 | + raise ImmediateHttpResponse(HttpResponseBadRequest( |
| 27 | + 'Invalid `shop` parameter')) |
| 28 | + return shop |
| 29 | + |
| 30 | + def _shop_url(self, path): |
| 31 | + shop = self._shop_domain() |
| 32 | + return 'https://{}{}'.format(shop, path) |
| 33 | + |
| 34 | + @property |
| 35 | + def access_token_url(self): |
| 36 | + return self._shop_url('/admin/oauth/access_token') |
| 37 | + |
| 38 | + @property |
| 39 | + def authorize_url(self): |
| 40 | + return self._shop_url('/admin/oauth/authorize') |
| 41 | + |
| 42 | + @property |
| 43 | + def profile_url(self): |
| 44 | + return self._shop_url('/admin/shop.json') |
| 45 | + |
| 46 | + def complete_login(self, request, app, token, **kwargs): |
| 47 | + headers = { |
| 48 | + 'X-Shopify-Access-Token': '{token}'.format(token=token.token)} |
| 49 | + response = requests.get( |
| 50 | + self.profile_url, |
| 51 | + headers=headers) |
| 52 | + extra_data = response.json() |
| 53 | + return self.get_provider().sociallogin_from_response( |
| 54 | + request, extra_data) |
| 55 | + |
| 56 | + |
| 57 | +oauth2_login = OAuth2LoginView.adapter_view(ShopifyOAuth2Adapter) |
| 58 | +oauth2_callback = OAuth2CallbackView.adapter_view(ShopifyOAuth2Adapter) |
0 commit comments