This repository has been archived by the owner on Feb 10, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
AuthorizationClientService.ts
89 lines (63 loc) · 2.54 KB
/
AuthorizationClientService.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
// Copyright (c) 2020-2021 Sendanor. All rights reserved.
import { RequestClientImpl } from "./RequestClientImpl";
import { LogService } from "./LogService";
import { RequestError } from "./request/types/RequestError";
import { RequestStatus } from "./request/types/RequestStatus";
import { AuthorizationUtils } from "./AuthorizationUtils";
import { isString } from "./types/String";
const LOG = LogService.createLogger('AuthorizationClientService');
export interface AuthorizationResultDTO {
email : string;
}
export function isAuthorizationResultDTO (value : any) : value is AuthorizationResultDTO {
return (
!!value && isString(value?.email) && !!value?.email
);
}
/**
* Experimental service. Not recommended to use. May change later.
*/
export class AuthorizationClientService {
private readonly _serviceUrl : string;
public constructor(serviceUrl : string) {
this._serviceUrl = serviceUrl;
}
public async verifySessionJwt (token: string) : Promise<AuthorizationResultDTO | undefined> {
try {
const result = await RequestClientImpl.postJson(`${this._serviceUrl}/verify`, {
token
});
if (!isAuthorizationResultDTO(result)) {
LOG.debug('verifyJwt: result not AuthorizationResultDTO: ', result);
return undefined;
}
LOG.debug('verifyJwt: result: ', result);
return {
email : result.email
};
} catch (err) {
LOG.error('verifyJwt: error: ', err);
return undefined;
}
}
public static async verifySessionAuthorizationHeader (
authService : AuthorizationClientService,
header : string
) : Promise<AuthorizationResultDTO> {
const jwt : string | undefined = AuthorizationUtils.parseBearerToken(header);
if (!jwt) {
LOG.debug('verifySessionAuthorizationHeader: Unsupported header value: ', header);
throw new RequestError(RequestStatus.Forbidden, 'Forbidden');
}
LOG.debug('verifyAuthorizationHeader: jwt: ', jwt);
const result : AuthorizationResultDTO | undefined = await authService.verifySessionJwt(jwt);
if (!result) {
LOG.debug('verifyAuthorizationHeader: Jwt is not valid: ', jwt);
throw new RequestError(RequestStatus.Forbidden, 'Forbidden');
}
LOG.debug('verifyAuthorizationHeader: Jwt verified successfully: ', jwt);
return {
email: result.email
};
}
}