GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — skeleton/app.js at master · dstroot/skeleton Expand file tree/ Copy pathapp.jsMore file actions executable file ·540 lines (467 loc) · 17.8 KB / Copy pathapp.jsFile metadata and controlsexecutable file ·540 lines (467 loc) · 17.8 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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 'use strict'; /** * Module Dependencies */ // Express 4.x Modules var csrf = require('csurf'); // https://github.com/expressjs/csurf var morgan = require('morgan'); // https://github.com/expressjs/morgan var express = require('express'); // https://npmjs.org/package/express var favicon = require('serve-favicon'); // https://github.com/expressjs/favicon var session = require('express-session'); // https://github.com/expressjs/session var compress = require('compression'); // https://github.com/expressjs/compression var bodyParser = require('body-parser'); // https://github.com/expressjs/body-parser var errorHandler = require('errorhandler'); // https://github.com/expressjs/errorhandler var methodOverride = require('method-override'); // https://github.com/expressjs/method-override // Additional Modules var fs = require('fs'); // http://nodejs.org/docs/v0.10.25/api/fs.html var path = require('path'); // http://nodejs.org/docs/v0.10.25/api/path.html var debug = require('debug')('skeleton'); // https://github.com/visionmedia/debug var flash = require('express-flash'); // https://npmjs.org/package/express-flash var config = require('./config/config'); // Get configuration file var logger = require('express-loggly'); // https://github.com/dstroot/express-loggly var helmet = require('helmet'); // https://github.com/evilpacket/helmet var semver = require('semver'); // https://npmjs.org/package/semver var enforce = require('express-sslify'); // https://github.com/florianheinemann/express-sslify var mongoose = require('mongoose'); // https://npmjs.org/package/mongoose var passport = require('passport'); // https://npmjs.org/package/passport var MongoStore = require('connect-mongo')(session); // https://npmjs.org/package/connect-mongo var expressValidator = require('express-validator'); // https://npmjs.org/package/express-validator /** * Create Express app, HTTP server and socket.io listener */ var app = module.exports = express(); // export app for testing ;) var server = require('http').Server(app); var io = require('socket.io')(server); /** * Configure Mongo Database */ mongoose.connect(config.mongodb.url); var db = mongoose.connection; // Use Mongo for session store config.session.store = new MongoStore({ mongooseConnection: db, autoReconnect: true }); /** * Express Configuration and Setup */ // Application local variables are provided to *all* templates // rendered within the application. (personally I would have called // them "app.globals") They are useful for providing helper // functions to templates, as well as global app-level data. // NOTE: you must *not* reuse existing (native) named properties // for your own variable names, such as name, apply, bind, call, // arguments, length, and constructor. app.locals.application = config.name; app.locals.version = config.version; app.locals.description = config.description; app.locals.author = config.author; app.locals.keywords = config.keywords; app.locals.ga = config.ga; // Format dates/times in jade templates // Use moment anywhere within a jade template like this: // p #{moment(Date.now()).format('MM/DD/YYYY')} // http://momentjs.com/ // Good for an evergreen copyright ;) app.locals.moment = require('moment'); // Format numbers in jade templates: // Use numeral anywhere within a jade template like this: // #{numeral('123456').format('$0,0.00')} // http://numeraljs.com/ app.locals.numeral = require('numeral'); if (app.get('env') === 'development') { // Jade options: Don't minify html, debug intrumentation app.locals.pretty = true; app.locals.compileDebug = true; // Turn on console logging in development app.use(morgan('dev')); // Turn off caching in development // This sets the Cache-Control HTTP header to no-store, no-cache, // which tells browsers not to cache anything. app.use(helmet.nocache()); } if (app.get('env') === 'production') { // Jade options: minify html, no debug intrumentation app.locals.pretty = false; app.locals.compileDebug = false; // Enable If behind nginx, proxy, or a load balancer (e.g. Heroku, Nodejitsu) app.enable('trust proxy', 1); // trust first proxy // Since our application has signup, login, etc. forms these should be protected // with SSL encryption. Heroku, Nodejitsu and other hosters often use reverse // proxies or load balancers which offer SSL endpoints (but then forward unencrypted // HTTP traffic to the server). This makes it simpler for us since we don't have to // setup HTTPS in express. When in production we can redirect all traffic to SSL // by using a little middleware. // // In case of a non-encrypted HTTP request, enforce.HTTPS() automatically // redirects to an HTTPS address using a 301 permanent redirect. BE VERY // CAREFUL with this! 301 redirects are cached by browsers and should be // considered permanent. // // NOTE: Use `enforce.HTTPS(true)` if you are behind a proxy or load // balancer that terminates SSL for you (e.g. Heroku, Nodejitsu). app.use(enforce.HTTPS(true)); // This tells browsers, "hey, only use HTTPS for the next period of time". // This will set the Strict Transport Security header, telling browsers to // visit by HTTPS for the next ninety days: // TODO: should we actually have this *and* app.use(enforce.HTTPS(true)); above? // this seems more flexible rather than a hard redirect. var ninetyDaysInMilliseconds = 7776000000; app.use(helmet.hsts({ maxAge: ninetyDaysInMilliseconds })); // Turn on HTTPS/SSL cookies config.session.proxy = true; config.session.cookie.secure = true; } // Port to listen on. app.set('port', config.port); // Favicon - This middleware will come very early in your stack // (maybe even first) to avoid processing any other middleware // if we already know the request is for favicon.ico app.use(favicon(__dirname + '/public/favicon.ico')); // Report CSP violations (*ABOVE* CSURF in the middleware stack) // Browsers will post violations to this route // https://mathiasbynens.be/notes/csp-reports app.post('/csp', bodyParser.json(), function (req, res) { // TODO - requires production level logging if (req.body) { // Just send to debug to see if this is working debug('CSP Violation: ' + JSON.stringify(req.body)); } else { debug('CSP Violation: No data received!'); } res.status(204).end(); }); // Setup the view engine (jade) app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // Compress response data with gzip / deflate. // This middleware should be placed "high" within // the stack to ensure all responses are compressed. app.use(compress()); // http://en.wikipedia.org/wiki/HTTP_ETag // Google has a nice article about "strong" and "weak" caching. // It's worth a quick read if you don't know what that means. // https://developers.google.com/speed/docs/best-practices/caching app.set('etag', true); // other values 'weak', 'strong' // Now setup serving static assets from /public // time in milliseconds... var minute = 1000 * 60; // 60000 var hour = (minute * 60); // 3600000 var day = (hour * 24); // 86400000 var week = (day * 7); // 604800000 app.use(express.static(__dirname + '/public', { maxAge: week })); // Body parsing middleware supporting // JSON, urlencoded, and multipart requests. // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); // Easy form validation! // This line must be immediately after bodyParser! app.use(expressValidator()); // If you want to simulate DELETE and PUT // in your app you need methodOverride. app.use(methodOverride()); // Use sessions // NOTE: cookie-parser not needed with express-session > v1.5 app.use(session(config.session)); /* Thoughts on logging: ** DEVELOPMENT ** In development we can use the standard logger (morgan) and debug (https://github.com/visionmedia/debug) for console output Debug has an advantage over `console.log` because it only outputs when you specifically start node with it enabled. ** PRODUCTION ** Personally I prefer to stream Express logging to a service like Loggly or Papertrail. That way I don't worry about the file system, log shipping/rotating, etc. Plus these have useful features for analyzing the data. If you want to log to a file in production you can do as follows. (Be careful however because this can fill up your file system unless you handle it properly.) Probably best to use a tool like Winston. But the easy way is to send the morgan log stream to ./myLogFile.log: // use {flags: 'w'} to open in write mode, 'a' = append var logFile = fs.createWriteStream('./myLogFile.log', { flags: 'a' }); app.use(morgan('combined', { stream: logFile })); */ // Log requests to Loggly in production // Needs to be below session and bodyParser in the stack if (app.get('env') === 'production' && config.logging) { app.use(logger({ loggly: config.loggly })); } // Security Settings app.disable('x-powered-by'); // Don't advertise our server type app.use(csrf()); // Prevent Cross-Site Request Forgery app.use(helmet.ienoopen()); // X-Download-Options for IE8+ app.use(helmet.nosniff()); // Sets X-Content-Type-Options to nosniff app.use(helmet.xssFilter()); // sets the X-XSS-Protection header app.use(helmet.frameguard('deny')); // Prevent iframe clickjacking // Content Security Policy: // http://content-security-policy.com/ // http://www.html5rocks.com/en/tutorials/security/content-security-policy/ // http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/ // // NOTE: TURN THIS OFF DURING DEVELOPMENT // IT'S JUST PAINFUL OTHERWISE! OR DON'T // EVEN USE IT AT ALL - I JUST WANTED TO // LEARN HOW IT WORKS. :) app.use(helmet.contentSecurityPolicy({ defaultSrc: [ "'self'", 'skeleton-app.jit.su' ], scriptSrc: [ "'self'", "'unsafe-eval'", "'unsafe-inline'", 'http://ajax.googleapis.com', 'https://ajax.googleapis.com', 'http://www.google-analytics.com', 'https://www.google-analytics.com', 'http://oss.maxcdn.com', 'https://oss.maxcdn.com', 'http://cdn.socket.io', 'https://cdn.socket.io', 'http://checkout.stripe.com', 'https://checkout.stripe.com', 'http://cdnjs.cloudflare.com', 'https://cdnjs.cloudflare.com' ], styleSrc: [ "'self'", "'unsafe-inline'", 'http://fonts.googleapis.com', 'https://fonts.googleapis.com', 'http://checkout.stripe.com', 'https://checkout.stripe.com' ], fontSrc: [ "'self'", 'http://fonts.googleapis.com', 'https://fonts.googleapis.com', 'http://fonts.gstatic.com', 'https://fonts.gstatic.com', 'htp://themes.googleusercontent.com', 'https://themes.googleusercontent.com' ], imgSrc: [ "'self'", 'data:', 'http://img2-ak.lst.fm', 'https://gravatar.com', 'https://avatars.githubusercontent.com', 'http://pbs.twimg.com', 'https://pbs.twimg.com', 'http://*.4sqi.net', 'https://*.4sqi.net', 'http://*.media.tumblr.com', 'http://userserve-ak.last.fm', 'http://graph.facebook.com', 'https://graph.facebook.com', 'http://*.fbcdn.net', 'https://*.fbcdn.net', 'http://fbcdn-profile-a.akamaihd.net', 'https://fbcdn-profile-a.akamaihd.net', 'http://github.global.ssl.fastly.net', 'https://github.global.ssl.fastly.net', 'http://chart.googleapis.com', 'https://chart.googleapis.com', 'http://www.google-analytics.com', 'https://www.google-analytics.com' ], mediaSrc: [ "'self'" ], connectSrc: [ // limit the origins (via XHR, WebSockets, and EventSource) "'self'", 'ws://localhost:5000', 'ws://localhost:3000', 'ws://127.0.0.1:35729/livereload', 'wss://skeleton-app.jit.su', 'https://api.github.com' ], objectSrc: [ // allows control over Flash and other plugins "'none'" ], frameSrc: [ // origins that can be embedded as frames 'http://checkout.stripe.com', 'https://checkout.stripe.com', ], sandbox: [ 'allow-same-origin', 'allow-forms', 'allow-scripts' ], reportUri: '/report-violation', reportOnly: false, // set to true if you *only* want to report errors setAllHeaders: false, // set to true if you want to set all headers disableAndroid: false, // set to true if you want to disable Android (browsers can vary and be buggy) safari5: false // set to true if you want to force buggy CSP in Safari 5 })); // Passport OAUTH Middleware app.use(passport.initialize()); app.use(passport.session()); // Keep user, csrf token and config available app.use(function (req, res, next) { res.locals.user = req.user; res.locals.config = config; res.locals._csrf = req.csrfToken(); next(); }); // Flash messages app.use(flash()); /** * Routes/Routing */ // Dynamically include routes (via controllers) fs.readdirSync('./controllers').forEach(function (file) { if (file.substr(-3) === '.js') { var route = require('./controllers/' + file); route.controller(app); } }); /** * Error Handling */ // If nothing responded above we will assume a 404 // (since no routes responded or static assets found) // Tests: // $ curl http://localhost:3000/notfound // $ curl http://localhost:3000/notfound -H "Accept: application/json" // $ curl http://localhost:3000/notfound -H "Accept: text/plain" // Handle 404 Errors app.use(function (req, res, next) { res.status(404); debug('404 Warning. URL: ' + req.url); // Respond with html page if (req.accepts('html')) { res.render('error/404', { url: req.url }); return; } // Respond with json if (req.accepts('json')) { res.send({ error: 'Not found!' }); return; } // Default to plain-text. send() res.type('txt').send('Error: Not found!'); }); // True error-handling middleware requires an arity of 4, // aka the signature (err, req, res, next). // Handle 403 Errors app.use(function (err, req, res, next) { if (err.status === 403) { res.status(err.status); debug('403 Not Allowed. URL: ' + req.url + ' Err: ' + err); // Respond with HTML if (req.accepts('html')) { res.render('error/403', { error: err, url: req.url }); return; } // Respond with json if (req.accepts('json')) { res.send({ error: 'Not Allowed!' }); return; } // Default to plain-text. send() res.type('txt').send('Error: Not Allowed!'); } else { // Since the error is not a 403 pass it along return next(err); } }); // Production 500 error handler (no stacktraces leaked to public!) if (app.get('env') === 'production') { app.use(function (err, req, res, next) { res.status(err.status || 500); debug('Error: ' + (err.status || 500).toString().red.bold + ' ' + err); res.render('error/500', { error: {} // don't leak information }); }); } // Development 500 error handler if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); debug('Error: ' + (err.status || 500).toString().red.bold + ' ' + err); res.render('error/500', { error: err }); }); // Final error catch-all just in case... app.use(errorHandler()); } /* * Start Express server. * * NOTE: To alter the environment we can set the * NODE_ENV environment variable, for example: * * $ NODE_ENV=production node app.js * * This is important - many caching mechanisms * are *only* enabled when in production! */ db.on('error', function () { debug('MongoDB Connection Error. Please make sure MongoDB is running.'.red.bold); process.exit(0); }); db.on('open', function () { debug('Mongodb ' + 'connected!'.green.bold); // "server.listen" for socket.io server.listen(app.get('port'), function () { // Test for correct node version as spec'ed in package.info if (!semver.satisfies(process.versions.node, config.engine)) { debug('Error: unsupported version of Node or io.js!'.red.bold); debug(config.name.red.bold + ' needs Node or io.js version '.red.bold + config.engine.red.bold); process.exit(0); } // Log how we are running debug('listening on port ' + app.get('port').toString().green.bold); debug('listening in ' + app.settings.env.green.bold + ' mode.'); debug('Ctrl+C'.green.bold + ' to shut down. ;)'); // Exit cleanly on Ctrl+C process.on('SIGINT', function () { io.close(); // close socket.io console.log('\n'); debug('has ' + 'shutdown'.green.bold); debug('was running for ' + Math.round(process.uptime()).toString().green.bold + ' seconds.'); process.exit(0); }); }); }); /** * Emit Pageviews on Socket.io for Dashboard * * Web Page (Client) --->> ( `pageview` messages ) --->> Server * Web Page (Client) <<--- (`dashUpdate` messages) <<--- Server */ var connectedCount = 0; io.on('connection', function (socket) { connectedCount += 1; // Listen for pageview messages from clients socket.on('pageview', function (message) { var ip = socket.handshake.headers['x-forwarded-for'] || socket.client.conn.remoteAddress || socket.handshake.address; var url = message; // Broadcast dashboard update (to all clients in default namespace) io.emit('dashUpdate', { connections: connectedCount, ip: ip, url: url, timestamp: new Date() }); }); // Update dashboard connections on disconnect events socket.on('disconnect', function () { connectedCount -= 1; io.emit('dashUpdate', { connections: connectedCount }); }); }); |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |