This repository has been archived by the owner on Mar 19, 2024. It is now read-only.
forked from TrueLayer/truelayer-client-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthAPIClient.ts
197 lines (179 loc) · 6.09 KB
/
AuthAPIClient.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
import { ApiError } from "./APIError";
import { Constants } from "./Constants";
import { IAuthResponse } from "./interfaces/auth/IAuthResponse";
import { IOptions } from "./interfaces/auth/IOptions";
import { IProviderInfo } from './interfaces/auth/IProviderInfo';
import { ITokenResponse } from "./interfaces/auth/ITokenResponse";
import * as request from "request-promise";
/**
* Class responsible for performing authentication with TrueLayer
*
* @export
* @class AuthAPIClient
*/
export class AuthAPIClient {
private readonly options: IOptions;
/**
* Creates an instance of AuthAPIClient - If no constructor options are passed then look for environment variables by default.
*
* @param {IOptions} options
*/
constructor(options?: IOptions) {
if (options) {
this.options = options;
} else if (process.env.CLIENT_ID && process.env.CLIENT_SECRET) {
this.options = {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET
};
} else {
throw new Error("Need to pass client_id and client_secret or set as environment variables");
}
}
/**
* Builds a correctly formatted authentication url
*
* @param {string} redirectURI
* @param {string[]} scope
* @param {string} nonce
* @param {string} [state]
* @param {string} [responseMode]
* @param {boolean} [enableMock]
* @returns {string}
*/
public getAuthUrl(redirectURI: string,
scope: string[],
nonce: string,
responseMode?: string,
state?: string,
enableMock?: boolean): string {
for (const grant of scope) {
if (!AuthAPIClient.isValidScope(grant)) {
throw new Error(`Provided scope is not valid: ${grant}`);
}
}
const concatScope: string = scope.join(" ");
let authUrl: string =
`${Constants.AUTH_URL}/?` +
`response_type=code&` +
`client_id=${this.options.client_id}&` +
`redirect_uri=${redirectURI}&` +
`scope=${concatScope}&` +
`nonce=${nonce}`;
if (responseMode) {
authUrl += `&response_mode=${responseMode}`;
}
if (state) {
authUrl += `&state=${state}`;
}
if (enableMock) {
authUrl += `&enable_mock=true`;
}
return encodeURI(authUrl);
}
/**
* Validates that a given string is a correct scope literal
*
* @private
* @param {string} grant
* @returns {boolean}
*/
private static isValidScope(grant: string): boolean {
switch (grant) {
case "offline_access":
case "info":
case "accounts":
case "transactions":
case "balance":
case "cards":
return true;
default:
return false;
}
}
/**
* Exchanges an auth code for an access token
*
* @param {string} redirectURI
* @param {string} code
* @returns {Promise<ITokenResponse>}
*/
public async exchangeCodeForToken(redirectURI: string, code: string): Promise<ITokenResponse> {
const requestOptions: request.Options = {
uri: `${Constants.AUTH_URL}/connect/token`,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
form: {
grant_type: "authorization_code",
client_id: this.options.client_id,
client_secret: this.options.client_secret,
redirect_uri: redirectURI,
code
}
};
try {
const response: string = await request.post(requestOptions);
const parsedResponse: IAuthResponse = JSON.parse(response);
return {
access_token: parsedResponse.access_token,
refresh_token: parsedResponse.refresh_token,
expires_in: parsedResponse.expires_in
};
} catch (error) {
throw new ApiError(error);
}
}
/**
* Exchanges a refresh token for a fresh access token
*
* @param {string} refreshToken
* @returns {Promise<ITokenResponse>}
*/
public async refreshAccessToken(refreshToken: string): Promise<ITokenResponse> {
const requestOptions: request.Options = {
uri: `${Constants.AUTH_URL}/connect/token`,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
form: {
grant_type: "refresh_token",
client_id: this.options.client_id,
client_secret: this.options.client_secret,
refresh_token: refreshToken
}
};
try {
const response: string = await request(requestOptions);
const parsedResponse: IAuthResponse = JSON.parse(response);
return {
access_token: parsedResponse.access_token,
refresh_token: parsedResponse.refresh_token,
expires_in: parsedResponse.expires_in
};
} catch (error) {
throw new ApiError(error);
}
}
/**
* Gets info about available providers
* Docs: https://docs.truelayer.com/#list-of-supported-providers
*
* @param {string} [type] when provided, returns only providers of the given type
*/
public static async getProviderInfos(
type?: "credentialssharing" | "oauth" | "oauth/openbanking",
): Promise<IProviderInfo[]> {
const requestOptions: request.Options = {
uri: `${Constants.AUTH_URL}/api/providers/${type || ""}`,
}
try {
const response: string = await request.get(requestOptions);
const parsedResponse: IProviderInfo[] = JSON.parse(response);
return parsedResponse;
} catch (error) {
throw new ApiError(error);
}
}
}