-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathauth.ts
More file actions
49 lines (43 loc) · 1.85 KB
/
auth.ts
File metadata and controls
49 lines (43 loc) · 1.85 KB
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
43
44
45
46
47
48
49
import { Configuration } from './src/xapi';
import AsyncLock from 'async-lock';
import axios, { AxiosError } from 'axios';
axios.interceptors.response.use((response) => response, (error) => Promise.reject(error instanceof AxiosError ? new Error(error.response?.data ? JSON.stringify(error.response?.data) : error.message) : error));
export function odataParamEncoder(value: string) {
return `'${value.replaceAll("'", "''")}'`;
}
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;
}),
});
}