forked from heusalagroup/fi.hg.backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJwtEncodeServiceImpl.ts
77 lines (66 loc) · 2.3 KB
/
JwtEncodeServiceImpl.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
// Copyright (c) 2021-2023. Heusala Group Oy <info@heusalagroup.fi>. All rights reserved.
import { Algorithm, sign as jwsSign, verify as jwsVerify } from "jws";
import { JwtEngine } from "../core/jwt/JwtEngine";
import { ReadonlyJsonObject } from "../core/Json";
import { LogService } from "../core/LogService";
import { LogLevel } from "../core/types/LogLevel";
import { JwtEncodeService } from "../core/jwt/JwtEncodeService";
const LOG = LogService.createLogger('JwtServiceImpl');
/**
* Jwt service implemented using "jws" NPM module.
*/
export class JwtEncodeServiceImpl implements JwtEncodeService {
public static setLogLevel (level: LogLevel) {
LOG.setLogLevel(level);
}
private _defaultAlgorithm: string;
protected constructor (
defaultAlgorithm: string = 'HS256'
) {
this._defaultAlgorithm = defaultAlgorithm;
}
public static create (
defaultAlgorithm: string = 'HS256'
) {
return new JwtEncodeServiceImpl(defaultAlgorithm);
}
public getDefaultAlgorithm (): string {
return this._defaultAlgorithm;
}
public setDefaultAlgorithm (value: string) {
this._defaultAlgorithm = value;
}
/**
* Creates a jwt engine which hides secret
*
* @param secret
* @param defaultAlgorithm
*/
public createJwtEngine (
secret: string,
defaultAlgorithm ?: string
): JwtEngine {
let _defaultAlgorithm: string | undefined = defaultAlgorithm;
return {
getDefaultAlgorithm: (): string => _defaultAlgorithm ?? this.getDefaultAlgorithm(),
setDefaultAlgorithm: (value: string): void => {
_defaultAlgorithm = value;
},
sign: (
payload: ReadonlyJsonObject,
alg?: string
): string =>
jwsSign(
{
header: {alg: (alg ?? this.getDefaultAlgorithm()) as unknown as Algorithm},
payload: payload,
secret: secret
}
),
verify: (
token: string,
alg?: string
): boolean => jwsVerify(token, (alg ?? _defaultAlgorithm ?? this.getDefaultAlgorithm()) as unknown as Algorithm, secret)
};
}
}