1 |
|
2 |
|
3 | import { generateHeaders } from "./utils/headers";
|
4 | import { Constants, getResourceIdFromPath, ResourceType, trimSlashFromLeftAndRight, } from "./common";
|
5 |
|
6 |
|
7 |
|
8 | export async function setAuthorizationHeader(clientOptions, verb, path, resourceId, resourceType, headers) {
|
9 | if (clientOptions.permissionFeed) {
|
10 | clientOptions.resourceTokens = {};
|
11 | for (const permission of clientOptions.permissionFeed) {
|
12 | const id = getResourceIdFromPath(permission.resource);
|
13 | if (!id) {
|
14 | throw new Error(`authorization error: ${id} \
|
15 | is an invalid resourceId in permissionFeed`);
|
16 | }
|
17 | clientOptions.resourceTokens[id] = permission._token;
|
18 | }
|
19 | }
|
20 | if (clientOptions.key) {
|
21 | await setAuthorizationTokenHeaderUsingMasterKey(verb, resourceId, resourceType, headers, clientOptions.key);
|
22 | }
|
23 | else if (clientOptions.resourceTokens) {
|
24 | headers[Constants.HttpHeaders.Authorization] = encodeURIComponent(getAuthorizationTokenUsingResourceTokens(clientOptions.resourceTokens, path, resourceId));
|
25 | }
|
26 | else if (clientOptions.tokenProvider) {
|
27 | headers[Constants.HttpHeaders.Authorization] = encodeURIComponent(await clientOptions.tokenProvider({ verb, path, resourceId, resourceType, headers }));
|
28 | }
|
29 | }
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | export async function setAuthorizationTokenHeaderUsingMasterKey(verb, resourceId, resourceType, headers, masterKey) {
|
35 |
|
36 | if (resourceType === ResourceType.offer) {
|
37 | resourceId = resourceId && resourceId.toLowerCase();
|
38 | }
|
39 | headers = Object.assign(headers, await generateHeaders(masterKey, verb, resourceType, resourceId));
|
40 | }
|
41 |
|
42 |
|
43 |
|
44 |
|
45 | export function getAuthorizationTokenUsingResourceTokens(resourceTokens, path, resourceId) {
|
46 | if (resourceTokens && Object.keys(resourceTokens).length > 0) {
|
47 |
|
48 |
|
49 |
|
50 | if (!path && !resourceId) {
|
51 | return resourceTokens[Object.keys(resourceTokens)[0]];
|
52 | }
|
53 |
|
54 | if (resourceId && resourceTokens[resourceId]) {
|
55 | return resourceTokens[resourceId];
|
56 | }
|
57 |
|
58 | if (!path || path.length < 4) {
|
59 |
|
60 | return null;
|
61 | }
|
62 | path = trimSlashFromLeftAndRight(path);
|
63 | const pathSegments = (path && path.split("/")) || [];
|
64 |
|
65 | if (pathSegments.length === 6) {
|
66 |
|
67 | const containerPath = pathSegments.slice(0, 4).map(decodeURIComponent).join("/");
|
68 | if (resourceTokens[containerPath]) {
|
69 | return resourceTokens[containerPath];
|
70 | }
|
71 | }
|
72 |
|
73 |
|
74 |
|
75 |
|
76 | let index = pathSegments.length % 2 === 0 ? pathSegments.length - 1 : pathSegments.length - 2;
|
77 | for (; index > 0; index -= 2) {
|
78 | const id = decodeURI(pathSegments[index]);
|
79 | if (resourceTokens[id]) {
|
80 | return resourceTokens[id];
|
81 | }
|
82 | }
|
83 | }
|
84 |
|
85 | return null;
|
86 | }
|
87 |
|
\ | No newline at end of file |