src/interceptors/auth-interceptor.ts   A
last analyzed

Complexity

Total Complexity 9
Complexity/F 4.5

Size

Lines of Code 52
Function Count 2

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 28
mnd 7
bc 7
fnc 2
dl 0
loc 52
rs 10
bpm 3.5
cpm 4.5
noi 0
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A AuthInterceptor.setAuthorizationHeader 0 13 3
B AuthInterceptor.requestHandler 0 26 6
1
import { AxiosRequestConfig } from 'axios';
2
import { GrantType } from '../bedita-api-client';
3
import RequestInterceptor from './request-interceptor';
4
5
/**
6
 * Auth interceptor.
7
 * It responsible to add Authorization header if it needs.
8
 */
9
export default class AuthInterceptor extends RequestInterceptor {
10
11
    /**
12
     * If present it adds access token to Authorization header.
13
     *
14
     * @param config The axios request config
15
     */
16
    public async requestHandler(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {
17
        config = await this.setAuthorizationHeader(config);
18
19
        // Authorization header set so go ahead
20
        if (config.headers?.Authorization) {
21
            return config;
22
        }
23
24
        // trying client credentials auth so go ahead
25
        if (config.url === '/auth' && config.data?.grant_type === GrantType.ClientCredentials) {
26
            return config;
27
        }
28
29
        if (!this.beditaClient.getConfig('clientId')) {
30
            return config;
31
        }
32
33
        await this.beditaClient.clientCredentials();
34
35
        return await this.setAuthorizationHeader(config);
36
    }
37
38
    /**
39
     * Set Authorization header if not already set and access token is present.
40
     *
41
     * @param config The axios request config
42
     */
43
    protected async setAuthorizationHeader(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {
44
        const accessToken = await this.beditaClient.getStorageService().getAccessToken();
45
        if (accessToken && !config.headers?.Authorization) {
46
            config.headers.Authorization = `Bearer ${accessToken}`;
47
        }
48
49
        return config;
50
    }
51
}
52