Completed
Push — main ( 6d480a...457c6f )
by Stefano
18s queued 12s
created

AuthInterceptor.requestHandler   B

Complexity

Conditions 6

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 26
rs 8.6666
c 0
b 0
f 0
cc 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 requestHandler(config: AxiosRequestConfig): Promise<AxiosRequestConfig> {
17
        config = this.setAuthorizationHeader(config);
18
19
        // Authorization header set so go ahead
20
        if (config.headers?.Authorization) {
21
            return Promise.resolve(config);
22
        }
23
24
        // trying client credentials auth so go ahead
25
        if (config.url === '/auth' && config.data?.grant_type === GrantType.ClientCredentials) {
26
            return Promise.resolve(config);
27
        }
28
29
        if (!this.beditaClient.getConfig('clientId')) {
30
            return Promise.resolve(config);
31
        }
32
33
        return this.beditaClient
34
            .clientCredentials()
35
            .then(() => Promise.resolve(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 setAuthorizationHeader(config: AxiosRequestConfig): AxiosRequestConfig {
44
        const accessToken = this.beditaClient.getStorageService().accessToken;
45
        if (accessToken && !config.headers?.Authorization) {
46
            config.headers.Authorization = `Bearer ${accessToken}`;
47
        }
48
49
        return config;
50
    }
51
}
52