multitenancy.test.js
1.92 KB
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
const jwt = require("jsonwebtoken");
const assert = require("assert");
const koajwt = require("../lib");
const UnauthorizedError = require("../lib/errors/UnauthorizedError");
const mockContext = require("./context");
describe("multitenancy", function() {
const tenants = {
a: {
secret: "secret-a"
}
};
let ctx;
beforeEach(() => {
ctx = mockContext();
});
const secretAsync = async function(ctx, payload) {
const issuer = payload.iss;
if (tenants[issuer]) {
return tenants[issuer].secret;
}
throw new UnauthorizedError("missing_secret", {
message: "Could not find secret for issuer."
});
};
const middleware = koajwt({
secret: secretAsync
});
it("should retrieve secret using callback", async () => {
const token = jwt.sign({ iss: "a", foo: "bar" }, tenants.a.secret);
ctx.headers.authorization = "Bearer " + token;
await middleware(ctx, () => {});
assert.equal("bar", ctx.state.user.foo);
});
it("should throw if an error ocurred when retrieving the token", async () => {
const secret = "shhhhhh";
const token = jwt.sign({ iss: "inexistent", foo: "bar" }, secret);
ctx.headers.authorization = "Bearer " + token;
try {
await middleware(ctx, () => {});
} catch (err) {
assert.ok(err);
assert.equal(err.code, "missing_secret");
assert.equal(err.message, "Could not find secret for issuer.");
}
});
it("should fail if token is revoked", async () => {
const token = jwt.sign({ iss: "a", foo: "bar" }, tenants.a.secret);
ctx.headers.authorization = "Bearer " + token;
try {
await koajwt({
secret: secretAsync,
isRevoked: async function(ctx, payload) {
return true;
}
})(ctx, () => {});
} catch (err) {
assert.ok(err);
assert.equal(err.code, "revoked_token");
assert.equal(err.message, "The token has been revoked.");
}
});
});