-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcontext.ts
32 lines (29 loc) · 901 Bytes
/
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
import { GraphQLError } from "graphql";
import { authorize } from "./services/Cerbos.service";
import { Users } from "./data/users.data";
import { Principal } from "@cerbos/core";
import { StandaloneServerContextFunctionArgument } from "@apollo/server/dist/esm/standalone";
import { ContextFunction } from "@apollo/server";
export interface Context {
principal: Principal;
authorizer: ReturnType<typeof authorize>;
}
export const createContext: ContextFunction<
[StandaloneServerContextFunctionArgument],
Context
> = async ({ req }) => {
const token = (req.headers.token as string) || "";
const principal = Users[token];
if (!token || !principal) {
throw new GraphQLError("User is not authenticated", {
extensions: {
code: "UNAUTHENTICATED",
http: { status: 401 },
},
});
}
return {
principal,
authorizer: authorize(principal),
};
};