Skip to content

Commit a8c57bd

Browse files
committed
Update api.py
1 parent d731a74 commit a8c57bd

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

pyhilo/api.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import asyncio
4+
import base64
45
from datetime import datetime, timedelta
56
import json
67
import random
@@ -92,6 +93,7 @@ def __init__(
9293
self.ws_url: str = ""
9394
self.ws_token: str = ""
9495
self.endpoint: str = ""
96+
self._urn: str | None = None
9597

9698
@classmethod
9799
async def async_create(
@@ -145,6 +147,27 @@ async def async_get_access_token(self) -> str:
145147

146148
return str(self._oauth_session.token["access_token"])
147149

150+
@property
151+
def urn(self) -> str | None:
152+
"""Extract URN from the JWT access token."""
153+
try:
154+
if not self._oauth_session.valid_token:
155+
return None
156+
token = self._oauth_session.token["access_token"]
157+
payload_part = token.split(".")[1]
158+
# Add padding if necessary
159+
padding = 4 - len(payload_part) % 4
160+
if padding != 4:
161+
payload_part += "=" * padding
162+
163+
decoded = base64.urlsafe_b64decode(payload_part)
164+
claims = json.loads(decoded)
165+
self._urn = claims.get("urn")
166+
return self._urn
167+
except (IndexError, json.JSONDecodeError, KeyError):
168+
LOG.error("Failed to extract URN from access token")
169+
return None
170+
148171
def dev_atts(
149172
self, attribute: str, value_type: Union[str, None] = None
150173
) -> Union[DeviceAttribute, str]:

0 commit comments

Comments
 (0)