From bceb19cc8cdb402375b630fef62d397132e1187a Mon Sep 17 00:00:00 2001 From: Jonnie Spratley Date: Sun, 14 Dec 2014 14:40:42 -0800 Subject: [PATCH] updated files --- Gruntfile.js | 5 +- config/config.json | 8 +-- package.json | 5 +- routes/cms-passport.js | 64 ++++++++++++------- routes/cms-rest.js | 25 +++++--- routes/cms-routes.js | 17 ++++- routes/cms-server.js | 30 ++++++++- routes/cms-sockets.js | 104 +++++++++++++++++++++++++++++-- routes/models/user.js | 2 +- server.js | 4 -- test/routes/cms-passport-spec.js | 16 +++-- www/account.ejs | 19 +++++- www/index.html | 59 +++++++++++++++--- www/layout.ejs | 39 +++++++++++- www/login.ejs | 19 +----- 15 files changed, 330 insertions(+), 86 deletions(-) diff --git a/Gruntfile.js b/Gruntfile.js index 58a095f..30f82ff 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -91,7 +91,10 @@ module.exports = function (grunt) { // Change this to '0.0.0.0' to access the server from outside. hostname: '127.0.0.1', livereload: 35729, - base: ['.tmp', '<%= yeoman.app %>'] + base: ['.tmp', '<%= yeoman.app %>'], + onCreateServer: function(server, connect, options) { + console.warn('onCreateServer', options); + } }, livereload: { options: { diff --git a/config/config.json b/config/config.json index ee1081f..aa3ffea 100644 --- a/config/config.json +++ b/config/config.json @@ -20,10 +20,10 @@ "hostname": "localhost", "port": 5001 }, - "staticDir": "/dist", - "publicDir": "/app", - "uploadsTmpDir": "/.tmp", - "uploadsDestDir": "/www/cms-content/uploads", + "staticDir": "dist", + "publicDir": "www", + "uploadsTmpDir": ".tmp", + "uploadsDestDir": "www/cms-content/uploads", "uploadsUrl": ":8181/cms-content/", "logFormat": "[:date] - [:method] - :url - :status - :response-time ms" } diff --git a/package.json b/package.json index a94a88c..7569e87 100755 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "logfmt": "~0.18.1", "markdown": "~0.5.0", "method-override": "~1.0.0", - "mongodb": "*", + "mongodb": "^1.4.23", "mongoose": "^3.8.20", "passport": "^0.2.1", "passport-facebook": "^1.0.3", @@ -59,7 +59,8 @@ "promised-io": "~0.3.4", "q": "^1.1.2", "request": "~2.34.0", - "socket.io": "~0.9.16" + "socket.io": "~0.9.16", + "websocket": "^1.0.14" }, "devDependencies": { "chai": "^1.10.0", diff --git a/routes/cms-passport.js b/routes/cms-passport.js index ed32753..57e2976 100644 --- a/routes/cms-passport.js +++ b/routes/cms-passport.js @@ -1,5 +1,5 @@ var passport = require('passport'), - BasicStrategy = require('passport-http').Strategy, + BasicStrategy = require('passport-http').BasicStrategy, LocalStrategy = require('passport-local').Strategy, GoogleStrategy = require('passport-google').Strategy, express = require('express'), @@ -38,18 +38,39 @@ var ensureAuthenticated = function (req, res, next) { */ var cmsPassport = function (config, app) { +var user = new User(); if (!app) { throw new Error('Must provide express application!'); } + /* + + */ + var findOrCreate = function(u, done){ + console.log('find', u); + + for (var i = 0; i < u.emails.length; i++) { + var email = u.emails[i].value + User.findOne({ email: email }, function (err, user) { + if (err) { return done(err); } + if (!user) { + console.warn('create user', u); + return done(null, false); + } + return done(null, user); + }); + } + + }; + /** * I handle serializing a user. * @param user * @param done */ var serializeUser = function (user, done) { - done(null, user.id); + done(null, user._id); }; /** @@ -67,26 +88,18 @@ var cmsPassport = function (config, app) { passport.deserializeUser(deserializeUser); - passport.use(new LocalStrategy({ - usernameField: 'username', - passwordField: 'password', - passReqToCallback: true - }, function (username, password, done) { - console.warn('username', username, password); - process.nextTick(function () { - console.warn('find by username'); - User.find({ - username: username - }, function (err, user) { - console.warn(err, user); - if (err) { - return done(null, false); - } +var strategy = function(username, password, done) { + console.warn('find user', username, password); + User.findOne({ username: username }, function (err, user) { + if (err) { return done(err); } + if (!user) { return done(null, false); } + if (!user.validPassword(password)) { return done(null, false); } return done(null, user); }); - }); - } - )); + }; + + passport.use(new BasicStrategy(strategy)); + passport.use(new LocalStrategy(strategy)); passport.use(new GoogleStrategy({ returnURL: 'http://localhost:8181/auth/google/return', @@ -95,7 +108,7 @@ var cmsPassport = function (config, app) { function (identifier, profile, done) { console.warn('googleCallback', profile); profile.openId = identifier; - User.findOrCreate(profile, function (err, user) { + findOrCreate(profile, function (err, user) { done(err, user); }); } @@ -117,11 +130,13 @@ var cmsPassport = function (config, app) { app.use(passport.session()); app.use(flash()); + app.get('/api/me', passport.authenticate('basic', {session: false}), function (req, res) { res.json(req.user); }); app.all('*', function (req, res, next) { + req.config = JSON.stringify(config); console.warn('cmsAuth', req.params); next(); }); @@ -131,7 +146,10 @@ var cmsPassport = function (config, app) { }); app.get('/account', ensureAuthenticated, function (req, res) { - res.render('account', {user: req.user}); + res.render('account', { + user: req.user, + config: req.config + }); }); app.get('/login', function (req, res) { @@ -140,7 +158,7 @@ var cmsPassport = function (config, app) { app.post('/login', passport.authenticate('local', { - successRedirect: '/', + successRedirect: '/account', failureRedirect: '/login', failureFlash: false }) diff --git a/routes/cms-rest.js b/routes/cms-rest.js index 0fd127b..c6c286a 100644 --- a/routes/cms-rest.js +++ b/routes/cms-rest.js @@ -1,20 +1,29 @@ -var bodyParser = require( 'body-parser' ), +var express = require('express'), + bodyParser = require( 'body-parser' ), session = require( 'express-session' ), RestResource = require( './rest' ); module.exports = function (config, app) { 'use strict'; + var router = express.Router(); - app.get( config.apiBase + '/plugins', RestResource.plugins ); - app.get( config.apiBase + '/readme', RestResource.readme ); - app.get( config.apiBase, RestResource.index ); +// a middleware with no mount path, gets executed for every request to the router + router.use(function (req, res, next) { + console.log('cms-rest Time:', Date.now()); + next(); + }); + router.get( config.apiBase, RestResource.index ); + router.get( config.apiBase + '/plugins', RestResource.plugins ); + router.get( config.apiBase + '/readme', RestResource.readme ); //Dynamic REST - app.get( config.apiBase + '/:db/:collection/:id?', RestResource.get ) - app.post( config.apiBase + '/:db/:collection/:id?', bodyParser.json(), RestResource.add ) - app.put( config.apiBase + '/:db/:collection/:id?', bodyParser.json(), RestResource.edit ) - app.delete( config.apiBase + '/:db/:collection/:id?', RestResource.destroy ); + router.get( config.apiBase + '/:db/:collection/:id?', RestResource.get ) + router.post( config.apiBase + '/:db/:collection/:id?', bodyParser.json(), RestResource.add ) + router.put( config.apiBase + '/:db/:collection/:id?', bodyParser.json(), RestResource.edit ) + router.delete( config.apiBase + '/:db/:collection/:id?', RestResource.destroy ); console.warn( 'cms-rest', 'initialized' ); + + app.use('/', router); }; diff --git a/routes/cms-routes.js b/routes/cms-routes.js index 6042580..1946918 100644 --- a/routes/cms-routes.js +++ b/routes/cms-routes.js @@ -1,12 +1,23 @@ -var mongoose = require('mongoose'); +var mongoose = require('mongoose'), http = require('http'), util = require('util'); module.exports.mount = function (config, app) { + 'use strict'; + + //Connect to database mongoose.connect(config.mongodb); + + var server = http.createServer(app); + require( './cms-auth' )( config, app ); require( './cms-passport' )( config, app ); require( './cms-rest' )( config, app ); require( './cms-proxy' )( config, app ); - require( './cms-sockets' )( config, app ); - require( './cms-server' )( config, app ); require( './cms-upload' )( config, app ); + require( './cms-sockets' )( config, server ); + require( './cms-server' )( config, app ); + + return server.listen(config.port || process.env.PORT, function () { + util.log('App listening on port: ' + config.port + ''.verbose); + util.log(util.inspect(config, {colors: true})); + }); }; diff --git a/routes/cms-server.js b/routes/cms-server.js index d26cb07..d995919 100644 --- a/routes/cms-server.js +++ b/routes/cms-server.js @@ -1,3 +1,31 @@ +var express = require('express'), + path = require('path'), + bodyParser = require( 'body-parser' ); + module.exports = function (config, app) { - console.warn( 'cms-server'); + console.warn( 'cms-server initialized'); + + var router = express.Router(); + + var options = { + dotfiles: 'ignore', + etag: false, + extensions: ['htm', 'html'], + index: false, + maxAge: '1d', + redirect: false, + setHeaders: function (res, path) { + res.set('x-timestamp', Date.now()) + } + }; + + router.use(express.static(config.staticDir, options)); + router.use(express.static(config.publicDir, options)); + router.use('/', function(res, req, next){ + req.send(config.publicDir + path.sep + 'index.html'); + next(); + }); + + app.use('/', router); + }; diff --git a/routes/cms-sockets.js b/routes/cms-sockets.js index 894fc91..bc2c29d 100644 --- a/routes/cms-sockets.js +++ b/routes/cms-sockets.js @@ -1,11 +1,105 @@ + const events = require('events'), util = require('util'); -var cmsSockets = function (config, app) { +var q = require( 'q' ), +WebSocketServer = require('websocket').server, +WebSocketRouter = require('websocket').router; +//////////////////////////// +//## Socket Server +//This is a socket server implementation for 'real' time analytics and other data. +//This is for use with geo analytics and other backend data from the app. listen for connected clients +// +// ### Server Channels +//These are the events that this socket server dispatches. +// +//1. cms:authorization +//2. cms:client:message +//3. cms:client:connect +//4. cms:client:disconnect +//5. cms:server:message +//6. cms:server:disconnect +//7. cms:server:connect +//8. cms: +module.exports = function (config, app) { + 'use strict'; events.EventEmitter.call(this); + console.warn( 'cms-sockts initialized' ); - console.warn( 'cms-sockts' ); + //Start the websocket server + //SocketServer.init(proxyServer); + var cmsSockets = {}, + connections, wsserver, wsclient, router, self = cmsSockets; -}; -util.inherits(cmsSockets, events.EventEmitter); -module.exports = cmsSockets; + var delay = function (fn, time) { + var defer = q.defer(); + setTimeout( function () { + fn(); + defer.resolve(); + }, time ); + return defer.promise; + }; + + var delayedSocketPush = function(socket, time){ + return delay( function (msg) { + socket.emit( 'msg', { + datetime: new Date(), + message: msg, + id: 'Server' + } ); + }, time ); + }; + + //Hold the names of events that this socket server listens for and emits + self.events = { + session: { + pageView: 'cms:session:pageView', + hashChange: 'cms:session:hashChange', + login: 'cms:session:login', + logout: 'cms:session:logout' + }, + server: { + message: 'cms:server:message', + connected: 'cms:server:connect', + disconnected: 'cms:server:disconnect' + }, + client: { + message: 'cms:client:message', + connected: 'cms:client:connect', + disconnected: 'cms:client:disconnect' + } + }; + + + //Store a list of the connected clients + connections = []; + + var serverConfig = { + httpServer: app, + }; + + wsserver = new WebSocketServer(); + wsserver.mount(serverConfig); + + router = new WebSocketRouter(); + router.attachServer(wsserver); + + router.mount('*', 'echo-protocol', function(request) { + console.log('mounted to echo protocol'); + var conn = request.accept(request.origin); + conn.on('message', function(message) { + console.log('routed message', message); + }); + conn.send('hey'); + }); + + router.mount('*', 'update-protocol', function(request) { + console.log('mounted to update protocol'); + var conn = request.accept(request.origin); + conn.on('message', function(message) { + console.log('update all the things', message); + }); }); + + util.inherits(cmsSockets, events.EventEmitter); + +}; diff --git a/routes/models/user.js b/routes/models/user.js index f40eb34..1f7e6cb 100644 --- a/routes/models/user.js +++ b/routes/models/user.js @@ -65,7 +65,7 @@ UserSchema.method( 'findOrCreate', function (profile, fn) { UserSchema.method( 'findByUsername', function (username, fn) { console.warn( 'findByUsername', username ); - this.find( {username: username}, function (err, data) { + UserSchema.find( {username: username}, function (err, data) { if (err) { fn( false, err ); } diff --git a/server.js b/server.js index cc22780..7aa4c8c 100755 --- a/server.js +++ b/server.js @@ -56,10 +56,6 @@ var cmsRoutes = require('./routes/cms-routes'); cmsRoutes.mount(config, app); -var webapp = http.createServer(app).listen(config.port || process.env.PORT, function () { - util.log('App listening on port: ' + config.port + ''.verbose); - util.log(util.inspect(config, {colors: true})); -}); diff --git a/test/routes/cms-passport-spec.js b/test/routes/cms-passport-spec.js index 530ee48..88f2972 100644 --- a/test/routes/cms-passport-spec.js +++ b/test/routes/cms-passport-spec.js @@ -13,7 +13,7 @@ define([ var app = express(); var config = JSON.parse(fs.readFileSync(process.cwd() + '/config/config.json')); - config.port = 9191 + config.port = 9191; cmsPassport(config, app); @@ -39,7 +39,7 @@ define([ this.skip(); var dfd = this.async(); request(app) - .post('/register') + .post('/auth/register') .send({ "username": Date.now() + "test@email.com", "email": Date.now() + "test@email.com", @@ -53,17 +53,21 @@ define([ .expect(201, dfd.resolve()); }, 'POST - /login - should return user on successful login': function () { - this.skip(); var dfd = this.async(); var validUser = { - username: 'test@email.com', + username: 'test@gmail.com', password: 'test' }; request(app) - .post('/login') + .post('/auth/login') .send(validUser) .expect("Content-Type", /json/) - .expect(200, dfd.resolve); + .expect(200) + .end(function(err, res){ + if (err) {throw err;} + console.log(res.body); + dfd.callback(res); + }); } }); }); diff --git a/www/account.ejs b/www/account.ejs index d69ad21..b6f1c69 100644 --- a/www/account.ejs +++ b/www/account.ejs @@ -1,3 +1,20 @@ + <% layout('layout') -%> +

Username: <%= user.username %>

-

Email: <%= user.email %>

\ No newline at end of file +

Email: <%= user.email %>

+ +
+ + +
+ +<%= user %> diff --git a/www/index.html b/www/index.html index fd8dc8c..3e9733e 100644 --- a/www/index.html +++ b/www/index.html @@ -1,8 +1,53 @@ - + + + + + Passport-Local Example + + + + + + + + +
+ +
+

Bootstrap starter template

+

Use this document as a way to quickly start any new project.
All you get is this text and a mostly barebones HTML document.

+
+ +
+ \ No newline at end of file +window.onload = function() { + var ws = new WebSocket('ws://localhost:8181', 'echo-protocol'); + ws.onopen = function() { + console.log('opened'); + }; + ws.onmessage = function(event) { + console.warn('ws-event', event); + }; +}; + + + diff --git a/www/layout.ejs b/www/layout.ejs index 4fb627b..7a5c7fc 100644 --- a/www/layout.ejs +++ b/www/layout.ejs @@ -1,4 +1,3 @@ - @@ -9,8 +8,42 @@ -
- <%- body %> + + +
+ <%- body %> + + +
+ + diff --git a/www/login.ejs b/www/login.ejs index 0e87566..13c98df 100644 --- a/www/login.ejs +++ b/www/login.ejs @@ -2,24 +2,9 @@ <% layout('layout') -%>
-
-
- - -
-
- - -
-
- -
-
-