-
Notifications
You must be signed in to change notification settings - Fork 1
/
envelopPlugins.ts
149 lines (130 loc) · 3.77 KB
/
envelopPlugins.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import {PluginOrDisabledPlugin} from "@envelop/core";
import {ResolveUserFn, useGenericAuth} from "@envelop/generic-auth";
import * as jose from "jose";
type UserCourseMembership = {
courseId: string;
role: string;
}
type UserType = {
id: string;
userName: string;
firstName: string;
lastName: string;
authToken: string;
courseMemberships: UserCourseMembership[];
realmRoles: string[];
};
const JWKS = jose.createRemoteJWKSet(
new URL(
process.env.JWKS_URL ?? `http://keycloak:8080/realms/GITS/protocol/openid-connect/certs`
)
);
async function resolveUserAuthenticated(context) {
try {
// get user information from request headers
let authHeader = retrieveHeaderSafe(context, "authorization");
authHeader = authHeader.replace("Bearer ", "");
const {payload} = await jose.jwtVerify(
authHeader,
JWKS,
{}
);
// query the course service to find out which courses the user is a member of
const courseMemberships = await context.CourseService.Query._internal_noauth_courseMembershipsByUserId({
args: {
userId: payload.sub
},
selectionSet: `
{
courseId
role
course {
id
published
startDate
endDate
}
}
`
});
// check that we received a response
if (courseMemberships == null) {
console.error("Failed to retrieve user course memberships.");
return null;
}
// construct the user object we will return
const user: UserType = {
id: payload.sub,
userName: payload.preferred_username,
firstName: payload.given_name,
lastName: payload.family_name,
authToken: authHeader,
courseMemberships: courseMemberships.map((membership) => {
return {
courseId: membership.courseId,
role: membership.role,
published: membership.course.published,
startDate: membership.course.startDate,
endDate: membership.course.endDate
}
}),
realmRoles: payload.realm_access.roles
};
// add json representation of the user object to the context
// (will be injected into the request headers to the services)
context.currentUserJson = JSON.stringify(user);
return user;
} catch (e) {
console.error("Failed to validate token");
console.error(e);
return null;
}
}
function resolveUserSkipAuth(context) {
return JSON.parse(retrieveHeaderSafe(context, "currentUser"));
}
function retrieveHeadersSafe(context: any) {
let headers = context.request.headers;
if (!headers) {
headers = context.req.headers;
}
if (!headers) {
console.log("No headers found.");
throw new Error("No headers found");
}
return headers;
}
function retrieveHeaderSafe(context, header: string) {
let headers = retrieveHeadersSafe(context);
let authHeader = headers.get(header);
if (!authHeader) {
authHeader = headers.authorization;
}
if (!authHeader) {
console.log("No header '" + header + "' found.");
throw new Error("No header '" + header + "' found");
}
return authHeader;
}
/**
* Function which is called for every request to resolve the current user based on data in the request.
* @param context The GraphQL context
* @returns Object representing the current user or null if authentication failed
*/
const resolveUserFn: ResolveUserFn<UserType> = async (context) => {
if (process.env.SKIP_AUTH !== undefined && process.env.SKIP_AUTH.toLowerCase() === "true") {
return resolveUserSkipAuth(context);
} else {
return await resolveUserAuthenticated(context);
}
};
/**
* List of Envelop plugins the gateway shall use.
*/
const plugins: PluginOrDisabledPlugin = [
useGenericAuth({
resolveUserFn,
mode: "protect-all",
}),
];
export default plugins;