Skip to content

Commit

Permalink
Polished up ecobee account ID getter to support invalid JWTs
Browse files Browse the repository at this point in the history
  • Loading branch information
ziebelje committed Jan 8, 2022
1 parent 8c50791 commit ee6a196
Showing 1 changed file with 36 additions and 19 deletions.
55 changes: 36 additions & 19 deletions api/ecobee_token.php
Expand Up @@ -73,32 +73,49 @@ public function obtain($code) {
}

/**
* Get an ecobee_account_id from the ecobee JWT.
* Get an ecobee_account_id from the ecobee JWT. Check a bunch of stuff to
* make sure it's valid.
*
* @param ecobee_token $ecobee_token The ecobee_token.
*
* @return string The ecobee_account_id.
*/
public function get_ecobee_account_id($ecobee_token) {
$access_token_decoded = json_decode(
base64_decode(
str_replace(
'_',
'/',
str_replace(
'-',
'+',
explode(
'.',
$ecobee_token['access_token']
)[1]
)
)
),
true
);
$parts = explode('.', $ecobee_token['access_token']);
if(count($parts) !== 3) {
return null;
}

$payload = $parts[1];
$payload = str_replace(['_', '-'], ['/', '+'], $payload);

$json = base64_decode($payload);

if($json === false) {
return null;
}

$object = json_decode($json, true);
if($object === null) {
return null;
}

if(isset($object['sub']) === false) {
return null;
}

$sub_parts = explode('|', $object['sub']);
if(count($sub_parts) !== 2) {
return null;
}

$ecobee_account_id = $sub_parts[1];

if(strlen($ecobee_account_id) !== 36) {
return null;
}

return explode('|', $access_token_decoded['sub'])[1];
return $ecobee_account_id;
}

/**
Expand Down

0 comments on commit ee6a196

Please sign in to comment.