Repository navigation
Expand file tree
/
Copy pathauth.py
More file actions
90 lines (71 loc) · 2.72 KB
/
Copy pathauth.py
File metadata and controls
90 lines (71 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
8000
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
from dataclasses import dataclass
import base64
import hashlib
import hmac
import boto3
from botocore import UNSIGNED
from botocore.client import Config
from pycognito import Cognito
COGNITO_APP_CLIENT_ID = "14og512b9u20b8vrdm55d8empi"
COGNITO_CLIENT_SECRET_KEY = "k554d4pvgf2n0chbhgtmbe4q0ul4a9flp3pcl6a47ch6rripvvr"
COGNITO_USER_POOL_ID = "us-east-1_Ofd50EosD"
COGNITO_REGION = "us-east-1"
@dataclass
class WinixAuthResponse:
user_id: str
access_token: str
refresh_token: str
id_token: str
def login(username: str, password: str, **kwargs) -> WinixAuthResponse:
"""Generate fresh credentials via Cognito SRP auth."""
from jose import jwt
pool_id = kwargs.get("pool_id", COGNITO_USER_POOL_ID)
client_id = kwargs.get("client_id", COGNITO_APP_CLIENT_ID)
client_secret = kwargs.get("client_secret", COGNITO_CLIENT_SECRET_KEY)
user = Cognito(
pool_id,
client_id,
client_secret=client_secret,
username=username,
botocore_config=Config(signature_version=UNSIGNED),
)
user.authenticate(password=password)
if not user.access_token or not user.refresh_token or not user.id_token:
raise RuntimeError("Authentication failed: missing tokens")
return WinixAuthResponse(
user_id=jwt.get_unverified_claims(user.access_token)["sub"],
access_token=user.access_token,
refresh_token=user.refresh_token,
id_token=user.id_token,
)
def refresh(user_id: str, refresh_token: str, **kwargs) -> WinixAuthResponse:
"""Refresh tokens using refresh_token."""
client_id = kwargs.get("client_id", COGNITO_APP_CLIENT_ID)
client_secret = kwargs.get("client_secret", COGNITO_CLIENT_SECRET_KEY)
auth_params = {
"REFRESH_TOKEN": refresh_token,
"SECRET_HASH": _secret_hash(user_id, client_id, client_secret),
}
resp = _boto_client(kwargs.get("pool_region")).initiate_auth(
ClientId=client_id,
AuthFlow="REFRESH_TOKEN",
AuthParameters=auth_params,
)
return WinixAuthResponse(
user_id=user_id,
access_token=resp["AuthenticationResult"]["AccessToken"],
refresh_token=refresh_token,
id_token=resp["AuthenticationResult"]["IdToken"],
)
def _secret_hash(username: str, client_id: str, client_secret: str) -> str:
"""Compute Cognito secret hash (HMAC-SHA256)."""
msg = (username + client_id).encode()
key = client_secret.encode()
return base64.b64encode(hmac.new(key, msg, hashlib.sha256).digest()).decode()
def _boto_client(region):
"""Get an uncredentialed boto cognito-idp client."""
return boto3.client(
"cognito-idp",
config=Config(signature_version=UNSIGNED),
region_name=region or COGNITO_REGION,
)