-
Notifications
You must be signed in to change notification settings - Fork 7
/
cacheClient.service.ts
305 lines (264 loc) · 11.4 KB
/
cacheClient.service.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import axios, { AxiosError, AxiosInstance, AxiosResponse } from "axios";
import { stringify } from "qs";
import { IRoleDefinition } from "@energyweb/iam-contracts";
import { IDIDDocument } from "@ew-did-registry/did-resolver-interface";
import { IApp, IOrganization, IRole } from "../domains/domains.types";
import { AssetHistory } from "../assets/assets.types";
import { Claim, IClaimIssuance, IClaimRejection, IClaimRequest } from "../claims/claims.types";
import { Asset } from "../assets/assets.types";
import { executionEnvironment, ExecutionEnvironment } from "../../utils/detectEnvironment";
import { SignerService } from "../signer/signer.service";
import { IPubKeyAndIdentityToken } from "../signer/signer.types";
import { cacheConfigs } from "../../config/cache.config";
import { ICacheClient } from "./ICacheClient";
import { AssetsFilter, ClaimsFilter } from "./cacheClient.types";
import { SearchType, TEST_LOGIN_NAMESPACE } from ".";
export class CacheClient implements ICacheClient {
public pubKeyAndIdentityToken: IPubKeyAndIdentityToken | undefined;
private httpClient: AxiosInstance;
private isAlreadyFetchingAccessToken = false;
private failedRequests: Array<(token?: string) => void> = [];
private authEnabled: boolean;
private isBrowser: boolean;
private refresh_token: string | undefined;
constructor(private _signerService: SignerService) {
this._signerService.onInit(this.init.bind(this));
}
async init() {
const { url, cacheServerSupportsAuth = false } = cacheConfigs()[this._signerService.chainId];
this.httpClient = axios.create({
baseURL: url,
withCredentials: true,
});
this.httpClient.interceptors.response.use((response: AxiosResponse) => {
return response;
}, this.handleUnauthorized.bind(this));
this.authEnabled = cacheServerSupportsAuth;
this.isBrowser = executionEnvironment() === ExecutionEnvironment.BROWSER;
}
isAuthEnabled() {
return this.authEnabled;
}
async handleRefreshToken() {
const { refreshToken, token } = await this.refreshToken();
this.refresh_token = refreshToken;
this.failedRequests = this.failedRequests.filter((callback) => callback(this.isBrowser ? undefined : token));
if (!this.isBrowser) {
this.httpClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
this.refresh_token = refreshToken;
}
}
addFailedRequest(callback: (token?: string) => void) {
this.failedRequests.push(callback);
}
async handleUnauthorized(error: AxiosError) {
const { config, response } = error;
const originalRequest = config;
if (
this.authEnabled &&
response &&
response.status === 401 &&
config &&
config.url?.indexOf("/login") === -1 &&
config.url?.indexOf("/refresh_token") === -1
) {
const retryOriginalRequest = new Promise((resolve) => {
this.addFailedRequest((token?: string) => {
if (token) {
originalRequest.headers.Authorization = "Bearer " + token;
}
resolve(axios(originalRequest));
});
});
if (!this.isAlreadyFetchingAccessToken) {
this.isAlreadyFetchingAccessToken = true;
await this.handleRefreshToken();
this.isAlreadyFetchingAccessToken = false;
}
return retryOriginalRequest;
}
return Promise.reject(error);
}
async login() {
await this.testLogin();
}
async getRoleDefinition(namespace: string) {
const { data } = await this.httpClient.get<IRole>(`/role/${namespace}`);
return data?.definition;
}
async getRolesDefinition(namespaces: string[]) {
const { data } = await this.httpClient.get<IRole[]>(`/role?namespaces=${namespaces.join(",")}`);
const rolesWithDefinitions = data?.map((entry) => ({ definition: entry.definition, role: entry.namespace }));
return rolesWithDefinitions.reduce((result, { role, definition }) => {
return { ...result, [role]: definition };
}, {} as Record<string, IRoleDefinition>);
}
async getOrgDefinition(namespace: string) {
const { data } = await this.httpClient.get<IOrganization>(`/org/${namespace}`);
return data?.definition;
}
async getAppDefinition(namespace: string) {
const { data } = await this.httpClient.get<IApp>(`/app/${namespace}`);
return data?.definition;
}
async getApplicationRoles(namespace: string) {
const { data } = await this.httpClient.get<IRole[]>(`/app/${namespace}/roles`);
return data;
}
async getOrganizationRoles(namespace: string) {
const { data } = await this.httpClient.get<IRole[]>(`/org/${namespace}/roles`);
return data;
}
async getOrganizationsByOwner(owner: string, withRelations = true) {
const { data } = await this.httpClient.get<IOrganization[]>(
`/org/owner/${owner}?withRelations=${withRelations}`,
);
return data;
}
async getSubOrganizationsByOrganization(namespace: string) {
const { data } = await this.httpClient.get<IOrganization[]>(`/org/${namespace}/suborgs`);
return data;
}
async getOrgHierarchy(namespace: string) {
const { data } = await this.httpClient.get<IOrganization>(`/org/${namespace}`);
return data;
}
async getNamespaceBySearchPhrase(search: string, types?: SearchType[]) {
if (types && types.length > 0) {
const { data } = await this.httpClient.get<(IOrganization | IApp | IRole)[]>(`/search/${search}`, {
params: {
types,
},
paramsSerializer: (params) => {
return stringify(params, { arrayFormat: "brackets" });
},
});
return data;
}
const { data } = await this.httpClient.get<(IOrganization | IApp | IRole)[]>(`/search/${search}`);
return data;
}
async getApplicationsByOwner(owner: string, withRelations = true) {
const { data } = await this.httpClient.get<IApp[]>(`/app/owner/${owner}?withRelations=${withRelations}`);
return data;
}
async getApplicationsByOrganization(namespace: string) {
const { data } = await this.httpClient.get<IApp[]>(`/org/${namespace}/apps`);
return data;
}
async getRolesByOwner(owner: string) {
const { data } = await this.httpClient.get<IRole[]>(`/role/owner/${owner}`);
return data;
}
async getClaimsBySubjects(subjects: string[]): Promise<Claim[]> {
const { data } = await this.httpClient.get<Claim[]>("/claim/by/subjects", {
params: { subjects: subjects.join(",") },
});
return data;
}
async getClaimsByIssuer(issuer: string, { isAccepted, namespace }: ClaimsFilter = {}) {
const { data } = await this.httpClient.get<Claim[]>(`/claim/issuer/${issuer}`, {
params: {
isAccepted,
namespace,
},
});
return data;
}
async getClaimsByRequester(requester: string, { isAccepted, namespace }: ClaimsFilter = {}) {
const { data } = await this.httpClient.get<Claim[]>(`/claim/requester/${requester}`, {
params: {
isAccepted,
namespace,
},
});
return data;
}
async getClaimsBySubject(subject: string, { isAccepted, namespace }: ClaimsFilter = {}) {
const { data } = await this.httpClient.get<Claim[]>(`/claim/subject/${subject}`, {
params: {
isAccepted,
namespace,
},
});
return data;
}
async requestClaim(requester: string, message: IClaimRequest) {
await this.httpClient.post<void>(`/claim/request/${requester}`, message);
}
async issueClaim(issuer: string, message: IClaimIssuance) {
await this.httpClient.post<void>(`/claim/issue/${issuer}`, message);
}
async rejectClaim(issuer: string, message: IClaimRejection) {
await this.httpClient.post<void>(`/claim/reject/${issuer}`, message);
}
async deleteClaim(id: string) {
await this.httpClient.delete<void>(`/claim/${id}`);
}
async getDIDsForRole(namespace: string) {
const { data } = await this.httpClient.get<string[]>(`/claim/did/${namespace}?accepted=true`);
return data;
}
async getDidDocument(did: string, includeClaims?: boolean) {
const { data } = await this.httpClient.get<IDIDDocument>(`/DID/${did}?includeClaims=${includeClaims || false}`);
return data;
}
async getAllowedRolesByIssuer(did: string) {
const { data } = await this.httpClient.get<string[]>(`/claim/issuer/roles/allowed/${did}`);
return data;
}
async addDIDToWatchList(did: string) {
await this.httpClient.post(`/DID/${did}`);
}
async getOwnedAssets(did: string) {
const { data } = await this.httpClient.get<Asset[]>(`/assets/owner/${did}`);
return data;
}
async getOfferedAssets(did: string) {
const { data } = await this.httpClient.get<Asset[]>(`/assets/offered_to/${did}`);
return data;
}
async getAssetById(id: string) {
const { data } = await this.httpClient.get<Asset>(`/assets/${id}`);
return data;
}
async getPreviouslyOwnedAssets(owner: string) {
const { data } = await this.httpClient.get<Asset[]>(`/assets/owner/history/${owner}`);
return data;
}
async getAssetHistory(id: string, { order, take, skip, type }: AssetsFilter = {}) {
const query = stringify({ order, take, skip, type }, { skipNulls: true });
const { data } = await this.httpClient.get<AssetHistory[]>(`/assets/history/${id}?${query}`);
return data;
}
private async refreshToken(): Promise<{ token: string; refreshToken: string }> {
try {
const { data } = await this.httpClient.get<{ token: string; refreshToken: string }>(
`/refresh_token${
executionEnvironment() === ExecutionEnvironment.BROWSER
? ""
: `?refresh_token=${this.refresh_token}`
}`,
);
return data;
} catch {
const pubKeyAndIdentityToken = await this._signerService.publicKeyAndIdentityToken();
const {
data: { refreshToken, token },
} = await this.httpClient.post<{ token: string; refreshToken: string }>("/login", {
identityToken: pubKeyAndIdentityToken.identityToken,
});
if (!this.isBrowser) {
this.httpClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
this.refresh_token = refreshToken;
}
this.pubKeyAndIdentityToken = pubKeyAndIdentityToken;
return { token, refreshToken };
}
}
private async testLogin(): Promise<void> {
// Simple test to check if logged in or no. TODO: have dedicated endpoint on the cache-server
// If receive unauthorized response, expect that refreshToken() will be called
await this.getRoleDefinition(TEST_LOGIN_NAMESPACE);
}
}