This repository has been archived by the owner on Dec 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·242 lines (197 loc) · 7.03 KB
/
app.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
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
234
235
236
237
238
239
240
241
242
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var helmet = require('helmet')
var redis = require('redis');
var session = require('express-session');
// https://github.com/tj/connect-redis
var RedisStore = require('connect-redis')(session);
/////////////////
// required for socket.io to use passport's authentication
// see the following website for information about this
// https://www.codementor.io/tips/0217388244/sharing-passport-js-sessions-with-both-express-and-socket-io
// don't confuse this with passport.socket.io, which is wrong!
// https://www.npmjs.com/package/passport.socketio
// https://github.com/jfromaniello/passport.socketio
var passportSocketIo = require('passport.socketio');
var cookieParser = require('cookie-parser');
// https://www.npmjs.com/package/connect-redis
// start redis and create the redis store
// https://github.com/tj/connect-redis/blob/master/migration-to-v4.md
// No password, so removed this line for now.
// password: 'my secret',
let redisClient = redis.createClient({
host: 'localhost',
port: 6379,
db: 1,
});
redisClient.unref();
redisClient.on('error', console.log);
let sessionStore = new RedisStore({ client: redisClient });
/////////////////
mongoose.Promise = global.Promise;
console.log('start mongoose');
mongoose.connect('mongodb://localhost/node-auth', {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('connection successful'))
.catch((err) => console.error(err));
var index = require('./routes/index');
var app = express();
// "Helmet helps you secure your Express apps by setting various HTTP headers."
console.log('use helmet');
app.use(helmet());
var use_content_security_policy = true;
if (use_content_security_policy) {
console.log('using a content security policy');
app.use(helmet.contentSecurityPolicy({
directives:{
defaultSrc:["'self'"],
scriptSrc:["'self'", "'unsafe-inline'", 'static.robotwebtools.org', 'robotwebtools.org', 'webrtc.github.io'],
connectSrc:["'self'", 'ws://localhost:9090'],
imgSrc: ["'self'", 'data:'],
styleSrc:["'self'"],
fontSrc:["'self'"]}}));
} else {
// Disable the content security policy. This is helpful during
// development, but risky when deployed.
console.log('WARNING: Not using a content security policy. This is risky when deployed!');
app.use(
helmet({
contentSecurityPolicy: false,
})
);
}
/////////////////////////
//
// Only allow use of HTTPS and redirect HTTP requests to HTTPS
//
// code derived from
// https://stackoverflow.com/questions/24015292/express-4-x-redirect-http-to-https
console.log('require https');
app.all('*', ensureSecure); // at top of routing calls
function ensureSecure(req, res, next){
if(req.secure){
// OK, continue
return next();
};
// handle port numbers if you need non defaults
res.redirect('https://' + req.hostname + req.url);
};
/////////////////////////
// view engine setup
console.log('set up the view engine');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var secret_string = 'you should change this secret string';
app.use(session({
secret: secret_string,
store: sessionStore,
resave: false,
saveUninitialized: false,
cookie: {
secure: true,
sameSite: true
}
}));
//var RedisStore = require('connect-redis')(session);
// set up passport for user authorization (logging in, etc.)
console.log('set up passport');
app.use(passport.initialize());
app.use(passport.session());
// make files in the public directory available to everyone
console.log('make public directory contents available to everyone');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// passport configuration
console.log('configure passport');
var User = require('./models/User');
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
console.log('set up error handling');
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
//////////////////////////////////////////////////////////
// check if user is an approved and logged-in robot
function isRobot(data) {
return (data.user &&
data.user.logged_in &&
data.user.approved &&
(data.user.role === 'robot'));
};
// check if user is an approved and logged-in operator
function isOperator(data) {
return (data.user &&
data.user.logged_in &&
data.user.approved &&
(data.user.role === 'operator'));
};
// based on passport.socketio documentation
// https://github.com/jfromaniello/passport.socketio
function onAuthorizeSuccess(data, accept){
console.log('');
console.log('successful connection to socket.io');
console.log('data.user =');
console.log(data.user);
if(isRobot(data) || isOperator(data)) {
console.log('connection authorized!');
accept();
} else {
console.log('connection attempt from unauthorized source!');
// reject connection (for whatever reason)
accept(new Error('not authorized'));
}
}
function onAuthorizeFail(data, message, error, accept){
console.log('');
console.log('#######################################################');
console.log('failed connection to socket.io:', message);
console.log('data.headers =');
console.log(data.headers);
// console.log('message =');
// console.log(message);
// console.log('error =');
// console.log(error);
// console.log('accept =');
// console.log(accept);
console.log('#######################################################');
console.log('');
// error indicates whether the fail is due to an error or just an unauthorized client
if(error) throw new Error(message);
// send the (not-fatal) error-message to the client and deny the connection
//return accept(new Error(message));
return accept(new Error("You are not authorized to connect."));
}
ioauth = passportSocketIo.authorize({
key: 'connect.sid',
secret: secret_string,
store: sessionStore,
cookieParser: cookieParser,
success: onAuthorizeSuccess,
fail: onAuthorizeFail
});
module.exports = {
app: app,
ioauth: ioauth
};