Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ The following API calls are available
/* Authentication */
/*********************/
tado.authenticate(refreshToken?, interval?);
tado.authenticateWithToken(token?, interval?);
tado.setTokenCallback(cb);

/*********************/
Expand Down
8 changes: 7 additions & 1 deletion examples/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,16 @@ async function main(): Promise<void> {
);
console.log("------------------------------------------------");
}
await futureToken;
const token = await futureToken;

const me = await tado.getMe();
console.log(me);

const [_, futureToken2] = await tado.authenticateWithToken(token);
const token2 = await futureToken2;
console.log("new token: ", token2);
const me2 = await tado.getMe();
console.log(me2);
}

main();
27 changes: 27 additions & 0 deletions src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,33 @@ export class BaseTado {
return [verify.data, token];
}

/**
* Authenticate with the Oauth server. An existing token may be supplied to bypass the device auth
* flow if it is still valid, otherwise the device flow is initiaited.
*
* @param existingToken - Attempt to use the provided token to re-authenticate
* @param timeout - Ignore the Tado provided timeout for device auth and use this value
* @returns A promise that resolves to either a `DeviceVerification` object for device auth flows
* and a promise of a token, or an undefined auth flow and a promise of a token, if the refresh token
* was supplied
*/
async authenticateWithToken(
existingToken?: Token,
timeout?: number,
): Promise<[DeviceVerification | undefined, Promise<Token>]> {
const now = new Date();

if (existingToken?.expiry && existingToken.expiry > now) {
this.#token = existingToken;
try {
return [undefined, new Promise((resolve) => resolve(existingToken))];
} catch {
// Refresh token is no good
}
}
return this.authenticate(existingToken?.refresh_token, timeout);
}

/**
* Makes an API call to the provided URL with the specified method and data.
*
Expand Down