-
Notifications
You must be signed in to change notification settings - Fork 3
/
oauth2Interceptor.ts
65 lines (61 loc) · 1.9 KB
/
oauth2Interceptor.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import {
BodyCasing,
bodyParser,
bodySerializer,
ContentType,
HttpClient,
NormalizedHttpOptions
} from '@coolio/http';
import { createAuthInterceptor } from './authInterceptor';
import { OAuth2InterceptorOptions, OAuth2TokenResponse } from './oauth2Interceptor.types';
import { AuthError } from './authError';
export const createOAuth2Interceptor = ({
oauth: {
clientId,
clientSecret,
contentType,
refreshTokenUrl,
httpClientOptions,
},
authStorage,
canAuthorize,
onAuthorizationFailure,
}: OAuth2InterceptorOptions) => {
const authHttpClient = new HttpClient({
requestHandler: httpClientOptions.requestHandler,
bodyParser: bodyParser({ bodyCasing: BodyCasing.CAMEL_CASE }),
bodySerializer: bodySerializer({ bodyCasing: BodyCasing.SNAKE_CASE }),
...httpClientOptions,
});
const getAuthData = async () => {
const authData = await Promise.resolve(authStorage.getData());
if (!authData) {
throw new AuthError('Data received from AuthStorage is undefined.');
}
return authData;
};
return createAuthInterceptor({
reauthorize: async () => {
const response = await authHttpClient.post(refreshTokenUrl, {
headers: {
'Content-Type': contentType || ContentType.URL_ENCODED,
},
body: {
clientId,
clientSecret,
grantType: 'refresh_token',
refreshToken: (await getAuthData()).refreshToken,
},
});
const oauth2Data: OAuth2TokenResponse = await response.parsedBody();
await Promise.resolve(authStorage.setData(oauth2Data));
},
setAuthorizationData: async (options: NormalizedHttpOptions) => {
// Get previously stored tokens
const { accessToken, tokenType } = await getAuthData();
options.headers['Authorization'] = tokenType ? `${tokenType} ${accessToken}` : accessToken;
},
onAuthorizationFailure,
canAuthorize,
});
};