/
utils.ts
212 lines (173 loc) · 6.06 KB
/
utils.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
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import { readFile } from 'fs';
import { Request, Response } from 'express';
import { promisify } from 'util';
import {
AuthorizationCodeGrantConfig,
Logger,
CredentialsDirConfig,
CredentialsClientConfig,
CredentialsUserConfig,
CredentialsUserClientConfig,
OAuthConfig,
OAuthGrantType,
RefreshGrantConfig,
Token
} from './types';
const fsReadFile = promisify(readFile);
const AUTHORIZATION_BEARER_PREFIX = 'Bearer';
const AUTHORIZATION_BASIC_PREFIX = 'Basic';
/**
* Returns a promise containing the file content as json object.
*
* @param filePath
* @param fileName
* @returns {Promise<any>}
*/
const getFileDataAsObject = (filePath: string, fileName: string): Promise<any> => {
if (filePath.substr(-1) !== '/') { // substr operates with the length of the string
filePath += '/';
}
const promise = fsReadFile(filePath + fileName, 'utf-8')
.then(JSON.parse);
return promise;
};
/**
* Returns the value of a specified header field from a request
*
* @param req
* @param field The name of the field to return
* @returns {string} The value of the header field
*/
const getHeaderValue = (req: Request, fieldName: string): string | undefined => {
const headerValue = req && req.headers[fieldName];
const normalizedHeaderValue =
Array.isArray(headerValue) ?
headerValue.join(' ') :
headerValue;
return normalizedHeaderValue;
};
const btoa = (input: string) => Buffer.from(input, 'binary').toString('base64');
/**
* Returns a basic authentication header value with the given credentials
*
* @param clientId
* @param clientSecret
* @returns {string}
*/
const getBasicAuthHeaderValue = (clientId: string, clientSecret: string): string => {
return AUTHORIZATION_BASIC_PREFIX + ' ' + btoa(clientId + ':' + clientSecret);
};
/**
* Extracts and returns an access_token from an authorization header
*
* @param authHeader
* @returns {any}
*/
const extractAccessToken = (authHeader: string): string | undefined => {
const parts = authHeader.split(' ');
// if type is bearer
if (parts[0] === AUTHORIZATION_BEARER_PREFIX && parts.length === 2) {
return parts[1];
} else {
return undefined;
}
};
/**
* Attach scopes on the request object.
* The `requireScopesMiddleware` relies on this information attribute.
*
* ⚠️ This function mutates req.
*
* @param req
* @returns {function(any): undefined}
*/
const setTokeninfo = (req: Request): (data: Token) => void => {
return (data: Token) => {
const tokeninfo = {
...data,
access_token: undefined
};
// Avoid leaking of sensitive information
delete tokeninfo.access_token;
Object.assign(req, {
$$tokeninfo: tokeninfo
});
};
};
/**
* Reject a request with the given status code.
*
* @param res
* @param status
*/
type rejectRequest = (res: Response, logger: Logger, status: number) => void;
// eslint-disable-next-line @typescript-eslint/no-redeclare -- intentionally naming the variable the same as the type
const rejectRequest: rejectRequest = (res, logger, status) => {
logger.info(`Request will be rejected with status ${status}`);
res.sendStatus(status);
};
const isCredentialsDirConfig = (options: Record<string | number | symbol, unknown>): options is CredentialsDirConfig =>
options.credentialsDir !== undefined;
const isCredentialsClientConfig =
(options: Record<string | number | symbol, unknown>): options is CredentialsClientConfig =>
options.clientId !== undefined && options.clientSecret !== undefined;
const isCredentialsUserConfig =
(options: Record<string | number | symbol, unknown>): options is CredentialsUserConfig =>
options.applicationUsername !== undefined && options.applicationPassword !== undefined;
const isPasswordGrantNoCredentialsDir =
(options: Record<string | number | symbol, unknown>): options is CredentialsUserClientConfig =>
options.grantType === OAuthGrantType.PASSWORD_CREDENTIALS_GRANT &&
isCredentialsUserConfig(options) && isCredentialsClientConfig(options);
const checkCredentialsSource = (options: OAuthConfig) =>
isCredentialsDirConfig(options) || isCredentialsClientConfig(options) || isPasswordGrantNoCredentialsDir(options);
const extractUserCredentials = (options: CredentialsUserConfig | CredentialsUserClientConfig): CredentialsUserConfig =>
({ applicationPassword: options.applicationPassword, applicationUsername: options.applicationUsername });
const extractClientCredentials =
(options: CredentialsClientConfig | CredentialsUserClientConfig): CredentialsClientConfig =>
({ clientId: options.clientId, clientSecret: options.clientSecret });
/**
* Validates options object and throws TypeError if mandatory options is not specified.
*
* @param options
*/
const validateOAuthConfig = (options: OAuthConfig): void => {
if (!checkCredentialsSource(options)) {
throw TypeError('credentials must be defined');
}
if (!options.accessTokenEndpoint) {
throw TypeError('accessTokenEndpoint must be defined');
}
if (!options.grantType) {
throw TypeError('grantType must be defined');
}
if (isAuthorizationCodeGrantConfig(options) && !options.code) {
throw TypeError('code must be defined');
}
if (isAuthorizationCodeGrantConfig(options) && !options.redirectUri) {
throw TypeError('redirectUri must be defined');
}
if (isRefreshGrantConfig(options) && !options.refreshToken) {
throw TypeError('refreshToken must be defined');
}
};
const isAuthorizationCodeGrantConfig = (config: OAuthConfig): config is AuthorizationCodeGrantConfig =>
config.grantType === OAuthGrantType.AUTHORIZATION_CODE_GRANT.valueOf();
const isRefreshGrantConfig = (config: OAuthConfig): config is RefreshGrantConfig =>
config.grantType === OAuthGrantType.REFRESH_TOKEN_GRANT.valueOf();
export {
extractAccessToken,
extractUserCredentials,
extractClientCredentials,
getBasicAuthHeaderValue,
getFileDataAsObject,
getHeaderValue,
isAuthorizationCodeGrantConfig,
isCredentialsDirConfig,
isCredentialsUserConfig,
isCredentialsClientConfig,
isRefreshGrantConfig,
isPasswordGrantNoCredentialsDir,
rejectRequest,
validateOAuthConfig,
setTokeninfo
};