-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
199 lines (164 loc) · 6.21 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
195
196
197
198
199
'use strict';
module.exports = exports = function( args ) {
process.env.NODE_ENV = args.production ? 'production' : 'development';
var config = global.config = args;
// Now let's get to twerk:
var socketio, isValidRequest, sessionMiddleware,
server, options, servicePath, fileName, validLevels, ll,
runAsHTTPS = args.keyfile && args.certfile,
arrServices, arrViews,
oUserSessions = {}
, fs = require( 'fs' )
, path = require( 'path' )
, swig = require( 'swig' )
, https = require( 'https' )
, express = require( 'express' )
, session = require( 'express-session' )
, bodyParser = require( 'body-parser' )
, logger = require( './modules/logger' )(module.filename)
, util = require( 'util' )
, app = express()
;
/*
// Let's fetch the configuration first before we do anything else
// This will throw an error if the configuration file is invalid.
config = JSON.parse( fs.readFileSync( __dirname + '/config/system.json' ) );
*/
ll = args.loglevel || config.loglevel || 'info';
//default value for log level
if ( logger.validLevels.indexOf( ll ) < 0 )
ll = 'info';
ll = 'trace';
logger.setLevel( 'mainlog', ll );
//logger.write( 'error', 'asd', module.filename.split('/') );
//logger.setLevel( 'stdout-log', ll );
// Define a global persistence handler according to the configuration
global.persistence = require( './persistence_handlers/' + config.persistence.method );
// For consistency reasons we should only load our modules after setting the persistence module
socketio = require( './modules/socket' );
// We disable caching for development environments
if ( args.production ) {
process.on( 'uncaughtException', function( e ) {
logger.write( 'error', '', 'This is a general exception catcher, but should really be removed in the future!' );
logger.write( 'error', '', e );
});
} else {
app.set( 'view cache', false );
swig.setDefaults({ cache: false });
}
app.engine( 'html', swig.renderFile );
app.set( 'view engine', 'html' );
app.set( 'views', __dirname + '/views' );
if( runAsHTTPS )
app.set( 'trust proxy', 1 ) // required for secure cookies
sessionMiddleware = session({
secret: config.session.secret,
resave: false,
saveUninitialized: true,
cookie: {
secure: runAsHTTPS ? true : false // We can only use secure cookies on a HTTPS server
}
});
app.use( sessionMiddleware );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({ extended: true }) );
app.use( express.static( path.join( __dirname, 'public' ) ) );
// Apply our own session expiration handler
app.use( function( req, res, next ) {
var username;
if( req.session.pub ) {
username = req.session.pub.username;
// We need to be sure that we do some garbage collecting after the user session expired
if( oUserSessions[ username ] )
clearTimeout( oUserSessions[ username ] );
oUserSessions[ username ] = setTimeout( function() {
// since the session is still existing (user still on webpage in browser) we destroy it, right?
if( req.session.pub )
req.session.destroy();
logger.write( 'fatal', '', 'TODO: cleaning up session of user "' + username + '"!' );
// TODO CLEANUP
}, config.session.timeout * 60 * 1000 ); // Session expiration time is defined in minutes in the config
}
next(); // Continue with the other handlers
});
app.get( '/views/*', function( req, res, next ) {
var allowedRoutes = [
'/views/login',
'/views/register'
];
if( req.session.pub || allowedRoutes.indexOf( req.url ) > -1 )
next();
else
res.render( 'index' );
});
app.get( '/services/*', function( req, res, next ) {
var allowedRoutes = [
'/services/session/login',
'/services/users/create'
];
if( req.session.pub || allowedRoutes.indexOf( req.url ) > -1 )
next();
else {
res.status( 401 );
res.send( 'Login first!' );
}
});
// Load all existing views
arrViews = fs.readdirSync( __dirname + '/views' );
isValidRequest = function( req ) {
var name = req.params[ 0 ];
for( var i = 0; i < arrViews.length; i++ ) {
if( arrViews[ i ] === name + '.html' ) return true;
}
};
// Redirect the views that will be loaded by the swig templating engine
app.get( '/views/*', function ( req, res ) {
var view = 'index';
if( isValidRequest( req ) )
view = req.params[ 0 ];
res.render( view, req.session.pub );
});
// Dynamically load all services from the services folder
logger.write( 'info', '', 'LOADING WEB SERVICES: ' );
arrServices = fs.readdirSync( __dirname + '/services' ).filter(function( d ) {
return ( d.substring( d.length - 3 ) === '.js' );
});
for( var i = 0; i < arrServices.length; i++ ) {
fileName = arrServices[ i ];
logger.write( 'info', '', ' -> ' + fileName );
servicePath = '/services/' + fileName.substring( 0, fileName.length - 3 );
app.use( servicePath, require( '.' + servicePath ) );
}
// Redirect if no routing applied so far
if( args.production ) app.use( function ( req, res ) { res.render( 'index' ) });
// Start the server
// If no key and certificate are provided we start a normal server
if( !runAsHTTPS ) {
server = app.listen( parseInt( args.port ) || 8080, function() {
var addr = server.address(),
mode = args.production ? 'ON' : 'OFF',
str = 'HPWC SSH Interface Server listening at "http://%s:%s" with CACHING %s';
logger.formattedWrite( 'info', '', str, addr.address, addr.port, mode.toUpperCase() );
/* str = 'HPWC SSH Interface Server listening at '
+ '"http://' + addr.address + ':' + addr.port
+ '" with CACHING ' + mode.toUpperCase();
logger.write( 'info', '', str );
//console.log( 'UTIL: ' + util.inspect(addr, {showHidden: false, depth: null}));
*/
});
// Else we are starting a HTTPS server
} else {
options = {
key: fs.readFileSync( args.keyfile ),
cert: fs.readFileSync( args.certfile )
};
server = https.createServer( options, app ).listen( parseInt( args.port ) || 443, function() {
var addr = server.address(),
mode = args.production ? 'ON' : 'OFF',
str = 'HPWC SSH Interface Server listening at "https://%s:%s" with CACHING %s';
logger.formattedWrite( 'info', '', str, addr.address, addr.port, mode.toUpperCase() );
});
}
// Let socket.io listen for websockets
socketio.listen( server, sessionMiddleware );
};