This repository has been archived by the owner on Mar 9, 2018. It is now read-only.
/
index.js
108 lines (80 loc) · 2.53 KB
/
index.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
'use strict';
const React = require('react');
const ReactDomServer = require('react-dom/server');
const ReactHelmet = require('react-helmet');
const ReactRouter = require('react-router-dom');
const internals = {};
const StaticRouter = ReactRouter.StaticRouter;
internals.routeHandler = function (request, reply) {
const routerState = {};
const routerProps = {
location: request.url.path,
context: routerState
};
const AppUniversal = require('../../../client/pages/main/app-universal.jsx');
const AppEl = React.createElement(AppUniversal);
const App = React.createElement(StaticRouter, routerProps, AppEl);
const markup = ReactDomServer.renderToString(App);
const helmet = ReactHelmet.Helmet.renderStatic(); // leaks if not called after render
if (routerState.url) {
return reply().redirect(routerState.url).code(routerState.code);
}
const response = reply.view('main/index', {
helmet,
markup,
state: request.app.state
});
if (routerState.code) {
response.code(routerState.code);
}
if (request.app.headers) {
Object.keys(request.app.headers).forEach((key) => {
response.header(key, request.app.headers[key]);
});
}
};
internals.applyRoutes = function (server, next) {
server.route({
method: 'GET',
path: '/{glob*}',
handler: internals.routeHandler
});
server.route({
method: 'GET',
path: '/login/{glob*}',
config: {
auth: {
mode: 'try',
strategy: 'session'
},
plugins: {
'hapi-auth-cookie': {
redirectTo: false
}
}
},
handler: function (request, reply) {
if (request.params.glob !== 'logout' &&
request.auth.isAuthenticated) {
if (request.auth.credentials.user.roles.admin) {
return reply.redirect('/admin');
}
return reply.redirect('/account');
}
if (!request.auth.isAuthenticated) {
request.app.headers = {
'x-auth-required': true
};
}
internals.routeHandler(request, reply);
}
});
next();
};
exports.register = function (server, options, next) {
server.dependency(['auth', 'hapi-mongo-models'], internals.applyRoutes);
next();
};
exports.register.attributes = {
name: 'web/main'
};