/
server.js
124 lines (115 loc) · 4.12 KB
/
server.js
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
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import 'babel-polyfill';
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import React from 'react';
import ReactDOM from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import passport from './core/passport';
import schema from './data/schema';
import routes from './routes';
import Html from './components/Html';
import ContextHolder from './core/ContextHolder';
import assets from './assets';
import { port, auth } from './config';
const server = global.server = express();
//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
server.use(express.static(path.join(__dirname, 'public')));
server.use(cookieParser());
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());
//
// Authentication
// -----------------------------------------------------------------------------
server.use(expressJwt({
secret: auth.jwt.secret,
credentialsRequired: false,
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
getToken: req => req.cookies.id_token,
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
}));
server.use(passport.initialize());
server.get('/login/facebook',
passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false })
);
server.get('/login/facebook/return',
passport.authenticate('facebook', { failureRedirect: '/login', session: false }),
(req, res) => {
const expiresIn = 60 * 60 * 24 * 180; // 180 days
const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn });
res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true });
res.redirect('/');
}
);
//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/graphql', expressGraphQL(req => ({
schema,
graphiql: true,
rootValue: { request: req },
pretty: process.env.NODE_ENV !== 'production',
})));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
try {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (error) {
throw error;
}
if (redirectLocation) {
const redirectPath = `${redirectLocation.pathname}${redirectLocation.search}`;
res.redirect(302, redirectPath);
return;
}
let statusCode = 200;
const data = { title: '', description: '', css: '', body: '', entry: assets.main.js };
const css = [];
const context = {
insertCss: styles => css.push(styles._getCss()),
onSetTitle: value => (data.title = value),
onSetMeta: (key, value) => (data[key] = value),
onPageNotFound: () => (statusCode = 404),
};
data.body = ReactDOM.renderToString(
<ContextHolder context={context}>
<RouterContext {...renderProps} />
</ContextHolder>
);
data.css = css.join('');
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode).send(`<!doctype html>\n${html}`);
});
} catch (err) {
next(err);
}
});
//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(port, () => {
/* eslint-disable no-console */
console.log(`The server is running at http://localhost:${port}/`);
});