forked from resource-watch/resource-watch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
194 lines (162 loc) · 5.51 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
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
require('dotenv').load();
const express = require('express');
const next = require('next');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const basicAuth = require('basic-auth');
const serveStatic = require('serve-static');
const redis = require('redis');
const RedisStore = require('connect-redis')(session);
const { parse } = require('url');
const path = require('path');
const routes = require('./routes');
const auth = require('./auth');
const port = process.env.PORT || 3000;
const prod = process.env.RW_NODE_ENV === 'production';
// Next app creation
const app = next({ dev: !prod });
const handle = routes.getRequestHandler(app, ({ req, res, route, query }) => {
app.render(req, res, route.page, query);
});
// Express app creation
const server = express();
function checkBasicAuth(credentials) {
return function authMiddleware(req, res, nextAction) {
if (!/(AddSearchBot)|(HeadlessChrome)/.test(req.headers['user-agent'])) {
const user = basicAuth(req);
let authorized = false;
if (user && (user.name === credentials.name && user.pass === credentials.pass)) {
authorized = true;
}
if (!authorized) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.sendStatus(401);
}
}
return nextAction();
};
}
function isAuthenticated(req, res, nextAction) {
// Saving referrer of user
if (req.session) req.session.referrer = req.url;
if (req.isAuthenticated()) return nextAction();
return res.redirect('/sign-in');
}
function isAdmin(req, res, nextAction) {
if (req.user.role === 'ADMIN') return nextAction();
// if the user has not admin role, it will be redirect to the sign-in/register page
return res.redirect('/sign-in');
}
// Configuring session and cookie options
const sessionOptions = {
secret: process.env.SECRET || 'keyboard cat',
resave: false,
saveUninitialized: true
};
if (prod) {
const redisClient = redis.createClient(process.env.REDIS_URL);
sessionOptions.store = new RedisStore({
client: redisClient,
logErrors: true,
prefix: 'resourcewatch_sess_'
});
}
// Using basic auth in prod mode
const { RW_USERNAME, RW_PASSWORD } = process.env;
if (prod && (RW_USERNAME && RW_PASSWORD)) {
server.use(
checkBasicAuth({
name: RW_USERNAME,
pass: RW_PASSWORD
})
);
}
// configure Express
server.use(cookieParser());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
server.use(session(sessionOptions));
server.use(serveStatic(path.join(__dirname, 'static')));
// Middleware check: Make sure that we trigger auth if a token is passed to RW
server.use((req, res, nextAction) => {
if (req.query && req.query.token && !/auth/.test(req.url)) {
return res.redirect(`/auth?token=${req.query.token}`);
}
return nextAction();
});
// Authentication
auth.initialize(server);
// Initializing next app before express server
app.prepare().then(() => {
// Configuring next routes with express
const handleUrl = (req, res) => {
const parsedUrl = parse(req.url, true);
return handle(req, res, parsedUrl);
};
// Redirecting data to data/explore
server.get('/data', (req, res) => res.redirect('/data/explore'));
// Authentication
server.get(
'/auth',
auth.authenticate({ failureRedirect: '/sign-in' }),
(req, res) => {
if (req.user.role === 'ADMIN' && /admin/.test(req.session.referrer)) return res.redirect('/admin');
const authRedirect = req.cookies.authUrl || '/myrw/widgets/my_widgets';
if (req.cookies.authUrl) {
res.clearCookie('authUrl');
}
return res.redirect(authRedirect);
}
);
// Authenticate specific service, and set authUrl cookie so we remember where we where
server.get('/auth/:service', (req, res) => {
const { service } = req.params;
// Returning user data
if (service === 'user') return res.json(req.user || {});
if (!/facebook|google|twitter/.test(service)) {
return res.redirect('/sign-in');
}
if (req.cookies.authUrl) {
res.clearCookie('authUrl');
}
// save the current url for redirect if successfull, set it to expire in 5 min
res.cookie('authUrl', req.headers.referer, { maxAge: 3e5, httpOnly: true });
return res.redirect(
`${process.env.CONTROL_TOWER_URL}/auth/${service}?callbackUrl=${
process.env.CALLBACK_URL
}&applications=rw&token=true&origin=rw`
);
});
// if the user is already logged-in, redirect it to /myrw
// if it tries to go to sign-in page
server.get('/sign-in', (req, res, nextAction) => {
if (req.isAuthenticated()) res.redirect('/myrw');
return nextAction();
});
server.get('/login', auth.login);
server.get('/logout', (req, res) => {
req.session.destroy();
req.logout();
res.redirect('back');
});
// authenticated routes
server.get('/myrw', isAuthenticated, (req, res) => {
res.redirect('/myrw/widgets/my_widgets');
});
server.get('/myrw-detail*?', isAuthenticated, handleUrl); // TODO: review these routes
server.get('/myrw*?', isAuthenticated, handleUrl);
server.get('/admin*?', isAuthenticated, isAdmin, handleUrl);
// local sign-in
server.post('/local-sign-in', auth.signin);
// updates user data
server.post('/update-user', auth.updateUser);
server.use(handle);
server.listen(port, (err) => {
if (err) throw err;
console.info(
`> Ready on http://localhost:${port} [${process.env.RW_NODE_ENV ||
'development'}]`
);
});
});