forked from vsuaste/server-graphql-sequelize
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
290 lines (262 loc) · 10.5 KB
/
Copy pathserver.js
File metadata and controls
290 lines (262 loc) · 10.5 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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
var express = require("express");
var path = require("path");
var { createHandler } = require("graphql-http/lib/use/express");
const GraphiQL = require("zendro-graphiql");
const { authRouter, attachAuthFromSession } = require("./utils/auth");
const bodyParser = require("body-parser");
const globals = require("./config/globals");
const execute = require("graphql/execution/execute");
const getRoles = require("./utils/roles");
const helper = require("./utils/helper");
const nodejq = require("node-jq");
const { JSONPath } = require("jsonpath-plus");
const errors = require("./utils/errors");
const { graphql, GraphQLError } = require("graphql");
const models = require("./models/index.js");
const adapters = require("./models/adapters/index.js");
const { initializeStorageHandlers } = require("./utils/helper.js");
const { BenignErrorArray } = require("./utils/errors");
var acl = null;
let resolvers = require("./resolvers/index");
var cors = require("cors");
const helpObj = {
oauth2_service_url: globals.OAUTH2_TOKEN_URI,
client_id: "zendro_graphql-server",
grant_type: "password",
authenticate_curl_template: `curl -X POST --url ${globals.OAUTH2_TOKEN_URI} -d 'Content-Type: application/x-www-form-urlencoded' -d grant_type=password -d client_id=zendro_graphql-server -d username=<username> -d password=<password>`,
execute_graphql_query_curl_template: `curl --url <graphql-server>/graphql -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer <access_token>' -d '{"query": "{ ...<your query> }" }'`,
execute_meta_query_curl_template: `curl --url <graphql-server>/graphql -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer <access_token>' -H 'jq: <expr>' -d '{"query": "{ ... <your query>}" }'`,
info: "1. authenticate with OAuth using e.g authenticate_curl_template to get an access_token, 2. query away including the access tokens in the request header. - Note the curl examples can be translated to any programming language. Just send the respective HTTP Requests.",
};
/* Server */
const APP_PORT = globals.PORT;
const app = express();
let benign_errors_arr = new BenignErrorArray();
let errors_sink = [];
let errors_collector = (err) => {
errors_sink.push(err);
};
benign_errors_arr.on("push", errors_collector);
let benign_errors_arr_meta = new BenignErrorArray();
let errors_sink_meta = [];
let errors_collector_meta = (err) => {
errors_sink_meta.push(err);
};
benign_errors_arr_meta.on("push", errors_collector_meta);
app.use((req, res, next) => {
// Website you wish to allow to connect
if (globals.REQUIRE_SIGN_IN) {
res.setHeader("Access-Control-Allow-Origin", globals.ALLOW_ORIGIN);
}
next();
});
/* Temporary solution: acl rules set */
if (process.argv.length > 2 && process.argv[2] == "acl") {
let node_acl = require("acl2");
let { aclRules } = require("./acl_rules");
acl = new node_acl(new node_acl.memoryBackend());
/* set authorization rules from file acl_rules.js */
acl.allow(aclRules);
console.log("Authorization rules set!");
} else {
console.log(
"Server started without Authorization-Check. Start with command " +
"line argument 'acl', if Rule Based Authorization is wanted."
);
}
/* Schema */
console.log("Merging Schema");
let Schema = helper.mergeSchemaSetScalarTypes(
path.join(__dirname, "./schemas")
);
/* Parse urlencoded bodies and JSON by bodyParser middlewares*/
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: globals.POST_REQUEST_MAX_BODY_SIZE }));
app.use(express.json());
/** return roles from the token as json object */
app.post("/getRolesForOAuth2Token", (req, res) => {
const token = req.body.token;
const roles = getRoles(token);
res.json({ token: token, roles: roles });
});
app.get("/help", (req, res) => {
res.json(helpObj);
});
/* Serve the built GraphiQL SPA (see zendro-graphiql/, run `npm run build:graphiql`) -
zendro-graphiql only ever needs to know whether to show the auth button/
filter panel, nothing more; it holds no credentials and runs no auth
logic of its own. */
const graphiqlOptions = {
features: {
auth: globals.AUTH_ENABLED,
filter: globals.GRAPHIQL_FILTER_ENABLED,
},
};
app.use("/graphiql", GraphiQL(graphiqlOptions));
/* The Zendro auth backend (login/callback/session/logout) - implemented
directly in this server (see utils/auth/), not by an imported library:
this is the only service that ever runs it. A fixed, top-level path,
independent of wherever /graphiql itself is mounted. */
const authConfig = {
enabled: globals.AUTH_ENABLED,
clientId: globals.OAUTH2_GRAPHIQL_CLIENT_ID,
clientSecret: globals.OAUTH2_GRAPHIQL_CLIENT_SECRET,
issuerUri: globals.OAUTH2_GRAPHIQL_ISSUER_URI,
issuerInternalUri: globals.OAUTH2_GRAPHIQL_ISSUER_INTERNAL_URI,
redirectUri: globals.AUTH_REDIRECT_URI[0],
// Lets a trusted external GraphiQL deployment (e.g. graphiql-auth,
// proxying /auth/* here rather than holding its own Keycloak
// credentials) run login/logout on behalf of its own origin. Reuses the
// same patterns already registered on the Keycloak client, rather than a
// second, independently-maintained list.
allowedRedirectUris: globals.AUTH_REDIRECT_URI,
sessionSecret: globals.SESSION_SECRET,
// A direct, non-proxied login through this server's own /auth should
// still land back on its own GraphiQL editor.
postLoginRedirectTo: "/graphiql",
};
app.use("/auth", authRouter(authConfig));
/* A logged-in session transparently authenticates these routes too,
without overriding an explicit Authorization header. */
const attachGraphiqlSession = attachAuthFromSession(authConfig);
/*request is passed as context by default */
app.all(
"/graphql",
cors(),
attachGraphiqlSession,
createHandler({
schema: Schema,
rootValue: resolvers,
context: (req) => ({
request: req.raw,
acl: acl,
benignErrors: benign_errors_arr,
errors_sink: errors_sink,
recordsLimit: globals.LIMIT_RECORDS,
}),
execute: async (args) => {
const result = await execute.execute(args);
// Resolvers report non-fatal "benign" errors (e.g. association hints,
// record-limit warnings) via context.benignErrors.push(), which lands
// here through errors_sink - graphql-http otherwise has no result
// returned alongside a successful `data` the way /meta_query's own
// handler already does (see its errors_sink merge below). Some
// pushed entries (e.g. handleErrorsInGraphQlResponse relaying a
// remote server's whole error array) are themselves arrays, so this
// concats per-item rather than the whole errors_sink at once - a
// single concat only flattens one level and leaves those nested.
if (errors_sink.length > 0) {
for (let err of errors_sink) {
result.errors = result.errors
? result.errors.concat(err)
: [].concat(err);
}
errors_sink = [];
}
return result;
},
formatError: function (error) {
errors.customErrorLog(error); // Will log the error either compact (defualt) or verbose dependent on the env variable "ERROR_LOG"
let extensions = errors.formatGraphQLErrorExtensions(error);
errors_sink = [];
return {
message: error.message,
locations: error.locations ? error.locations : "",
// Either use the extensions of a remote error, or
// the local originalError.errors generated by for example validation Errors (AJV):
extensions: extensions,
path: error.path,
};
},
})
);
let metaQueryCorsOptions = {
allowedHeaders: ["Content-Type", "Authorization", "jq", "jsonPath"],
};
app.options("/meta_query", cors(metaQueryCorsOptions));
app.post("/meta_query", cors(), attachGraphiqlSession, async (req, res, next) => {
try {
let context = {
request: req,
acl: acl,
benignErrors: benign_errors_arr_meta,
recordsLimit: globals.LIMIT_RECORDS,
};
if (req != null) {
const query = req.body.query;
const jq = req.headers.jq;
const jsonPath = req.headers.jsonpath;
const variables = req.body.variables;
helper.eitherJqOrJsonpath(jq, jsonPath);
// graphql-js v16's graphql() takes a single GraphQLArgs object, not
// positional args - the old positional call silently passed `Schema`
// as the whole args object, so `args.schema` (and everything else)
// came out undefined.
const graphQlResponse = await graphql({
schema: Schema,
source: query,
rootValue: resolvers,
contextValue: context,
variableValues: variables,
});
let output = graphQlResponse.data;
const resolversHaveData = output
? Object.values(output).some((val) => val)
: null;
if (resolversHaveData) {
if (helper.isNotUndefinedAndNotNull(jq)) {
// jq
output = await nodejq.run(jq, graphQlResponse.data, {
input: "json",
output: "json",
});
} else {
// JSONPath
output = JSONPath({
path: jsonPath,
json: graphQlResponse.data,
wrap: false,
});
}
}
if (errors_sink_meta.length > 0) {
for (let err of errors_sink_meta) {
graphQlResponse.errors = graphQlResponse.errors
? graphQlResponse.errors.concat(err)
: [err];
}
}
errors_sink_meta = [];
res.json({ data: output, errors: graphQlResponse.errors });
next();
}
} catch (error) {
// error isn't guaranteed to be a GraphQLError (e.g. eitherJqOrJsonpath's
// validation, or a jq/JSONPath execution failure both throw plain
// Errors) - graphql's own formatError() assumes a GraphQLError and
// throws (no .toJSON()) on anything else, so normalize first.
const formatted = error instanceof GraphQLError ? error : new GraphQLError(error.message);
res.json({ data: null, errors: [formatted] });
}
});
/**
* uncaughtException handler needed to prevent node from crashing upon receiving a malformed jq filter.
*/
process.on("uncaughtException", (err) => {
console.log("!!uncaughtException:", err);
});
// Error handling
app.use(function (err, req, res, next) {
if (err.name === "UnauthorizedError") {
// Send the error rather than to show it on the console
res.status(401).send(err);
} else {
next(err);
}
});
var server = app.listen(APP_PORT, async () => {
await initializeStorageHandlers(models);
await initializeStorageHandlers(adapters, "adapter");
console.log(`App listening on port ${APP_PORT}`);
});
module.exports = server;