This repository was archived by the owner on Oct 6, 2026. It is now read-only.
Repository navigation
Introduce ApiAccess for representing access scopes #482
Merged
+351
−55
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| # Handling access scope operations | ||
|
|
||
| #### Table of contents | ||
|
|
||
| - [Common ApiAccess operations](#common-apiaccess-operations) | ||
| - [Using ApiAccess to handle changes in app access scopes](#using-apiaccess-to-handle-changes-in-app-access-scopes) | ||
|
|
||
| There are common operations that are used for managing [access scopes](https://shopify.dev/docs/admin-api/access-scopes) in apps. Such operations include serializing, deserializing and normalizing scopes. Other operations can include checking whether two sets of scopes grant the same API access or whether one set covers the access granted by another set. | ||
|
|
||
| To encapsulate the access granted by access scopes, you can use the `ApiAccess` value object. | ||
|
|
||
| ## Common ApiAccess operations | ||
|
|
||
| ### Constructing an ApiAccess | ||
|
|
||
| ```python | ||
| api_access = ApiAccess(["read_products", "write_orders"]) # List of access scopes | ||
| another_api_access = ApiAccess("read_products, write_products, unauthenticated_read_themes") # String of comma-delimited access scopes | ||
| ``` | ||
|
|
||
| ### Serializing ApiAccess | ||
|
|
||
| ```python | ||
| api_access = ApiAccess(["read_products", "write_orders", "unauthenticated_read_themes"]) | ||
|
|
||
| access_scopes_list = list(api_access) # ["read_products", "write_orders", "unauthenticated_read_themes"] | ||
| comma_delmited_access_scopes = str(api_access) # "read_products,write_orders,unauthenticated_read_themes" | ||
| ``` | ||
|
|
||
| ### Comparing ApiAccess objects | ||
|
|
||
| #### Checking for API access equality | ||
|
|
||
| ```python | ||
| expected_api_access = ApiAccess(["read_products", "write_orders"]) | ||
|
|
||
| actual_api_access = ApiAccess(["read_products", "read_orders", "write_orders"]) | ||
| non_equal_api_access = ApiAccess(["read_products", "write_orders", "read_themes"]) | ||
|
|
||
| actual_api_access == expected_api_access # True | ||
| non_equal_api_access == expected_api_access # False | ||
| ``` | ||
|
|
||
| #### Checking if ApiAccess covers the access of another | ||
|
|
||
| ```python | ||
| superset_access = ApiAccess(["write_products", "write_orders", "read_themes"]) | ||
| subset_access = ApiAccess(["read_products", "write_orders"]) | ||
|
|
||
| superset_access.covers(subset_access) # True | ||
| ``` | ||
|
|
||
| ## Using ApiAccess to handle changes in app access scopes | ||
|
|
||
| If your app has changes in the access scopes it requests, you can use the `ApiAccess` object to determine whether the merchant needs to go through OAuth based on the scopes currently granted. A sample decorator shows how this can be achieved when loading an app. | ||
|
|
||
| ```python | ||
| from shopify import ApiAccess | ||
|
|
||
|
|
||
| def oauth_on_access_scopes_mismatch(func): | ||
| def wrapper(*args, **kwargs): | ||
| shop_domain = get_shop_query_paramer(request) # shop query param when loading app | ||
| current_shop_scopes = ApiAccess(ShopStore.get_record(shopify_domain = shop_domain).access_scopes) | ||
| expected_access_scopes = ApiAccess(SHOPIFY_API_SCOPES) | ||
|
|
||
| if current_shop_scopes != expected_access_scopes: | ||
| return redirect_to_login() # redirect to OAuth to update access scopes granted | ||
|
|
||
| return func(*args, **kwargs) | ||
|
|
||
| return wrapper | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| # Session tokens | ||
|
|
||
| The Shopify Python API library provides helper methods to decode [session tokens](https://shopify.dev/concepts/apps/building-embedded-apps-using-session-tokens). You can use the `decode_from_header` function to extract and decode a session token from an HTTP Authorization header. | ||
|
|
||
| ## Basic usage | ||
|
|
||
| ```python | ||
| from shopify import session_token | ||
|
|
||
| decoded_payload = session_token.decode_from_header( | ||
| authorization_header=your_auth_request_header, | ||
| api_key=your_api_key, | ||
| secret=your_api_secret, | ||
| ) | ||
| ``` | ||
|
|
||
| ## Create a decorator using `session_token` | ||
|
|
||
| Here's a sample decorator that protects your app views/routes by requiring the presence of valid session tokens as part of a request's headers. | ||
|
|
||
| ```python | ||
| from shopify import session_token | ||
|
|
||
|
|
||
| def session_token_required(func): | ||
| def wrapper(*args, **kwargs): | ||
| request = args[0] # Or flask.request if you use Flask | ||
| try: | ||
| decoded_session_token = session_token.decode_from_header( | ||
| authorization_header = request.headers.get('Authorization'), | ||
| api_key = SHOPIFY_API_KEY, | ||
| secret = SHOPIFY_API_SECRET | ||
| ) | ||
| with shopify_session(decoded_session_token): | ||
| return func(*args, **kwargs) | ||
| except session_token.SessionTokenError as e: | ||
| # Log the error here | ||
| return unauthorized_401_response() | ||
|
|
||
| return wrapper | ||
|
|
||
|
|
||
| def shopify_session(decoded_session_token): | ||
| shopify_domain = decoded_session_token.get("dest") | ||
| access_token = get_offline_access_token_by_shop_domain(shopify_domain) | ||
|
|
||
| return shopify.Session.temp(shopify_domain, SHOPIFY_API_VERSION, access_token) | ||
|
|
||
|
|
||
| @session_token_required # Requests to /products require session tokens | ||
| def products(request): | ||
| products = shopify.Product.find() | ||
| ... | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import re | ||
|
|
||
|
|
||
| class ApiAccessError(Exception): | ||
| pass | ||
|
|
||
|
|
||
| class ApiAccess: | ||
|
|
||
| SCOPE_DELIMITER = "," | ||
| SCOPE_RE = re.compile(r"\A(?P<unauthenticated>unauthenticated_)?(write|read)_(?P<resource>.*)\Z") | ||
| IMPLIED_SCOPE_RE = re.compile(r"\A(?P<unauthenticated>unauthenticated_)?write_(?P<resource>.*)\Z") | ||
|
|
||
| def __init__(self, scopes): | ||
| if type(scopes) == str: | ||
| scopes = scopes.split(self.SCOPE_DELIMITER) | ||
|
|
||
| self.__store_scopes(scopes) | ||
|
|
||
| def covers(self, api_access): | ||
| return api_access._compressed_scopes <= self._expanded_scopes | ||
|
|
||
| def __str__(self): | ||
| return self.SCOPE_DELIMITER.join(self._compressed_scopes) | ||
|
|
||
| def __iter__(self): | ||
| return iter(self._compressed_scopes) | ||
|
|
||
| def __eq__(self, other): | ||
| return type(self) == type(other) and self._compressed_scopes == other._compressed_scopes | ||
|
|
||
| def __store_scopes(self, scopes): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just out of curiosity what do double leading underscores do? 😅 Is this for name mangling?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is the Python convention of defining "private" methods. Although, methods in Python cannot be truly private. This is just a way to indicate that this method should not be consumed as a public interface as it is more likely to change.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ohh okay makes sense! |
||
| sanitized_scopes = frozenset(filter(None, [scope.strip() for scope in scopes])) | ||
| self.__validate_scopes(sanitized_scopes) | ||
|
|
||
| implied_scopes = frozenset(self.__implied_scope(scope) for scope in sanitized_scopes) | ||
| self._compressed_scopes = sanitized_scopes - implied_scopes | ||
| self._expanded_scopes = sanitized_scopes.union(implied_scopes) | ||
|
|
||
| def __validate_scopes(self, scopes): | ||
| for scope in scopes: | ||
| if not self.SCOPE_RE.match(scope): | ||
| error_message = "'{s}' is not a valid access scope".format(s=scope) | ||
| raise ApiAccessError(error_message) | ||
|
|
||
| def __implied_scope(self, scope): | ||
| match = self.IMPLIED_SCOPE_RE.match(scope) | ||
| if match: | ||
| return "{unauthenticated}read_{resource}".format( | ||
| unauthenticated=match.group("unauthenticated") or "", | ||
| resource=match.group("resource"), | ||
| ) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.