1 | import { createServer } from 'http';
|
2 | import { execute, subscribe } from 'graphql';
|
3 | import { graphqlExpress, graphiqlExpress } from 'graphql-server-express';
|
4 | import { SubscriptionServer } from 'subscriptions-transport-ws';
|
5 | import bodyParser from 'body-parser';
|
6 | import express from 'express';
|
7 | import fs from 'fs';
|
8 | import jwt from 'jsonwebtoken';
|
9 |
|
10 | import schema from './schema';
|
11 | import loaders from './Loaders';
|
12 | import userMapper from './Mapper/User';
|
13 |
|
14 | const app = express();
|
15 | const PORT = 3000;
|
16 | const cert = process.env.NODE_ENV === 'dev'
|
17 | ? 'hive'
|
18 | : fs.readFileSync('/etc/letsencrypt/production/certs/madbean.ovh/fullchain.pem');
|
19 |
|
20 | app.use(bodyParser.json());
|
21 |
|
22 | app.use((req, res, next) => {
|
23 | if (!req.headers.authorization) {
|
24 | console.log('head next');
|
25 | next();
|
26 | } else {
|
27 | const bearer = req.headers.authorization;
|
28 |
|
29 | const token = bearer.replace('Bearer ', '');
|
30 | console.log('token', token);
|
31 | jwt.verify(token, cert, { algorithms: ['RS256'] }, (err, decoded) => {
|
32 | console.log('decoded', decoded);
|
33 | if (!decoded) {
|
34 | console.log('next');
|
35 | next();
|
36 | } else {
|
37 | const { data } = decoded;
|
38 | if (data && data.userID && data.userID !== '') {
|
39 |
|
40 |
|
41 | console.log('data', data);
|
42 |
|
43 | console.log('then next');
|
44 | next();
|
45 | }
|
46 | }
|
47 | });
|
48 | }
|
49 | });
|
50 |
|
51 | app.use('/graphql', graphqlExpress((req) => {
|
52 | console.log('req.user', req.user);
|
53 | return {
|
54 | context: {
|
55 | loaders,
|
56 | auth: {
|
57 | isAuthenticated: !!req.user,
|
58 | scope: req.user && req.user.scope
|
59 | ? req.user.scope
|
60 | : null,
|
61 | },
|
62 | },
|
63 | schema,
|
64 | tracing: true,
|
65 | cacheControl: true,
|
66 | };
|
67 | }));
|
68 |
|
69 | app.use('/graphiql', graphiqlExpress({
|
70 | endpointURL: '/graphql',
|
71 | subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions`,
|
72 | }));
|
73 |
|
74 | const server = createServer(app);
|
75 |
|
76 | server.listen(PORT, () => {
|
77 | new SubscriptionServer({
|
78 | execute,
|
79 | subscribe,
|
80 | schema,
|
81 | onConnect: () => console.log('new client connected'),
|
82 | }, {
|
83 | server,
|
84 | path: '/subscriptions',
|
85 | });
|
86 | });
|
87 |
|
88 | console.log(`Middle running at http://localhost:${PORT}`);
|