1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.JWTService = exports.jsonwebtoken = void 0;
|
4 | const js_lib_1 = require("@naturalcycles/js-lib");
|
5 | const jsonwebtoken = require("jsonwebtoken");
|
6 | exports.jsonwebtoken = jsonwebtoken;
|
7 | const joi_shared_schemas_1 = require("../validation/joi/joi.shared.schemas");
|
8 | const joi_validation_util_1 = require("../validation/joi/joi.validation.util");
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | class JWTService {
|
19 | constructor(cfg) {
|
20 | this.cfg = cfg;
|
21 | }
|
22 | sign(payload, schema, opt = {}) {
|
23 | (0, js_lib_1._assert)(this.cfg.privateKey, 'JWTService: privateKey is required to be able to verify, but not provided');
|
24 | if (schema) {
|
25 | (0, joi_validation_util_1.validate)(payload, schema);
|
26 | }
|
27 | return jsonwebtoken.sign(payload, this.cfg.privateKey, {
|
28 | algorithm: this.cfg.algorithm,
|
29 | noTimestamp: true,
|
30 | ...this.cfg.signOptions,
|
31 | ...opt,
|
32 | });
|
33 | }
|
34 | verify(token, schema, opt = {}) {
|
35 | (0, js_lib_1._assert)(this.cfg.publicKey, 'JWTService: publicKey is required to be able to verify, but not provided');
|
36 | try {
|
37 | const data = jsonwebtoken.verify(token, this.cfg.publicKey, {
|
38 | algorithms: [this.cfg.algorithm],
|
39 | ...this.cfg.verifyOptions,
|
40 | ...opt,
|
41 | });
|
42 | if (schema) {
|
43 | (0, joi_validation_util_1.validate)(data, schema);
|
44 | }
|
45 | return data;
|
46 | }
|
47 | catch (err) {
|
48 | if (this.cfg.errorData) {
|
49 | (0, js_lib_1._typeCast)(err);
|
50 | (0, js_lib_1._errorDataAppend)(err, {
|
51 | ...this.cfg.errorData,
|
52 | });
|
53 | }
|
54 | throw err;
|
55 | }
|
56 | }
|
57 | decode(token, schema) {
|
58 | const data = jsonwebtoken.decode(token, {
|
59 | complete: true,
|
60 | });
|
61 | (0, js_lib_1._assert)(data, 'invalid token, decoded value is null', {
|
62 | ...this.cfg.errorData,
|
63 | });
|
64 | (0, joi_validation_util_1.validate)(data.payload, schema || joi_shared_schemas_1.anyObjectSchema);
|
65 | return data;
|
66 | }
|
67 | }
|
68 | exports.JWTService = JWTService;
|