Last active
August 29, 2015 13:56
-
-
Save hedgerh/8926638 to your computer and use it in GitHub Desktop.
Problem loading sources
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/** | |
* Module dependencies. | |
*/ | |
var express = require('express'), | |
consolidate = require('consolidate'), | |
mongoStore = require('connect-mongo')(express), | |
flash = require('connect-flash'), | |
helpers = require('view-helpers'), | |
config = require('./config'); | |
module.exports = function(app, passport, db) { | |
app.set('showStackError', true); | |
// Prettify HTML | |
app.locals.pretty = true; | |
// cache=memory or swig dies in NODE_ENV=production | |
app.locals.cache = 'memory'; | |
// Should be placed before express.static | |
// To ensure that all assets and data are compressed (utilize bandwidth) | |
app.use(express.compress({ | |
filter: function(req, res) { | |
return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); | |
}, | |
// Levels are specified in a range of 0 to 9, where-as 0 is | |
// no compression and 9 is best compression, but slowest | |
level: 9 | |
})); | |
// Only use logger for development environment | |
if (process.env.NODE_ENV === 'development') { | |
app.use(express.logger('dev')); | |
} | |
app.set('views', config.root + '/client/views'); | |
app.set('view engine', 'jade'); | |
// Enable jsonp | |
app.enable('jsonp callback'); | |
app.configure(function() { | |
// The cookieParser should be above session | |
app.use(express.cookieParser()); | |
app.use(express.cookieSession( | |
{ | |
secret: process.env.COOKIE_SECRET || "Superdupersecret" | |
})); | |
app.use(express.csrf()); | |
app.use(function(req, res, next) { | |
res.cookie('XSRF-TOKEN', req.csrfToken()); | |
next(); | |
}); | |
// Request body parsing middleware should be above methodOverride | |
app.use(express.bodyParser()); | |
app.use(express.methodOverride()); | |
// Express/Mongo session storage | |
/*app.use(express.session({ | |
secret: config.sessionSecret, | |
store: new mongoStore({ | |
db: db.connection.db, | |
collection: config.sessionCollection | |
}) | |
}));*/ | |
// Dynamic helpers | |
app.use(helpers(config.app.name)); | |
// Use passport session | |
app.use(passport.initialize()); | |
app.use(passport.session()); | |
// Connect flash for flash messages | |
app.use(flash()); | |
// Routes should be at the last | |
app.use(app.router); | |
// Setting the fav icon and static folder | |
app.use(express.favicon()); | |
app.use(express.static(config.root + '/client')); | |
// Assume "not found" in the error msgs is a 404. this is somewhat | |
// silly, but valid, you can do whatever you like, set properties, | |
// use instanceof etc. | |
app.use(function(err, req, res, next) { | |
// Treat as 404 | |
if (~err.message.indexOf('not found')) return next(); | |
// Log it | |
console.error(err.stack); | |
// Error page | |
res.status(500).render('500', { | |
error: err.stack | |
}); | |
}); | |
// Assume 404 since no middleware responded | |
app.use(function(req, res) { | |
res.status(404).render('404', { | |
url: req.originalUrl, | |
error: 'Not found' | |
}); | |
}); | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
doctype html | |
html(lang='en', data-ng-app='angular-client-side-auth') | |
head | |
meta(charset='utf-8') | |
title Angular Auth Example | |
link(rel='stylesheet', href='/css/app.css') | |
link(href="/components/bootstrap/dist/css/bootstrap.min.css", rel="stylesheet") | |
link(href="/components/font-awesome/css/font-awesome.min.css", rel="stylesheet") | |
// This is needed because Facebook login redirects add #_=_ at the end of the URL | |
script(type="text/javascript"). | |
if (window.location.href.indexOf('#_=_') > 0) { | |
window.location = window.location.href.replace(/#.*/, ''); | |
} | |
body(data-ng-cloak) | |
.navbar(data-ng-controller="NavCtrl") | |
.navbar-inner | |
.container-fluid | |
ul.nav.nav-tabs | |
li(data-access-level='accessLevels.anon', active-nav) | |
a(href='/login') Log in | |
li(data-access-level='accessLevels.anon', active-nav) | |
a(href='/register') Register | |
li(data-access-level='accessLevels.user', active-nav) | |
a(href='/') Home | |
li(data-access-level='accessLevels.user', active-nav='nestedTop') | |
a(href='/private') Private | |
li(data-access-level='accessLevels.admin', active-nav) | |
a(href='/admin') Admin | |
li(data-access-level='accessLevels.user') | |
a(href="", data-ng-click="logout()") | |
| Log out | |
div#userInfo.pull-right(data-access-level='accessLevels.user') | |
| Welcome | |
strong {{ user.username }} | |
span.label(data-ng-class='{"label-info": user.role.title == userRoles.user.title, "label-success": user.role.title == userRoles.admin.title}') {{ user.role.title }} | |
.container(data-ui-view) | |
#alertBox.alert.alert-danger(data-ng-show="error") | |
button(type="button", class="close", data-ng-click="error = null;") × | |
strong Oh no! | |
span(data-ng-bind="error") | |
script(src='/components/underscore/underscore-min.js') | |
script(src='/components/angular/angular.min.js') | |
script(src='/components/angular-cookies/angular-cookies.min.js') | |
script(src='/components/angular-ui-router/release/angular-ui-router.min.js') | |
script(src='/js/routingConfig.js') | |
script(src='/js/app.js') | |
script(src='/js/services.js') | |
script(src='/js/controllers.js') | |
script(src='/js/filters.js') | |
script(src='/js/directives.js') | |
// Partial views... Load up front to make transitions smoother | |
script(type="text/ng-template", id="404") | |
include partials/404 | |
script(type="text/ng-template", id="admin") | |
include partials/admin | |
script(type="text/ng-template", id="home") | |
include partials/home | |
script(type="text/ng-template", id="login") | |
include partials/login | |
script(type="text/ng-template", id="private/layout") | |
include partials/private/layout | |
script(type="text/ng-template", id="private/home") | |
include partials/private/home | |
script(type="text/ng-template", id="private/nested") | |
include partials/private/nested | |
script(type="text/ng-template", id="private/nestedAdmin") | |
include partials/private/nestedAdmin | |
script(type="text/ng-template", id="register") | |
include partials/register |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var _ = require('underscore') | |
, path = require('path') | |
, passport = require('passport') | |
, UserControl = require('../controllers/user') | |
, User = require('../models/user.js') | |
, userRoles = require('../../config/roles').userRoles | |
, accessLevels = require('../../config/roles').accessLevels; | |
var routes = [ | |
// Views | |
{ | |
path: '/partials/*', | |
httpMethod: 'GET', | |
middleware: [function (req, res) { | |
var requestedView = path.join('./', req.url); | |
res.render(requestedView); | |
}] | |
}, | |
// Local Auth | |
{ | |
path: '/register', | |
httpMethod: 'POST', | |
middleware: [UserControl.register] | |
}, | |
{ | |
path: '/login', | |
httpMethod: 'POST', | |
middleware: [UserControl.login] | |
}, | |
{ | |
path: '/logout', | |
httpMethod: 'POST', | |
middleware: [UserControl.logout] | |
}, | |
// All other get requests should be handled by AngularJS's client-side routing system | |
{ | |
path: '/*', | |
httpMethod: 'GET', | |
middleware: [function(req, res) { | |
var role = userRoles.public, username = ''; | |
if(req.user) { | |
role = req.user.role; | |
username = req.user.username; | |
} | |
res.cookie('user', JSON.stringify({ | |
'username': username, | |
'role': role | |
})); | |
res.render('index'); | |
}] | |
} | |
]; | |
module.exports = function(app) { | |
_.each(routes, function(route) { | |
route.middleware.unshift(ensureAuthorized); | |
var args = _.flatten([route.path, route.middleware]); | |
switch(route.httpMethod.toUpperCase()) { | |
case 'GET': | |
app.get.apply(app, args); | |
break; | |
case 'POST': | |
app.post.apply(app, args); | |
break; | |
case 'PUT': | |
app.put.apply(app, args); | |
break; | |
case 'DELETE': | |
app.delete.apply(app, args); | |
break; | |
default: | |
throw new Error('Invalid HTTP method specified for route ' + route.path); | |
break; | |
} | |
}); | |
} | |
function ensureAuthorized(req, res, next) { | |
var role; | |
if(!req.user) role = userRoles.public; | |
else role = req.user.role; | |
var accessLevel = _.findWhere(routes, { path: req.route.path }).accessLevel || accessLevels.public; | |
if(!(accessLevel.bitMask & role.bitMask)) return res.send(403); | |
return next(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/** | |
* Module dependencies. | |
*/ | |
var express = require('express'), | |
fs = require('fs'), | |
passport = require('passport'), | |
logger = require('mean-logger'); | |
/** | |
* Main application entry file. | |
* Please note that the order of loading is important. | |
*/ | |
// Load configurations | |
// Set the node enviornment variable if not set before | |
process.env.NODE_ENV = process.env.NODE_ENV || 'development'; | |
// Initializing system variables | |
var config = require('./config/config'), | |
mongoose = require('mongoose'); | |
// Bootstrap db connection | |
var db = mongoose.connect(config.db); | |
// Bootstrap models | |
var models_path = __dirname + '/server/models'; | |
var walk = function(path) { | |
fs.readdirSync(path).forEach(function(file) { | |
var newPath = path + '/' + file; | |
var stat = fs.statSync(newPath); | |
if (stat.isFile()) { | |
if (/(.*)\.(js$|coffee$)/.test(file)) { | |
require(newPath); | |
} | |
} else if (stat.isDirectory()) { | |
walk(newPath); | |
} | |
}); | |
}; | |
walk(models_path); | |
// Bootstrap passport config | |
require('./config/passport')(passport); | |
var app = express(); | |
// Express settings | |
require('./config/express')(app, passport, db); | |
// Bootstrap routes | |
var routes_path = __dirname + '/server/routes'; | |
var walk = function(path) { | |
fs.readdirSync(path).forEach(function(file) { | |
var newPath = path + '/' + file; | |
var stat = fs.statSync(newPath); | |
if (stat.isFile()) { | |
if (/(.*)\.(js$|coffee$)/.test(file)) { | |
require(newPath)(app, passport); | |
} | |
// We skip the app/routes/middlewares directory as it is meant to be | |
// used and shared by routes as further middlewares and is not a | |
// route by itself | |
} else if (stat.isDirectory() && file !== 'middlewares') { | |
walk(newPath); | |
} | |
}); | |
}; | |
walk(routes_path); | |
// Start the app by listening on <port> | |
var port = process.env.PORT || config.port; | |
app.listen(port); | |
console.log('Express app started on port ' + port); | |
// Initializing logger | |
logger.init(app, passport, mongoose); | |
// Expose app | |
exports = module.exports = app; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment