Spaces:
Sleeping
Sleeping
Download components/cogDecode.py from n3m/q39gqf6o08: direct link, hf CLI and curl.
- Browser
- Download file 2.24 kB
-
https://huggingface.co/spaces/n3m/q39gqf6o08/resolve/main/components/cogDecode.py
- Command line
-
hf download hf://spaces/n3m/q39gqf6o08/components/cogDecode.py
-
curl -L -o cogDecode.py https://huggingface.co/spaces/n3m/q39gqf6o08/resolve/main/components/cogDecode.py
2.24 kB
| import os | |
| import boto3 | |
| import base64 | |
| import json | |
| import boto3 | |
| import re | |
| from stcog import CognitoAuthenticator | |
| from stcog.session_provider import Boto3SessionProvider | |
| pool_id = os.environ["COGNITO_USER_POOL_ID"] | |
| app_client_id = os.environ["COGNITO_APP_CLIENT_ID"] | |
| app_client_secret = os.environ["COGNITO_APP_CLIENT_SECRET"] | |
| cognito_domain = os.environ["COGNITO_DOMAIN"] | |
| redirect_uri = os.environ["COGNITO_REDIRECT_URI"] | |
| region = os.environ["AWS_REGION"] | |
| identity_pool_id = os.environ["COGNITO_IDENTITY_POOL_ID"] | |
| aws_account_id = os.environ["AWS_ACCOUNT_ID"] | |
| authenticator = CognitoAuthenticator( | |
| pool_id=pool_id, | |
| app_client_id=app_client_id, | |
| app_client_secret=app_client_secret, | |
| use_cookies=False | |
| ) | |
| session_provider = Boto3SessionProvider( | |
| region=region, | |
| account_id=aws_account_id, | |
| user_pool_id=pool_id, | |
| identity_pool_id=identity_pool_id, | |
| ) | |
| # ------------------------------------------------------- | |
| # Decode access token to JWT to get user's cognito groups | |
| # ------------------------------------------------------- | |
| # Ref - https://gist.github.com/GuillaumeDerval/b300af6d4f906f38a051351afab3b95c | |
| def pad_base64(data): | |
| """ | |
| Makes sure base64 data is padded. | |
| Args: | |
| data: base64 token string. | |
| Returns: | |
| data: padded token string. | |
| """ | |
| missing_padding = len(data) % 4 | |
| if missing_padding != 0: | |
| data += "=" * (4 - missing_padding) | |
| return data | |
| def get_user_cognito_groups(id_token): | |
| """ | |
| Decode id token to get user cognito groups. | |
| Args: | |
| id_token: id token of a successfully authenticated user. | |
| Returns: | |
| user_cognito_groups: a list of all the cognito groups the user belongs to. | |
| """ | |
| if id_token != "": | |
| header, payload, signature = id_token.split(".") | |
| printable_payload = base64.urlsafe_b64decode(pad_base64(payload)) | |
| payload_dict = json.loads(printable_payload) | |
| user_cognito_groups = list(dict(payload_dict)["cognito:groups"]) | |
| user_email = dict(payload_dict)["email"] | |
| email_split = re.split('\.|\@|_|\+', user_email) | |
| else: | |
| user_cognito_groups = [] | |
| email_split = [] | |
| output = [email_split[0], user_cognito_groups] | |
| return output | |