-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJWTAuth.ts
More file actions
176 lines (150 loc) · 5.65 KB
/
JWTAuth.ts
File metadata and controls
176 lines (150 loc) · 5.65 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { Configuration } from './Configuration';
import { Authentication } from './Authentication';
import { ApiErrorResponse } from './models';
type AuthResponse = {
statusCode: number;
statusMessage: string;
headers: NodeJS.Dict<string | string[]>;
body: any;
};
type AuthRejectType = {
response: AuthResponse | null;
errorResponse: ApiErrorResponse | null;
error: Error;
};
export class JWTAuth implements Authentication {
private _accessToken?: string;
private readonly _configuration: Configuration;
private readonly _fetcher: typeof fetch;
constructor(configuration: Configuration) {
this._configuration = configuration;
const resolvedFetch = (globalThis as { fetch?: typeof fetch }).fetch;
if (!resolvedFetch) {
throw new Error('Global fetch API is not available. Please use Node.js 18+.');
}
this._fetcher = resolvedFetch;
if (configuration.accessToken) {
// Use saved token
this._accessToken = configuration.accessToken;
}
}
/**
* Apply authentication settings to header and query params.
*/
public async applyToRequestAsync(requestOptions: {
headers?: Record<string, string>;
qs?: Record<string, string>;
}): Promise<void> {
if (this._accessToken == null) {
this._accessToken = await this.requestToken();
}
if (requestOptions && requestOptions.headers) {
requestOptions.headers.Authorization = 'Bearer ' + this._accessToken;
}
return Promise.resolve();
}
private async requestToken(): Promise<string> {
if (!this._configuration.clientId || !this._configuration.clientSecret) {
throw new Error("Required 'clientId' or 'clientSecret' not specified in configuration.");
}
const requestBody = new URLSearchParams({
grant_type: 'client_credentials',
client_id: this._configuration.clientId,
client_secret: this._configuration.clientSecret,
}).toString();
let response: Response;
try {
response = await this._fetcher(this._configuration.tokenUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: requestBody,
});
} catch (error) {
throw {
response: null,
error: this.normalizeFetchError(error),
errorResponse: null,
} as AuthRejectType;
}
const responseBody = await response.text();
const responseInfo: AuthResponse = {
statusCode: response.status,
statusMessage: response.statusText,
headers: this.toHeaderDict(response.headers),
body: responseBody,
};
if (!response.ok) {
const rejectObject: AuthRejectType = {
response: responseInfo,
error: new Error(
`Error on '${this._configuration.tokenUrl}': ${response.status} ${response.statusText}`
),
errorResponse: null,
};
let errorResponse = null;
try {
errorResponse = JSON.parse(responseBody) as ApiErrorResponse;
} catch (parseError) {}
if (errorResponse) {
rejectObject.errorResponse = errorResponse;
} else {
rejectObject.error.message += `. ${responseBody}`;
}
throw rejectObject;
}
const parsed = JSON.parse(responseBody);
return parsed.access_token;
}
private toHeaderDict(headers: Headers): NodeJS.Dict<string | string[]> {
const normalizedHeaders: NodeJS.Dict<string | string[]> = {};
headers.forEach((value, key) => {
const existing = normalizedHeaders[key];
if (existing === undefined) {
normalizedHeaders[key] = value;
return;
}
if (Array.isArray(existing)) {
existing.push(value);
normalizedHeaders[key] = existing;
return;
}
normalizedHeaders[key] = [existing, value];
});
return normalizedHeaders;
}
private normalizeFetchError(error: unknown): Error {
if (error instanceof Error) {
const mutableError = error as Error & { code?: string; cause?: unknown; name: string };
let normalizedCode = mutableError.code;
if (!normalizedCode) {
const cause = mutableError.cause;
if (cause && typeof cause === 'object' && 'code' in (cause as { code?: string })) {
const code = (cause as { code?: string }).code;
if (code) {
normalizedCode = String(code);
}
}
}
if (!normalizedCode) {
normalizedCode = mutableError.name || 'FETCH_ERROR';
}
try {
if (!mutableError.code) {
mutableError.code = normalizedCode;
}
} catch (assignError) {}
if (mutableError.code) {
return mutableError;
}
const wrapped = new Error(mutableError.message);
wrapped.name = mutableError.name;
(wrapped as { code?: string }).code = normalizedCode;
return wrapped;
}
const wrapped = new Error(String(error));
(wrapped as { code?: string }).code = 'FETCH_ERROR';
return wrapped;
}
}