Skip to content

Commit

Permalink
Fix token refreshing & implement automatic token refreshing on failed…
Browse files Browse the repository at this point in the history
… requests
  • Loading branch information
StefanNienhuis committed Jun 9, 2022
1 parent 53f0e67 commit 1020120
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 18 deletions.
4 changes: 2 additions & 2 deletions plugin/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion plugin/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "homebridge-bold",
"displayName": "Homebridge Bold",
"version": "2.1.0",
"version": "2.1.1",
"description": "HomeKit support for the Bold Smart Locks.",
"main": "build/index.js",
"engines": {
Expand Down
24 changes: 17 additions & 7 deletions plugin/src/bold.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type APIResponse<Data> = APISuccess<Data> | APIError;
export class BoldAPI {

constructor(
private config: Config,
public config: Readonly<Config>,
private log: Logger
) {}

Expand Down Expand Up @@ -99,12 +99,25 @@ export class BoldAPI {
}
}

async activate(deviceId: number): Promise<boolean> {
async activate(deviceId: number, hasRefreshedToken = false): Promise<boolean> {
this.log.debug(`Activating device (${deviceId})`);

let response = await this.request('POST', `/v1/devices/${deviceId}/remote-activation`);

if (!response.success) {
if (!response.success && response.error.code == 401 && !hasRefreshedToken) {
// If HTTP 401, try token refresh
this.log.warn(`Error while activating device (${deviceId}). Refreshing token and retrying.`);

await this.refresh();

let result = await this.activate(deviceId, true);

if (!result) {
this.log.error('Activation failed even after token refresh. Try logging in again. If this problem persists, open an issue.');
}

return result;
} else if (!response.success) {
this.log.error(`Error ${response.error.code ? `(${response.error.code}) ` : ''}while activating device (${deviceId}): ${response.error.message}`);

return false;
Expand Down Expand Up @@ -163,11 +176,8 @@ export class BoldAPI {

let data = response.data as any;

this.config.accessToken = data.access_token;
this.config.refreshToken = data.refresh_token;

this.log.debug('Successfully refreshed access token');
return { accessToken: this.config.accessToken, refreshToken: this.config.refreshToken };
return { accessToken: data.access_token, refreshToken: data.refresh_token };
}

}
14 changes: 6 additions & 8 deletions plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class BoldPlatform implements DynamicPlatformPlugin {
private accessories: PlatformAccessory[] = [];

private hap: HAP;
private config: Config;
// private config: Config;
private bold: BoldAPI;

private refreshInterval?: NodeJS.Timer;
Expand All @@ -27,8 +27,7 @@ class BoldPlatform implements DynamicPlatformPlugin {
private api: API
) {
this.hap = api.hap;
this.config = config as Config;
this.bold = new BoldAPI({ ...this.config }, this.log);
this.bold = new BoldAPI(config as Config, this.log);

api.on(APIEvent.DID_FINISH_LAUNCHING, async () => {
await this.refreshAccessToken();
Expand Down Expand Up @@ -200,7 +199,7 @@ class BoldPlatform implements DynamicPlatformPlugin {
return;
}

let platformIndex = config.platforms.findIndex((platform: any) => platform.platform == PLATFORM_NAME && platform.accessToken == this.config.accessToken);
let platformIndex = config.platforms.findIndex((platform: any) => platform.platform == PLATFORM_NAME && platform.accessToken == this.bold.config.accessToken);

let hasWarned = false;
if (platformIndex == -1) {
Expand Down Expand Up @@ -229,7 +228,7 @@ class BoldPlatform implements DynamicPlatformPlugin {
return;
}

platformIndex = config.platforms.findIndex((platform: any) => platform.platform == PLATFORM_NAME && platform.accessToken == this.config.accessToken);
platformIndex = config.platforms.findIndex((platform: any) => platform.platform == PLATFORM_NAME && platform.accessToken == this.bold.config.accessToken);

if (platformIndex == -1 && hasWarned == false) {
this.log.warn("Warning while reading config for access token refresh: Couldn't find platform with current access token. Using first entry of Bold config.");
Expand All @@ -239,14 +238,13 @@ class BoldPlatform implements DynamicPlatformPlugin {
if (platformIndex == -1) {
this.log.error("Error while reading config for access token refresh: Couldn't find entry of Bold platform. Skipping token refresh.");
}

this.config.accessToken = refreshedTokens.accessToken;
this.config.refreshToken = refreshedTokens.refreshToken;

config.platforms[platformIndex].accessToken = refreshedTokens.accessToken;
config.platforms[platformIndex].refreshToken = refreshedTokens.refreshToken;

await fs.writeJSON(this.api.user.configPath(), config, { spaces: 4 });

this.bold.config = { ...this.bold.config, accessToken: refreshedTokens.accessToken, refreshToken: refreshedTokens.refreshToken };
}

}

0 comments on commit 1020120

Please sign in to comment.