-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.ts
42 lines (38 loc) · 1.54 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import {Configuration} from "./src/xapi";
import AsyncLock from 'async-lock';
export interface TokenResponse {
token_type: string;
expires_in: number;
access_token: string;
refresh_token: string;
}
export async function getAccessToken(basePath: string, username: string, password: string): Promise<TokenResponse> {
const formParams = new FormData();
formParams.append('client_id', username);
formParams.append('client_secret', password);
formParams.append('grant_type', 'client_credentials');
const refreshResponseFetch = await fetch(`${basePath}/connect/token`, {
method: 'POST',
body: formParams
});
if (!refreshResponseFetch.ok) {
throw new Error(`Refresh failed with status code ${refreshResponseFetch.status}'`);
}
return refreshResponseFetch.json();
}
export function createXAPIConfiguration(basePath: string, username: string, password: string){
let accessTokenResponse: TokenResponse| null = null;
let expires = 0;
const lock = new AsyncLock();
return new Configuration({
basePath: `${basePath}/xapi/v1`,
accessToken: async () => lock.acquire('token', async () => {
const now = Date.now();
if (!accessTokenResponse || now > expires){
accessTokenResponse = await getAccessToken(basePath, username, password);
expires = now + accessTokenResponse.expires_in * 60 * 1000;
}
return accessTokenResponse.access_token
})
})
}