-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
179 lines (154 loc) · 4.37 KB
/
server.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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import { Prisma, PrismaClient } from '@prisma/client';
import { ApolloServer } from 'apollo-server-express';
import {
PluginDefinition,
ApolloServerPluginDrainHttpServer,
} from 'apollo-server-core';
import { debug } from 'debug';
import * as dotenv from 'dotenv';
import * as express from 'express';
import * as http from 'http';
import * as cors from 'cors';
import * as fs from 'fs/promises'
import { schema } from './nexus/schema';
import { Issuer, errors } from 'openid-client';
import { UserInfo, loginResponse } from './serverTypes';
type TestInjections = {
insecure?: boolean;
onQuery?: (q: Prisma.QueryEvent) => void;
};
export async function makeServer(
config: BackendConfig,
{ insecure, onQuery }: TestInjections = {}
) {
const app = express();
const clientOptions: Prisma.PrismaClientOptions = {};
if (onQuery) {
if (! clientOptions.log) clientOptions.log = [];
clientOptions.log.push({ level: 'query', emit: 'event' });
}
if (debug.enabled('prisma:query')) {
if (! clientOptions.log) clientOptions.log = [];
clientOptions.log.push('query');
}
const prisma = new PrismaClient({
datasources: { db: { url: config.LHD_DB_URL } },
...clientOptions,
});
if (onQuery) {
(prisma as any).$on('query', onQuery);
}
const httpServer = http.createServer(app);
const server = new ApolloServer({
context: () => ({ prisma }),
schema,
plugins: [
onServerStop(() => prisma.$disconnect()),
ApolloServerPluginDrainHttpServer({ httpServer }),
],
});
await server.start();
app.use(express.json());
app.use(cors());
if (! insecure) {
app.use(async function (req, res, next) {
try {
var loginResponse = await isLoggedIn(req);
if (req.method === 'POST' && !isHarmless(req) && !loginResponse.loggedIn) {
res.status(loginResponse.httpCode);
res.send(loginResponse.message);
} else {
next();
}
} catch (e) {
res.status(500);
res.send(`GraphQL Error: ${e}`);
}
});
}
app.get('/graphiql', async (req, res) => {
const html = await fs.readFile('developer/graphiql.html', 'utf8')
res.send(html)
})
server.applyMiddleware({ path: '/', bodyParserConfig: false, app });
return httpServer;
}
type BackendConfig = {
LHD_DB_URL: string;
};
export function configFromDotEnv(): BackendConfig {
dotenv.config();
return process.env as BackendConfig;
}
/**
* An arbitrary stop-time callback, packaged as an ApolloServer plugin.
*/
function onServerStop(cb: () => Promise<void>): PluginDefinition {
return {
async serverWillStart() {
return {
serverWillStop: cb,
};
},
};
}
/**
* Whether a POST query is harmless.
*
* `IntrospectionQuery` GraphQL requests are presumed harmless;
* everything else returns `false`.
*/
function isHarmless(req: express.Request): boolean {
const query = (req?.body?.query || '').trim();
return query.startsWith('query IntrospectionQuery');
}
let _issuer: Issuer | undefined = undefined;
async function issuer() {
if (_issuer) return _issuer;
_issuer = await Issuer.discover(
process.env.OIDC_BASE_URL || 'http://localhost:8080/realms/LHD'
);
return _issuer;
}
async function isLoggedIn(req): Promise<loginResponse> {
async function verifyToken(access_token: string) {
const issuer_ = await issuer();
const client = new issuer_.Client({ client_id: 'LHDv3 server' });
try {
const userinfo: UserInfo = await client.userinfo(access_token);
const allowedGroups = process.env.ALLOWED_GROUPS.split(',');
console.log('Logged in', userinfo);
console.log('Allowed groups', allowedGroups);
// TODO: Some pages do not have the same access rights as others. Rewrite this to account for that.
if (userinfo.groups && userinfo.groups.some(e => allowedGroups.includes(e))) {
return {
loggedIn: true,
httpCode: 200,
message: 'Correct access rights and token are working, user logged in.',
};
}
return {
loggedIn: false,
httpCode: 403,
message: `Wrong access rights. You are required to have one of the following groups: ${allowedGroups.join(
', '
)}`,
};
} catch (e: any) {
if (e instanceof errors.OPError && e.error == 'invalid_token') {
return {
loggedIn: false,
httpCode: 401,
message: `JWT Token is invalid: ${e}`,
};
} else {
throw e;
}
}
}
const matched = req.headers.authorization?.match(/^Bearer\s(.*)$/);
if (!matched) {
return undefined;
}
return await verifyToken(matched[1]);
}