-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcreate-context.ts
61 lines (53 loc) · 1.9 KB
/
create-context.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
// Copyright 2021 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
import { ExpressContextFunctionArgument } from "@apollo/server/express4";
import DataLoader from "dataloader";
import Container from "typedi";
import { Users } from "../data/users.data";
import { CerbosService } from "../services/Cerbos.service";
import { ResourceCheck } from "@cerbos/core";
import logger from "../utils/logger";
import { IContext } from "./context.interface";
import { GraphQLError } from "graphql";
const log = logger("createContext");
export default async (
request: ExpressContextFunctionArgument
): Promise<IContext> => {
// Create a new request container
const requestId = Math.floor(
Math.random() * Number.MAX_SAFE_INTEGER
).toString();
const container = Container.of(requestId);
const cerbosService = Container.get(CerbosService);
// No token set access is denied
if (!request.req.headers["token"])
throw new GraphQLError("Access denied: No token provided");
// DO SOME ACTUAL AUTHENTICATION AGAINST A DB etc
const user = Users.find((u) => u.token === request.req.headers["token"]);
// User not found so denied
if (!user) throw new GraphQLError("Access denied: Token not valid");
// Set the context in the container
const context: IContext = {
req: request.req,
requestId,
user,
container: Container.of(requestId.toString()),
loaders: {
authorize: new DataLoader(async (resources: ResourceCheck[]) => {
const results = await cerbosService.cerbos.checkResources({
principal: {
id: user.id,
roles: [user.role.toString()],
attributes: JSON.parse(JSON.stringify(user)),
},
resources,
});
return resources.map((key) =>
results.findResult({ kind: key.resource.kind, id: key.resource.id })
);
}),
},
};
container.set("context", context);
return context;
};