@@ -110,7 +110,10 @@ def __init__(self, config: YepCodeApiConfig = None):
110110 self .team_id = final_config .get ("team_id" )
111111 self .access_token = final_config .get ("access_token" )
112112 self .timeout = final_config .get ("timeout" )
113- self ._init_team_id_by_access_token ()
113+ if not self .client_id and self .access_token :
114+ self .client_id = self ._client_id_from_access_token ()
115+ if not self .team_id and self .client_id :
116+ self .team_id = self ._team_id_from_client_id ()
114117
115118 def get_client_id (self ) -> str :
116119 if not self .client_id :
@@ -122,20 +125,28 @@ def get_team_id(self) -> str:
122125 raise ValueError ("Team ID is not set" )
123126 return self .team_id
124127
125- def _init_team_id_by_access_token (self ) -> None :
128+ def _client_id_from_access_token (self ) -> str :
126129 if not self .access_token :
127- return
128-
129- payload = self .access_token .split ("." )[1 ]
130- # Add padding if necessary
131- payload += "=" * ((4 - len (payload ) % 4 ) % 4 )
132- decoded_payload = json .loads (base64 .b64decode (payload ).decode ())
133-
134- if groups := decoded_payload .get ("groups" ):
135- self .team_id = next ((group for group in groups if group != "sandbox" ), None )
130+ raise ValueError ("Access token is not set" )
131+ try :
132+ payload = self .access_token .split ("." )[1 ]
133+ payload += "=" * ((4 - len (payload ) % 4 ) % 4 )
134+ decoded_payload = json .loads (base64 .b64decode (payload ).decode ())
135+ return decoded_payload ["client_id" ]
136+ except Exception as e :
137+ raise ValueError (f"Failed to extract client_id from access token: { e } " )
138+
139+ def _team_id_from_client_id (self ) -> str :
140+ if not self .client_id :
141+ raise ValueError ("Client ID is not set" )
142+ import re
136143
137- if not self .team_id :
138- raise ValueError ("No teamId found in the access token" )
144+ match = re .match (r"^sa-(.*)-[a-z0-9]{8}$" , self .client_id )
145+ if not match :
146+ raise ValueError (
147+ "Client ID is not valid. It must be in the format sa-<teamId>-<8randomCharsOrDigits>"
148+ )
149+ return match .group (1 )
139150
140151 def _get_base_url (self ) -> str :
141152 return f"{ self .api_host } /api/{ self .team_id } /rest"
@@ -164,7 +175,6 @@ def _get_access_token(self) -> str:
164175 if not self .access_token :
165176 raise ValueError ("No access token received from server" )
166177
167- self ._init_team_id_by_access_token ()
168178 return self .access_token
169179
170180 except Exception as error :
0 commit comments