-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathapp.js
More file actions
233 lines (194 loc) · 6.1 KB
/
app.js
File metadata and controls
233 lines (194 loc) · 6.1 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
const express = require('express');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const cookieParser = require('cookie-parser');
const morgan = require('morgan');
const rateLimit = require('express-rate-limit');
const nocache = require('nocache');
const app = express();
// rate limiter used on auth attempts
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 15, // limit each IP to 15 requests per windowMs
message: {
status: 'fail',
message: 'Too many requests, please try again later',
},
});
// read .env and store in process.env
dotenv.config();
// config vars
const port = process.env.AUTH_PORT || 3000;
const tokenSecret = process.env.AUTH_TOKEN_SECRET;
const defaultUser = 'user'; // default user when no username supplied
const expiryDays = process.env.AUTH_EXPIRY_DAYS || 7;
const cookieSecure =
'AUTH_COOKIE_SECURE' in process.env
? process.env.AUTH_COOKIE_SECURE === 'true'
: true;
let cookieOverrides = {};
try {
if (process.env.AUTH_COOKIE_OVERRIDES) {
const parsed = JSON.parse(process.env.AUTH_COOKIE_OVERRIDES);
for (const k of Object.keys(parsed)) {
cookieOverrides[k] = parsed[k];
}
}
} catch (e) {
console.log(
`Warning: Could not parse AUTH_COOKIE_OVERRIDES: ${process.env.AUTH_COOKIE_OVERRIDES}\n`
);
console.log(e);
process.exit(1);
}
// default auth function
// can be customised by defining one in auth.js, e.g use custom back end database
// using single password for the time being, but this could query a database etc
let checkAuth = (user, pass) => {
const authPassword = process.env.AUTH_PASSWORD;
if (!authPassword) {
console.error(
'Misconfigured server. Environment variable AUTH_PASSWORD is not configured'
);
process.exit(1);
}
// check for correct user password
if (pass === authPassword) return true;
return false;
};
// load checkAuth() if defined by user in auth.js
try {
customCheckAuth = require('./auth.js');
if (typeof customCheckAuth === 'function') checkAuth = customCheckAuth;
} catch (ex) {}
if (!tokenSecret) {
console.error(
'Misconfigured server. Environment variable AUTH_TOKEN_SECRET is not configured'
);
process.exit(1);
}
// middleware to check auth status
const jwtVerify = (req, res, next) => {
// get token from cookies
const token = req.cookies.authToken;
// check for missing token
if (!token) return next();
jwt.verify(token, tokenSecret, (err, decoded) => {
if (err) {
// e.g malformed token, bad signature etc - clear the cookie also
console.log(err);
res.clearCookie('authToken');
return res.status(403).send(err);
}
req.user = decoded.user || null;
next();
});
};
app.set('view engine', 'ejs');
// logging
app.use(morgan('dev'));
// serve static files in ./public
app.use(express.static('public'));
// parse cookies
app.use(cookieParser());
// parse json body
app.use(express.json());
// don't allow any form of caching, private or public
app.use(nocache());
// check for JWT cookie from requestor
// if there is a valid JWT, req.user is assigned
app.use(jwtVerify);
// we don't need a root path, direct to login interface
app.get('/', (req, res) => {
res.redirect('/login');
});
// interface for users who are logged in
app.get('/logged-in', (req, res) => {
if (!req.user) return res.redirect('/login');
return res.render('logged-in', { user: req.user || null });
});
// login interface
app.get('/login', (req, res) => {
// parameters from original client request
// these could be used for validating request
const requestUri = req.headers['x-original-uri'];
const remoteAddr = req.headers['x-original-remote-addr'];
const host = req.headers['x-original-host'];
// check if user is already logged in
if (req.user) return res.redirect('/logged-in');
// user not logged in, show login interface
return res.render('login', {
referer: requestUri ? `${host}/${requestUri}` : '/',
});
});
// endpoint called by NGINX sub request
// expect JWT in cookie 'authToken'
app.get('/auth', (req, res, next) => {
// parameters from original client request
// these could be used for validating request
const requestUri = req.headers['x-original-uri'];
const remoteAddr = req.headers['x-original-remote-addr'];
const host = req.headers['x-original-host'];
if (req.user) {
// user is already authenticated, refresh cookie
// generate JWT
const token = jwt.sign({ user: req.user }, tokenSecret, {
expiresIn: `${expiryDays}d`,
});
// set JWT as cookie, 7 day age
res.cookie('authToken', token, {
httpOnly: true,
maxAge: 1000 * 86400 * expiryDays, // milliseconds
secure: cookieSecure,
...cookieOverrides,
});
return res.sendStatus(200);
} else {
// not authenticated
return res.sendStatus(401);
}
});
// endpoint called by login page, username and password posted as JSON body
app.post('/login', apiLimiter, (req, res) => {
const { username, password } = req.body;
if (checkAuth(username, password)) {
// successful auth
const user = username || defaultUser;
// generate JWT
const token = jwt.sign({ user }, tokenSecret, {
expiresIn: `${expiryDays}d`,
});
// set JWT as cookie, 7 day age
res.cookie('authToken', token, {
httpOnly: true,
maxAge: 1000 * 86400 * expiryDays, // milliseconds
secure: cookieSecure,
...cookieOverrides,
});
return res.send({ status: 'ok' });
}
// failed auth
res.status(401).send({ status: 'fail', message: 'Invalid credentials' });
});
// force logout
app.get('/logout', (req, res) => {
res.clearCookie('authToken');
res.redirect('/login');
});
// endpoint called by logout page
app.post('/logout', (req, res) => {
const options = {};
if (cookieOverrides.path) {
options.path = cookieOverrides.path;
}
if (cookieOverrides.domain) {
options.domain = cookieOverrides.domain;
}
res.clearCookie('authToken', options);
res.sendStatus(200);
});
// default 404
app.use((req, res, next) => {
res.status(404).send('No such page');
});
app.listen(port, () => console.log(`Listening at http://localhost:${port}`));