diff --git a/package.json b/package.json
index fe2f900..e3e4ba3 100755
--- a/package.json
+++ b/package.json
@@ -32,7 +32,7 @@
"emailjs": "~0.3.6",
"express": "~3.4.6",
"http-proxy": "^1.3.0",
- "jps-ds": "0.0.1",
+ "jps-ds": "~0.0.2",
"jquery": "~2.1.0",
"jquery-file-upload-middleware": "~0.1.1",
"jshint-stylish": "~0.1.5",
diff --git a/routes/rest.js b/routes/rest.js
index ca2d61d..d3a3da1 100755
--- a/routes/rest.js
+++ b/routes/rest.js
@@ -41,12 +41,18 @@ var MESSAGES = {
USER_REGISTRATION_EXISTS: 'User already in exists.'
};
-
-
var DS = require('jps-ds').DS;
-
var _ds = new DS({
- host: 'localhost/angular-cms'
+ host: 'angularcms:angularcms@paulo.mongohq.com:10089/app19632340',
+ models: {
+ 'users': { username: String, email: String, password: String, active: Boolean, meta: Object, token: String, created: Date, updated: Date },
+ 'uploads': { title: String, body: String, image: String, path: String, filename: String, meta: Object, created: Date, updated:Date, userid: String},
+ 'posts': { title: String, body: String, image: String, published: Boolean, created: Date, updated: Date, status: String, userid: String, meta: Object},
+ 'pages': { title: String, body: String, image: String, published: Boolean, created: Date, updated: Date, status: String, userid: String, meta: Object},
+ 'themes': { },
+ 'widgets': { title: String, body: String, path: String, filename: String, meta: Object, created: Date, updated:Date, userid: String, active: Boolean},
+ 'plugins': { title: String, body: String, path: String, filename: String, meta: Object, created: Date, updated:Date, userid: String, active: Boolean}
+ }
});
function delay(ms, value) {
@@ -121,6 +127,7 @@ var RestResource = {
message: 'REST API Server ' + RestResource.useversion
});
},
+
//### v1index
//I handle displaying a message with the version for v1 index.
v1index: function (req, res, next) {
@@ -130,117 +137,7 @@ var RestResource = {
res.json(JSON.parse(body));
});
},
- //### v1get
- //I handle forwarding requests to the www.myappmatrix.com v1 api server and handling the results.
- v1get: function (req, res, next) {
- var url = RestResource.urls[RestResource.useversion] + '/Api/getall/' + req.param('model') + '?appid=' + req.param('appid');
-
- console.log('URL', url.debug);
-
- var options = {
- url: url,
- qs: {
- appid: req.param('appid')
- },
- headers: {
- Authorization: 'Basic: bXk6ZnJlZA=='
- }
- };
-
- if (req.param('appid')) {
- options.qs['appid'] = String(req.param('appid'));
- }
- request(options, function (error, response, body) {
- if (!error) {
- try {
- res.json(JSON.parse(body).results);
- } catch (e) {
- console.log(e);
- res.json(Array({
- status: false,
- message: 'There was an error parsing the data.'
- }));
- }
- }
- });
- },
- //### v1method
- //I handle forwarding method requests to a v1 api server and handling the results.
- v1method: function (req, res, next) {
- var url = RestResource.urls[RestResource.useversion] + '/' + req.param('method');
-
- var options = {
- url: url,
- method: 'GET',
- headers: {
- Authorization: 'Basic: bXk6ZnJlZA=='
- }
- };
-
- options.qs = {}
-
- if (req.param('appid')) {
- options.qs['appid'] = String(req.param('appid'));
- }
- request(options, function (error, response, body) {
- if (!error) {
- try {
- res.json(JSON.parse(body).results);
- } catch (e) {
- console.log(e);
- res.json(Array({
- status: false,
- message: 'There was an error parsing the data.'
- }));
- }
- }
- });
- },
- //### v1add
- //I handle forwarding post requests to a v1 api server.
- v1add: function (req, res, next) {
- RestResource.version = 'v1';
-
- var url = RestResource.urls[RestResource.useversion] + '/' + req.param('collection');
- var method = 'POST';
- if (req.param('id')) {
- method = 'PUT';
- url += '/' + req.param('id');
- }
-
- var options = {
- url: url,
- method: method,
- json: req.body,
- headers: {
- Authorization: 'Basic: bXk6ZnJlZA=='
- }
- };
-
- options.qs = {}
-
- if (req.param('appid')) {
- options.qs['appid'] = String(req.param('appid'));
- }
-
- console.log(url);
-
- request(options, function (error, response, body) {
- if (!error) {
- try {
-
- res.json(body);
- } catch (e) {
- console.log(e);
- res.json(Array({
- status: false,
- message: 'There was an error parsing the data.'
- }));
- }
- }
- });
- },
//### v2index
//I handle displaying a message for the v2 api index.
v2index: function (req, res, next) {
@@ -374,7 +271,7 @@ var RestResource = {
insert: function (collection, data) {
console.log(data);
var deferred = new Deferred();
- //Open db
+
var db = new mongo.Db(config.db.name, new mongo.Server(config.db.host, config.db.port, {safe: false}));
db.open(function (err, db) {
db.collection('users', function (err, collection) {
@@ -589,155 +486,33 @@ var RestResource = {
//### get
//I handle gathering records dynamically from a call to the v2 api.
get: function (req, res, next) {
- var query = req.query.query ? JSON.parse(req.query.query) : {};
- var self = this;
- // Providing an id overwrites giving a query in the URL
- if (req.params.id) {
- query = {
- '_id': new BSON.ObjectID(req.params.id)
- };
- }
- //Pass a appid param to get all records for that appid
- if (req.param('appid')) {
- query['appid'] = String(req.param('appid'));
- }
- var options = req.params.options || {};
- //Test array of legal query params
- var test = ['limit', 'sort', 'fields', 'skip', 'hint', 'explain', 'snapshot', 'timeout'];
- //loop and test
- for (o in req.query) {
- if (test.indexOf(o) >= 0) {
- options[o] = req.query[o];
- }
- }
- //Log for interal usage
- console.log('query', query, 'options', options);
- //new database instance
- var db = new mongo.Db(req.params.db, new mongo.Server(config.db.host, config.db.port, {
- auto_reconnect: true,
- safe: true
- }));
- //open database
- db.open(function (err, db) {
- if (err) {
- console.log(err);
- } else {
- //prep collection
- db.collection(req.params.collection, function (err, collection) {
- //query
- collection.find(query, options, function (err, cursor) {
- cursor.toArray(function (err, docs) {
- console.log(docs);
- if (err) {
- console.log(err);
- } else {
- var result = [];
- if (req.params.id) {
- if (docs.length > 0) {
- result = docs[0];
- res.header('Content-Type', 'application/json');
- res.jsonp(200, result);
- } else {
- res.jsonp(404, 'Not found');
- //res.send(404);
- }
- } else {
- docs.forEach(function (doc) {
- result.push(doc);
- });
- res.header('Content-Type', 'application/json');
- res.jsonp(200, result);
- }
- db.close();
- }
- });
- });
- });
- }
+ console.warn('find all', req.params.collection);
+ _ds.findAll(req.params.collection).then(function(data){
+ res.send(data);
+ }, function(err){
+ res.send(err);
});
},
//### add
//I handle adding a record to the database.
add: function (req, res, next) {
- var data = req.body;
- var results = [];
- var response = {};
-
- if (data) {
- var db = new mongo.Db(req.params.db, new mongo.Server(config.db.host, config.db.port, {
- auto_reconnect: true,
- safe: true
- }));
- db.open(function (err, db) {
- if (err) {
- console.log(err);
- } else {
- db.collection(req.params.collection, function (err, collection) {
- collection.count(function (err, count) {
- console.log("There are " + count + " records.");
- });
- });
-
- db.collection(req.params.collection, function (err, collection) {
- //Check if the posted data is an array, if it is, then loop and insert each document
- if (data.length) {
- //insert all docs
- for (var i = 0; i < data.length; i++) {
- var obj = data[i];
- console.log(obj);
- collection.insert(obj, function (err, docs) {
- results.push(obj);
- });
- }
- response.results = results;
- db.close();
- res.header('Content-Type', 'application/json');
- res.jsonp(200, response);
- } else {
- collection.insert(req.body, function (err, docs) {
- db.close();
- if (!err) {
- response.status = 'ok';
- response.data = docs[0];
- //res.header('Location', '/' + req.params.db + '/' + req.params.collection + '/' + docs[0]._id.toHexString());
- res.header('Content-Type', 'application/json');
- res.send(response, 201);
-
- }
- });
- }
- });
- }
- });
- } else {
- res.header('Content-Type', 'application/json');
- res.send('{"ok":0}', 200);
- }
+ _ds.create(req.params.collection, req.body).then(function(data){
+ console.warn( 'create', data);
+ res.send(data);
+ }, function(err){
+ res.send(err);
+ });
},
//### edit
//I handle
edit: function (req, res, next) {
- var spec = {
- '_id': new BSON.ObjectID(req.params.id)
- };
- var db = new mongo.Db(req.params.db, new mongo.Server(config.db.host, config.db.port, {
- 'auto_reconnect': true,
- 'safe': true
- }));
-
- console.log('Upating: ' + JSON.stringify(req.body).warn);
-
-
- db.open(function (err, db) {
- db.collection(req.params.collection, function (err, collection) {
- collection.update(spec, req.body, true, function (err, docs) {
- res.header('Location', '/' + req.params.db + '/' + req.params.collection + '/' + req.params.id);
- res.header('Content-Type', 'application/json');
- res.send('{"ok":1}');
- db.close();
- console.log('Location', '/' + req.params.db + '/' + req.params.collection + '/' + req.params.id);
- });
- });
+ var data = req.body;
+ delete data._id;
+ _ds.update(req.params.collection, req.params.id, data).then(function(data){
+ console.warn(data);
+ res.send(data);
+ }, function(err){
+ res.send(err);
});
},
//### view
@@ -747,27 +522,11 @@ var RestResource = {
//### destroy
//I handle
destroy: function (req, res, next) {
- var params = {
- _id: new BSON.ObjectID(req.params.id)
- };
- console.log('Delete by id ' + req.params);
- var db = new mongo.Db(req.params.db, new mongo.Server(config.db.host, config.db.port, {
- auto_reconnect: true,
- safe: true
- }));
- db.open(function (err, db) {
- db.collection(req.params.collection, function (err, collection) {
- console.log('found ', collection.collectionName, params);
- collection.remove(params, function (err, docs) {
- if (!err) {
- res.header('Content-Type', 'application/json');
- res.send('{"ok":1}');
- db.close();
- } else {
- console.log(err);
- }
- });
- });
+ _ds.destroy(req.params.collection, req.params.id).then(function(data){
+ console.warn(data);
+ res.send(data);
+ }, function(err){
+ res.send(err);
});
},
//### cloudupload
@@ -824,9 +583,8 @@ var RestResource = {
//### v2 API
//v2 mongo rest api
app.get('/api/v2', RestResource.v2index);
-app.post('/api/v1/imagecrop', RestResource.imageCrop);
+app.post('/api/v2/imagecrop', RestResource.imageCrop);
app.post('/api/v2/cloudupload', RestResource.cloudupload);
-
app.post('/api/v2/upload', RestResource.upload);
//Always users table
@@ -834,7 +592,7 @@ app.post('/api/v2/users/login', bodyParser.json(), RestResource.login);
app.post('/api/v2/users/register', bodyParser.json(), RestResource.register);
app.post('/api/v2/users/session', bodyParser.json(), RestResource.session);
-
+//Dynamic REST
app.get('/api/v2/:db/:collection/:id?', RestResource.get);
app.post('/api/v2/:db/:collection', bodyParser.json(), RestResource.add);
app.put('/api/v2/:db/:collection/:id', bodyParser.json(), RestResource.edit);
@@ -842,11 +600,9 @@ app.delete('/api/v2/:db/:collection/:id', RestResource.destroy);
//Readme
-
var markdown = require("markdown").markdown;
app.get('/api/v2/README', function (res, req) {
var localPath = __dirname + '/../README.md';
-
fs.readFile(localPath, 'utf8', function (err, data) {
if (err) {
req.end('There was an error.');
@@ -859,7 +615,6 @@ app.get('/api/v2/README', function (res, req) {
req.end(data);
}
console.log(data);
-
});
});
/* ======================[ @TODO: Other Rest Utility Methods ]====================== */
From 174637e97904f42ff1ff09fce5356ccf835cc5e7 Mon Sep 17 00:00:00 2001
From: Jonnie Spratley
Date: Thu, 4 Dec 2014 15:54:12 -0800
Subject: [PATCH 04/39] fixed spec
---
test/spec/controllers/pages.coffee | 27 +++++++++++++++------------
1 file changed, 15 insertions(+), 12 deletions(-)
diff --git a/test/spec/controllers/pages.coffee b/test/spec/controllers/pages.coffee
index 7639a2d..021985f 100644
--- a/test/spec/controllers/pages.coffee
+++ b/test/spec/controllers/pages.coffee
@@ -2,18 +2,21 @@
describe 'Controller: PagesCtrl', () ->
- # load the controller's module
- beforeEach module 'angularCmsApp'
+ # load the controller's module
+ beforeEach module 'angularCmsApp'
- PagesCtrl = {}
- scope = {}
+ PagesCtrl = {}
+ scope = {}
- # Initialize the controller and a mock scope
- beforeEach inject ($controller, $rootScope) ->
- scope = $rootScope.$new()
- PagesCtrl = $controller 'PagesCtrl', {
- $scope: scope
- }
+ # Initialize the controller and a mock scope
+ beforeEach inject ($controller, $rootScope, $injector) ->
+ scope = $rootScope.$new()
+ PagesCtrl = $controller 'PagesCtrl', {
+ $scope: scope
+ $log: $injector.get('$log')
+ pages: []
+ DataService: $injector.get('DataService')
+ }
- it 'should attach a list of awesomeThings to the scope', () ->
- expect(scope.awesomeThings.length).toBe 3
+ it 'should attach a list of awesomeThings to the scope', () ->
+ expect(scope.awesomeThings.length).toBe 3
From b86b0ff18bdb24075ff1a1fa159bcbc9e98a5f10 Mon Sep 17 00:00:00 2001
From: Jonnie Spratley
Date: Sat, 6 Dec 2014 00:56:26 +0000
Subject: [PATCH 05/39] updated git ignore
---
.gitignore | 1 +
1 file changed, 1 insertion(+)
diff --git a/.gitignore b/.gitignore
index e979917..9791eff 100755
--- a/.gitignore
+++ b/.gitignore
@@ -18,3 +18,4 @@ coverage/
atlassian-ide-plugin.xml
docs
dist
+.c9
\ No newline at end of file
From 68bf1be4e37ee7c8aea257a9227278dffd28e28c Mon Sep 17 00:00:00 2001
From: Jonnie Spratley
Date: Sat, 6 Dec 2014 14:24:35 -0800
Subject: [PATCH 06/39] updated readme
---
README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/README.md b/README.md
index 58a3d01..7cd73ec 100755
--- a/README.md
+++ b/README.md
@@ -11,6 +11,8 @@ This is a boilerplate CMS built with Angular, Twitter Bootstrap and Node; it is
[![Coverage Status](https://coveralls.io/repos/jonniespratley/angular-cms/badge.png)](https://coveralls.io/r/jonniespratley/angular-cms)[![Dependency Status](https://david-dm.org/jonniespratley/angular-cms.svg)](https://david-dm.org/jonniespratley/angular-cms)
+[![Dependency Status](https://david-dm.org/jonniespratley/angular-cms.svg)](https://david-dm.org/jonniespratley/angular-cms)
+
### Technologies
Some featured technologies used in this project include the following:
From e91eb0463a1b01e090ac92cdfce4b93e8489580b Mon Sep 17 00:00:00 2001
From: Jonnie Spratley
Date: Sat, 6 Dec 2014 15:21:36 -0800
Subject: [PATCH 07/39] added passport
---
app/scripts/controllers/users.coffee | 6 +-
config/config.json | 2 +
package.json | 219 +++++-----
routes/cms-auth.js | 1 +
routes/rest.js | 578 +++++++++------------------
server.js | 78 +---
6 files changed, 311 insertions(+), 573 deletions(-)
create mode 100644 routes/cms-auth.js
diff --git a/app/scripts/controllers/users.coffee b/app/scripts/controllers/users.coffee
index fe81cbc..f1903ec 100644
--- a/app/scripts/controllers/users.coffee
+++ b/app/scripts/controllers/users.coffee
@@ -10,13 +10,13 @@ angular.module('angularCmsApp').controller('UsersCtrl', ($scope, DataService) ->
username: null
email: null
password: null
- role: null
+ role: 'member'
created: new Date()
modified: new Date()
metadata:
avatar: ''
name: null
- aboue: null
+ about: null
#Hold the users
$scope.users = []
@@ -61,4 +61,4 @@ angular.module('angularCmsApp').controller('UsersCtrl', ($scope, DataService) ->
$('#user-modal').modal('hide')
)
-)
\ No newline at end of file
+)
diff --git a/config/config.json b/config/config.json
index 0dd4674..ae12d79 100644
--- a/config/config.json
+++ b/config/config.json
@@ -1,5 +1,7 @@
{
+ "host": "http://localhost",
"port": 8181,
+ "apiBase": "/api/v2",
"version": "v2",
"security": {"salt": ""},
"db": {
diff --git a/package.json b/package.json
index e3e4ba3..853cc0f 100755
--- a/package.json
+++ b/package.json
@@ -1,110 +1,113 @@
{
- "name": "angular-cms",
- "version": "0.0.1",
- "description": "This is a lightweight CMS built with Angular.js, Twitter Bootstrap and Node.js.",
- "author": "Jonnie Spratley",
- "license": "MIT",
- "readmeFilename": "README.md",
- "homepage": "https://github.com/jonniespratley/angular-cms",
- "main": "Gruntfile.js",
- "bugs": {
- "url": "https://github.com/jonniespratley/angular-cms/issues"
- },
- "directories": {
- "doc": "docs",
- "test": "test"
- },
- "repository": {
- "type": "git",
- "url": "https://github.com/jonniespratley/angular-cms.git"
- },
- "keywords": [
- "angular",
- "grunt",
- "angular-cms",
- "yeoman"
- ],
- "dependencies": {
- "body-parser": "^1.9.3",
- "body-parser-json": "^1.9.2",
- "colors": "~0.6.2",
- "easyimage": "~0.1.6",
- "emailjs": "~0.3.6",
- "express": "~3.4.6",
- "http-proxy": "^1.3.0",
- "jps-ds": "~0.0.2",
- "jquery": "~2.1.0",
- "jquery-file-upload-middleware": "~0.1.1",
- "jshint-stylish": "~0.1.5",
- "json-proxy": "^0.3.0",
- "logfmt": "~0.18.1",
- "markdown": "~0.5.0",
- "mongodb": "*",
- "mongoose": "*",
- "promised-io": "~0.3.4",
- "request": "~2.34.0",
- "socket.io": "~0.9.16"
- },
- "devDependencies": {
- "chai": "^1.10.0",
- "connect-proxy": "~1.0.2",
- "grunt": "~0.4.4",
- "grunt-angular-templates": "~0.5.1",
- "grunt-autoprefixer": "~0.4.0",
- "grunt-bower-install": "~0.8.0",
- "grunt-concurrent": "~0.4.1",
- "grunt-connect-proxy": "~0.1.10",
- "grunt-contrib-clean": "^0.6.0",
- "grunt-contrib-coffee": "~0.7.0",
- "grunt-contrib-compass": "~0.6.0",
- "grunt-contrib-concat": "~0.3.0",
- "grunt-contrib-connect": "~0.5.0",
- "grunt-contrib-copy": "~0.4.1",
- "grunt-contrib-cssmin": "~0.7.0",
- "grunt-contrib-htmlmin": "~0.1.3",
- "grunt-contrib-jasmine": "~0.5.2",
- "grunt-contrib-jshint": "~0.7.1",
- "grunt-contrib-less": "~0.9.0",
- "grunt-contrib-uglify": "~0.2.0",
- "grunt-contrib-watch": "~0.5.2",
- "grunt-google-cdn": "^0.4.3",
- "grunt-jasmine-node": "~0.1.0",
- "grunt-karma": "^0.9.0",
- "grunt-karma-coveralls": "^2.5.1",
- "grunt-mocha-test": "^0.12.4",
- "grunt-newer": "~0.5.4",
- "grunt-ngdocs": "~0.1.7",
- "grunt-ngmin": "0.0.3",
- "grunt-protractor-runner": "^1.1.0",
- "grunt-protractor-webdriver": "^0.1.8",
- "grunt-rev": "~0.1.0",
- "grunt-svgmin": "~0.2.0",
- "grunt-usemin": "~2.0.2",
- "jasmine-core": "^2.1.2",
- "jasmine-node": "~1.11.0",
- "jasmine-reporters": "^1.0.1",
- "karma": "^0.12.28",
- "karma-chrome-launcher": "^0.1.5",
- "karma-coverage": "^0.2.6",
- "karma-jasmine": "^0.3.1",
- "karma-ng-html2js-preprocessor": "~0.1",
- "karma-ng-scenario": "~0.1",
- "karma-phantomjs-launcher": "~0.1",
- "load-grunt-tasks": "~0.2.0",
- "mocha": "^2.0.1",
- "protractor": "^1.0.0",
- "supertest": "^0.15.0",
- "time-grunt": "~0.2.1"
- },
- "peerDependencies": {
- "grunt": "0.4.x",
- "karma": "~0.12.0"
- },
- "engines": {
- "node": ">=0.10.0"
- },
- "scripts": {
- "test": "grunt test",
- "start": "node web.js"
- }
+ "name": "angular-cms",
+ "version": "0.0.1",
+ "description": "This is a lightweight CMS built with Angular.js, Twitter Bootstrap and Node.js.",
+ "author": "Jonnie Spratley",
+ "license": "MIT",
+ "readmeFilename": "README.md",
+ "homepage": "https://github.com/jonniespratley/angular-cms",
+ "main": "Gruntfile.js",
+ "bugs": {
+ "url": "https://github.com/jonniespratley/angular-cms/issues"
+ },
+ "directories": {
+ "doc": "docs",
+ "test": "test"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/jonniespratley/angular-cms.git"
+ },
+ "keywords": [
+ "angular",
+ "grunt",
+ "angular-cms",
+ "yeoman"
+ ],
+ "dependencies": {
+ "body-parser": "^1.9.3",
+ "body-parser-json": "^1.9.2",
+ "colors": "~0.6.2",
+ "easyimage": "~0.1.6",
+ "emailjs": "~0.3.6",
+ "express": "~3.4.6",
+ "http-proxy": "^1.3.0",
+ "jps-ds": "~0.0.2",
+ "jquery": "~2.1.0",
+ "jquery-file-upload-middleware": "~0.1.1",
+ "jshint-stylish": "~0.1.5",
+ "json-proxy": "^0.3.0",
+ "logfmt": "~0.18.1",
+ "markdown": "~0.5.0",
+ "mongodb": "*",
+ "mongoose": "*",
+ "npmlog": "^0.1.1",
+ "passport": "^0.2.1",
+ "passport-google": "^0.3.0",
+ "promised-io": "~0.3.4",
+ "request": "~2.34.0",
+ "socket.io": "~0.9.16"
+ },
+ "devDependencies": {
+ "chai": "^1.10.0",
+ "connect-proxy": "~1.0.2",
+ "grunt": "~0.4.4",
+ "grunt-angular-templates": "~0.5.1",
+ "grunt-autoprefixer": "~0.4.0",
+ "grunt-bower-install": "~0.8.0",
+ "grunt-concurrent": "~0.4.1",
+ "grunt-connect-proxy": "~0.1.10",
+ "grunt-contrib-clean": "^0.6.0",
+ "grunt-contrib-coffee": "~0.7.0",
+ "grunt-contrib-compass": "~0.6.0",
+ "grunt-contrib-concat": "~0.3.0",
+ "grunt-contrib-connect": "~0.5.0",
+ "grunt-contrib-copy": "~0.4.1",
+ "grunt-contrib-cssmin": "~0.7.0",
+ "grunt-contrib-htmlmin": "~0.1.3",
+ "grunt-contrib-jasmine": "~0.5.2",
+ "grunt-contrib-jshint": "~0.7.1",
+ "grunt-contrib-less": "~0.9.0",
+ "grunt-contrib-uglify": "~0.2.0",
+ "grunt-contrib-watch": "~0.5.2",
+ "grunt-google-cdn": "^0.4.3",
+ "grunt-jasmine-node": "~0.1.0",
+ "grunt-karma": "^0.9.0",
+ "grunt-karma-coveralls": "^2.5.1",
+ "grunt-mocha-test": "^0.12.4",
+ "grunt-newer": "~0.5.4",
+ "grunt-ngdocs": "~0.1.7",
+ "grunt-ngmin": "0.0.3",
+ "grunt-protractor-runner": "^1.1.0",
+ "grunt-protractor-webdriver": "^0.1.8",
+ "grunt-rev": "~0.1.0",
+ "grunt-svgmin": "~0.2.0",
+ "grunt-usemin": "~2.0.2",
+ "jasmine-core": "^2.1.2",
+ "jasmine-node": "~1.11.0",
+ "jasmine-reporters": "^1.0.1",
+ "karma": "^0.12.28",
+ "karma-chrome-launcher": "^0.1.5",
+ "karma-coverage": "^0.2.6",
+ "karma-jasmine": "^0.3.1",
+ "karma-ng-html2js-preprocessor": "~0.1",
+ "karma-ng-scenario": "~0.1",
+ "karma-phantomjs-launcher": "~0.1",
+ "load-grunt-tasks": "~0.2.0",
+ "mocha": "^2.0.1",
+ "protractor": "^1.0.0",
+ "supertest": "^0.15.0",
+ "time-grunt": "~0.2.1"
+ },
+ "peerDependencies": {
+ "grunt": "0.4.x",
+ "karma": "~0.12.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "scripts": {
+ "test": "grunt test",
+ "start": "node web.js"
+ }
}
diff --git a/routes/cms-auth.js b/routes/cms-auth.js
new file mode 100644
index 0000000..b7944a5
--- /dev/null
+++ b/routes/cms-auth.js
@@ -0,0 +1 @@
+var passport = require('passport'), GoogleStrategy = require('passport-google').Strategy, log = require('npmlog');
var cmsAuth = function (options, app) {
if (!app) {
throw new Error('Must provide express application!');
}
console.warn('cmsAuth', options);
var baseUrl = options.host + ':' + options.port;
var authed = function(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
res.json(503, {
error: "service_unavailable", reason: "authentication_unavailable"
});
}
};
//Setup
app.use(passport.initialize());
app.use(passport.session());
app.all('*', function(req, res, next){
console.warn('cmsAuth', req.params);
next();
});
app.get('/api/user', authed, function(req, res){
res.json(req.user);
});
app.get('/auth/google/:return?', passport.authenticate('google', { successRedirect: baseUrl }) );
app.get('/auth/logout', function(req, res){
req.logout();
res.redirect(options.apiBase);
});
passport.use(new GoogleStrategy({
returnURL: baseUrl + '/auth/google/return',
realm: baseUrl
},
function (identifier, profile, done) {
profile.identifier = identifier;
return done(null, profile);
}));
passport.serializeUser(function (user, done) {
done(null, user.identifier);
});
passport.deserializeUser(function (id, done) {
done(null, {identifier: id});
});
return app;
};
module.exports = cmsAuth;
\ No newline at end of file
diff --git a/routes/rest.js b/routes/rest.js
index d3a3da1..6045035 100755
--- a/routes/rest.js
+++ b/routes/rest.js
@@ -16,23 +16,19 @@
*/
//## Required Modules
-var mongo = require('mongodb');
-var mongoose = require('mongoose');
var crypto = require('crypto');
-var Server = mongo.Server;
var path = require('path');
-var Db = mongo.Db;
-var BSON = mongo.BSONPure;
var express = require('express');
-var fs = require('fs');
-var app = express();
+var fs = require('fs'), util = require('util');
var request = require('request');
+var easyimage = require('easyimage');
var upload = require('jquery-file-upload-middleware');
-var easyimg = require('easyimage');
var sio = require('socket.io');
var Deferred = require("promised-io/promise").Deferred;
var when = require("promised-io/promise");
var bodyParser = require('body-parser');
+var markdown = require("markdown").markdown;
+
//Strings for results
var MESSAGES = {
@@ -45,13 +41,79 @@ var DS = require('jps-ds').DS;
var _ds = new DS({
host: 'angularcms:angularcms@paulo.mongohq.com:10089/app19632340',
models: {
- 'users': { username: String, email: String, password: String, active: Boolean, meta: Object, token: String, created: Date, updated: Date },
- 'uploads': { title: String, body: String, image: String, path: String, filename: String, meta: Object, created: Date, updated:Date, userid: String},
- 'posts': { title: String, body: String, image: String, published: Boolean, created: Date, updated: Date, status: String, userid: String, meta: Object},
- 'pages': { title: String, body: String, image: String, published: Boolean, created: Date, updated: Date, status: String, userid: String, meta: Object},
- 'themes': { },
- 'widgets': { title: String, body: String, path: String, filename: String, meta: Object, created: Date, updated:Date, userid: String, active: Boolean},
- 'plugins': { title: String, body: String, path: String, filename: String, meta: Object, created: Date, updated:Date, userid: String, active: Boolean}
+ 'groups': {
+ title: String,
+ body: String,
+ slug: String,
+ created: Date,
+ updated: Date
+ },
+ 'users': {
+ username: String,
+ email: String,
+ password: String,
+ active: Boolean,
+ meta: Object,
+ token: String,
+ created: Date,
+ updated: Date
+ },
+ 'uploads': {
+ title: String,
+ body: String,
+ image: String,
+ path: String,
+ filename: String,
+ meta: Object,
+ created: Date,
+ updated: Date,
+ userid: String
+ },
+ 'posts': {
+ title: String,
+ body: String,
+ image: String,
+ published: Boolean,
+ created: Date,
+ updated: Date,
+ status: String,
+ userid: String,
+ meta: Object
+ },
+ 'pages': {
+ title: String,
+ body: String,
+ image: String,
+ published: Boolean,
+ created: Date,
+ updated: Date,
+ status: String,
+ userid: String,
+ meta: Object
+ },
+ 'themes': {},
+ 'widgets': {
+ title: String,
+ body: String,
+ path: String,
+ filename: String,
+ meta: Object,
+ created: Date,
+ updated: Date,
+ userid: String,
+ active: Boolean
+ },
+ 'plugins': {
+ title: String,
+ body: String,
+ path: String,
+ filename: String,
+ meta: Object,
+ created: Date,
+ updated: Date,
+ userid: String,
+ active: Boolean
+ }
}
});
@@ -78,15 +140,6 @@ var hashPassword = function (pass, salt) {
//## Configuration
-//### Cloud Files Config
-var cloudfilesConfig = {
- auth: {
- username: '',
- apiKey: '',
- host: 'lon.auth.api.rackspacecloud.com'
- },
- servicenet: true
-};
//### Colors Config
var colors = require('colors');
@@ -114,12 +167,15 @@ var RestResource = {
this.config = config;
return this;
},
-
useversion: 'v2',
urls: {
v1: 'https://www..com',
v2: '/api/v2/'
},
+ log: function(){
+ console.log(util.inspect(arguments, {colors: true}));
+
+ },
//### index
//I handle displaying a message with the version for this api.
index: function (req, res, next) {
@@ -127,44 +183,6 @@ var RestResource = {
message: 'REST API Server ' + RestResource.useversion
});
},
-
- //### v1index
- //I handle displaying a message with the version for v1 index.
- v1index: function (req, res, next) {
- RestResource.useversion = 'v1';
- request(RestResource.urls[RestResource.useversion], function (error, response, body) {
- console.log(error, response, body);
- res.json(JSON.parse(body));
- });
- },
-
- //### v2index
- //I handle displaying a message for the v2 api index.
- v2index: function (req, res, next) {
- RestResource.version = 'v2';
- res.json({
- message: 'REST API Server ' + RestResource.useversion
- });
- },
-
- findOne: function (req, table, query, success, fail) {
- //Open db
- var db = new mongo.Db('angular-cms', new mongo.Server(config.db.host, config.db.port));
- db.open(function (err, db) {
- db.collection(table, function (err, collection) {
- var options = req.params.options || {};
- collection.findOne(query, options, function (err, cursor) {
- if (cursor != null) {
- success(cursor);
- } else {
- err = "No data found!";
- fail(err);
- }
- db.close();
- });
- });
- });
- },
/**
* //### login
//I handle trying to authorized a user with the v1 api server.
@@ -189,25 +207,10 @@ var RestResource = {
console.log('Login Query: ', query);
- var deferred = new Deferred();
-
- var userFound = false;
- RestResource.findOne(req, 'users', query, function (u) {
- userFound = true;
- res.jsonp(200, {
- success: true,
- result: u
- });
-
- }, function (error) {
- userFound = false;
- res.jsonp(404, {
- status: false,
- error: true,
- message: 'Invalid email/password.'
- });
-
-
+ _ds.findOne(req.params.collection, req.params.id).then(function (data) {
+ res.send(data);
+ }, function (err) {
+ res.send(err);
});
@@ -224,70 +227,12 @@ var RestResource = {
query = {
email: req.body.email
};
-
-
data.password = hashPassword(req.body.password, req.body.email),
- console.log(String("Register user").debug, req.body);
-
-
- RestResource.findOne(req, 'users', query, function (u) {
- user = u;
- res.jsonp(404, {
- status: false,
- message: MESSAGES.USER_REGISTRATION_EXISTS
- });
-
- }, function (error) {
- user = null;
- var db = new mongo.Db(config.db.name, new mongo.Server(config.db.host, config.db.port, {safe: true}));
- db.open(function (err, db) {
- db.collection('users', function (err, collection) {
- collection.insert(data, function (err, docs) {
- console.log(err, docs);
- if (!err) {
- res.header('Content-Type', 'application/json');
- res.jsonp(200, {
- status: true,
- message: MESSAGES.USER_REGISTRATION_SUCCESS,
- user: req.body
- });
- } else {
- res.jsonp(404, {
- status: false,
- message: MESSAGES.USER_REGISTRATION_ERROR
- });
- console.log(error.warn);
- }
- db.close();
- });
- });
- });
-
- });
+ console.log(String("Register user").debug, req.body);
},
session: function (req, res, next) {
},
- insert: function (collection, data) {
- console.log(data);
- var deferred = new Deferred();
-
- var db = new mongo.Db(config.db.name, new mongo.Server(config.db.host, config.db.port, {safe: false}));
- db.open(function (err, db) {
- db.collection('users', function (err, collection) {
- collection.insert(data, function (err, docs) {
- console.log(err, docs);
- if (!err) {
- deferred.resolve(true);
- } else {
- deferred.reject(false);
- }
- db.close();
- });
- });
- });
- return deferred.promise;
- },
//### upload
//I handled processing a uploaded file on the v2 server.
upload: function (req, res, next) {
@@ -337,10 +282,6 @@ var RestResource = {
if (err) {
console.error('File Rename Error:', err);
}
- ;
-
- //Upload the original to cloudfiles
- //rackspaceUpload(target_path, target_dir, filename);
//Create the thumb directory
fs.mkdir(thumb_dir, 0777, function (e) {
@@ -361,11 +302,6 @@ var RestResource = {
console.log('easyimg', imgOptions, e);
- //Upload thumb to rackspace
- /*
- rackspaceUpload(thumb_path, thumb_dir, filename, function(results) {
- });
- */
//set the new path on the file
req.files.file.target_dir = target_dir;
@@ -394,112 +330,32 @@ var RestResource = {
});
});
},
- //### imageCrop
- //I handle processing a uploaded image, cropping it and moving it to the proper directory, and uploaded to Rackspace Cloud Files.
- imageCrop: function (req, res, next) {
- var appid = null;
-
- if (req.param('appid')) {
- appid = String(req.param('appid'));
- }
-
- //Handle if dynamic filenames are enabled
- var tmp_filename = req.files.file.name;
- var filename = tmp_filename;
- var tmp_path = req.files.file.path;
- var target_dir = config.uploadsDestDir + '/' + appid + '/';
- var target_path = config.uploadsDestDir + '/' + appid + '/' + filename;
- var thumb_dir = config.uploadsDestDir + '/' + appid + '/thumbnail/';
- var thumb_path = config.uploadsDestDir + '/' + appid + '/thumbnail/' + filename;
-
- //Get the params for cropping an image
- var x1 = req.body.x1, y1 = req.body.y1, x2 = req.body.x2, y2 = req.body.y2, height = req.body.height, width = req.body.width, filepath = target_path;
-
- if (!width) {
- width = 100;
- }
-
- //Dev logger
- console.log(x1, x2, y1, y2, height, width, thumb_path);
- console.log(String('Target Path: ' + target_path).warn);
- console.log(String('Target Dir: ' + target_dir).warn);
- console.log(String('Temp Path: ' + tmp_path).warn);
-
- //Create the directory and move the file to that directory
- fs.mkdir(target_dir, 0777, function (e) {
-
- //Rename the file
- fs.rename(tmp_path, target_path, function (err) {
- if (err) {
- console.error('File Rename Error:', err);
- }
- ;
-
- //Create the thumbnail from the default image
- var imgOptions = {
- src: target_path,
- dst: thumb_path,
- width: width,
- height: height,
- quality: 100,
- x: x1,
- y: y1
- };
-
- //Create the thumb directory and resize the image
- fs.mkdir(thumb_dir, 0777, function (e) {
- //Resize the image
- easyimg.resize(imgOptions, function (e) {
- console.log('easyimg', e);
- });
- });
- //unlink the file
- fs.unlink(tmp_path, function () {
- if (err) {
- console.error('File Unlink Error: ', err);
-
- } else {
-
- //set the new path on the file
- req.files.file.target_dir = target_dir;
- req.files.file.target_path = target_path;
- req.files.file.thumb_path = thumb_path;
- req.files.file.thumb_dir = thumb_dir;
-
- req.files.file.filename = filename;
-
- //build the response object
- var json = {
- status: true,
- filename: filename,
- msg: 'File Uploaded',
- results: req.files,
- appid: appid
- };
- res.send(json);
- }
- });
- });
- });
- },
//### get
//I handle gathering records dynamically from a call to the v2 api.
get: function (req, res, next) {
- console.warn('find all', req.params.collection);
- _ds.findAll(req.params.collection).then(function(data){
- res.send(data);
- }, function(err){
- res.send(err);
- });
+ if (req.param('id')) {
+ console.log('find one', req.params.id);
+ _ds.findOne(req.params.collection, req.params.id).then(function (data) {
+ res.send(data);
+ }, function (err) {
+ res.send(err);
+ });
+ } else {
+ _ds.findAll(req.params.collection).then(function (data) {
+ res.send(data);
+ }, function (err) {
+ res.send(err);
+ });
+ }
},
//### add
//I handle adding a record to the database.
add: function (req, res, next) {
- _ds.create(req.params.collection, req.body).then(function(data){
- console.warn( 'create', data);
+ _ds.create(req.params.collection, req.body).then(function (data) {
+ console.warn('create', data);
res.send(data);
- }, function(err){
+ }, function (err) {
res.send(err);
});
},
@@ -508,10 +364,10 @@ var RestResource = {
edit: function (req, res, next) {
var data = req.body;
delete data._id;
- _ds.update(req.params.collection, req.params.id, data).then(function(data){
+ _ds.update(req.params.collection, req.params.id, data).then(function (data) {
console.warn(data);
res.send(data);
- }, function(err){
+ }, function (err) {
res.send(err);
});
},
@@ -522,108 +378,40 @@ var RestResource = {
//### destroy
//I handle
destroy: function (req, res, next) {
- _ds.destroy(req.params.collection, req.params.id).then(function(data){
+ _ds.destroy(req.params.collection, req.params.id).then(function (data) {
console.warn(data);
res.send(data);
- }, function(err){
+ }, function (err) {
res.send(err);
});
},
- //### cloudupload
- //I handle
- cloudupload: function (req, res, next) {
- var appid = null, results = null;
- if (req.param('appid')) {
- appid = String(req.param('appid'));
- }
-
- console.log(req.files);
-
- },
- /*
- * flavorize - Changes JSON based on flavor in configuration
- */
- flavorize: function (flavor, doc, direction) {
- if (direction == "in") {
- switch (flavor) {
- case "sproutcore":
- delete doc['guid'];
- // only do this in case flavor is set to sproutcore
- break;
- case "nounderscore":
- delete doc['id'];
- // only do this in case flavor is set to sproutcore
- break;
- default:
- break;
- }
- } else {
- switch (flavor) {
- case "sproutcore":
- var guid = doc._id.toHexString();
- delete doc['_id'];
- doc.guid = guid;
- break;
- case "nounderscore":
- var id = doc._id.toHexString();
- delete doc['_id'];
- doc.id = id;
- break;
- default:
- doc._id = doc._id.toHexString();
- break;
+ readme: function (res, req) {
+ var localPath = __dirname + '/../README.md';
+ fs.readFile(localPath, 'utf8', function (err, data) {
+ if (err) {
+ req.end('There was an error.');
+ return console.log(err);
+ } else {
+ req.writeHead(200, {
+ "Content-Type": 'utf8',
+ "Content-Length": data.length
+ });
+ req.end(data);
}
- }
- return doc;
+ console.log(data);
+ });
+ },
+ plugins: function (req, res) {
+ var result = fs.readdir('./app/cms-plugins', function (err, files) {
+ console.log(files);
+ res.header('Content-Type', 'application/json');
+ res.jsonp(200, files);
+ });
}
};
-//# Routes
-
-//### v2 API
-//v2 mongo rest api
-app.get('/api/v2', RestResource.v2index);
-app.post('/api/v2/imagecrop', RestResource.imageCrop);
-app.post('/api/v2/cloudupload', RestResource.cloudupload);
-app.post('/api/v2/upload', RestResource.upload);
-//Always users table
-app.post('/api/v2/users/login', bodyParser.json(), RestResource.login);
-app.post('/api/v2/users/register', bodyParser.json(), RestResource.register);
-app.post('/api/v2/users/session', bodyParser.json(), RestResource.session);
-//Dynamic REST
-app.get('/api/v2/:db/:collection/:id?', RestResource.get);
-app.post('/api/v2/:db/:collection', bodyParser.json(), RestResource.add);
-app.put('/api/v2/:db/:collection/:id', bodyParser.json(), RestResource.edit);
-app.delete('/api/v2/:db/:collection/:id', RestResource.destroy);
-
-
-//Readme
-var markdown = require("markdown").markdown;
-app.get('/api/v2/README', function (res, req) {
- var localPath = __dirname + '/../README.md';
- fs.readFile(localPath, 'utf8', function (err, data) {
- if (err) {
- req.end('There was an error.');
- return console.log(err);
- } else {
- req.writeHead(200, {
- "Content-Type": 'utf8',
- "Content-Length": data.length
- });
- req.end(data);
- }
- console.log(data);
- });
-});
-/* ======================[ @TODO: Other Rest Utility Methods ]====================== */
-
-//### rackspaceUpload
-//Upload a image file and create thumbnail and send to Rackspace Cloud Files.
-function rackspaceUpload(localPath, targetPath, filename, cb) {
-
-};
//### getFile
@@ -659,22 +447,6 @@ function writeFile(localPath, contents) {
});
};
-//### modules
-//Gather all of the files and folders in the app/modules directory
-app.get('/api/v2/modules', function (req, res) {
- var result = fs.readdir('./app/cms-content', function (err, files) {
- console.log(files);
- res.header('Content-Type', 'application/json');
- res.jsonp(200, files);
- });
-});
-
-//Write the pass.json file to the file system
-app.get('/api/v2/smartpass/sign', function (req, res) {
- var result = writeFile(req.params('path'), req.params('contents'));
- res.header('Content-Type', 'application/json');
- res.jsonp(200, result);
-});
var config = {};
@@ -682,48 +454,56 @@ var publicPath = config.publicDir;
var uploadsTmpDir = config.uploadsTmpDir;
var uploadDestDir = config.uploadDestDir;
-
-//Export to public api
-exports.rest = {
- RestResource: RestResource,
- app: app,
- express: express,
- init: function (options) {
-
- console.log('email: admin@email.com '.verbose);
- console.log('password: admin1234'.verbose)
-
- config = options;
-
- /*
- */
- //### Express Config
- //Configure the express app server.
- app.configure(function () {
- app.set("view options", {layout: false, pretty: true});
-
- app.use(express.static(config.staticDir));
- app.use(express.directory(config.publicDir));
-
- app.use(bodyParser.urlencoded({ extended: false }));
- // parse application/json
- app.use(bodyParser.json());
-
- app.use("jsonp callback", true);
- app.use('/api/upload', upload.fileHandler());
-
-
- app.use(function (req, res, next) {
- console.log('%s %s', req.method, req.body, req.url);
- next();
- });
- });
-
-
- app.listen(options.port || process.env.PORT, function () {
- console.log(String('Node.js REST server listening on port: ' + options.port).verbose);
+var cmsRest = function (options) {
+ "use strict";
+
+ var app = express();
+
+ console.warn('cmsRest - options', options);
+ console.log('email: admin@email.com '.verbose);
+ console.log('password: admin1234'.verbose)
+ config = options;
+
+
+ //### Express Config
+ //Configure the express app server.
+ //### modules
+ //Gather all of the files and folders in the app/modules directory
+ app.get(config.apiBase + '/plugins', RestResource.plugins);
+ //# Routes
+ //### v2 API
+ app.get(config.apiBase + '/readme', RestResource.readme);
+ //v2 mongo rest api
+ app.get(config.apiBase, RestResource.index);
+ app.post(config.apiBase + '/upload', RestResource.upload);
+
+ //Always users table
+ app.post(config.apiBase + '/login', bodyParser.json(), RestResource.login);
+ app.post(config.apiBase + '/register', bodyParser.json(), RestResource.register);
+ app.post(config.apiBase + '/session', bodyParser.json(), RestResource.session);
+
+ //Dynamic REST
+ app.get(config.apiBase + '/:collection/:id?', RestResource.get);
+ app.post(config.apiBase + '/:collection', bodyParser.json(), RestResource.add);
+ app.put(config.apiBase + '/:collection/:id', bodyParser.json(), RestResource.edit);
+ app.delete(config.apiBase + '/:collection/:id', RestResource.destroy);
+
+
+ app.configure(function () {
+ app.set("view options", {layout: false, pretty: true});
+ app.use(express.static(config.staticDir));
+ app.use(express.directory(config.publicDir));
+ app.use(bodyParser.urlencoded({extended: false}));
+ app.use(bodyParser.json());
+ app.use("jsonp callback", true);
+ app.use(config.apiBase + '/upload2', upload.fileHandler());
+ app.use(function (req, res, next) {
+ console.warn(req.param('db'), req.param('collection'))
+ console.log('%s %s', req.method, req.body, req.url);
+ next();
});
-
- return app;
- }
+ });
+ return app;
};
+
+module.exports = cmsRest;
diff --git a/server.js b/server.js
index 21d21fe..cfb3314 100755
--- a/server.js
+++ b/server.js
@@ -4,9 +4,9 @@
*/
var fs = require('fs'),
util = require('util'),
- httpProxy = require('http-proxy');
+ httpProxy = require('http-proxy'),
+ colors = require('colors');
-var colors = require('colors');
colors.setTheme({
silly: 'rainbow',
input: 'grey',
@@ -20,19 +20,6 @@ colors.setTheme({
error: 'red'
});
-/*
- console.log("this is an silly".silly);
- console.log("this is an input".input);
- console.log("this is an verbose".verbose);
- console.log("this is an prompt".prompt);
- console.log("this is an info".info);
- console.log("this is an data".data);
- console.log("this is an help".help);
- console.log("this is an debug".debug);
- console.log("this is an error".error);
- console.log("this is a warning".warn);
- */
-
/**
* @TODO - HTTPS Key and Cert
*
@@ -68,17 +55,25 @@ var options = {
* @TODO - Externalize configuration for server and proxy, mongodb
*/
var config = JSON.parse(fs.readFileSync('./config/config.json'));
+var cmsAuth = require('./routes/cms-auth');
+var cmsRest = require('./routes/rest');
+
+var rest = new cmsRest(config);
+var auth = new cmsAuth(config, rest);
+
+auth.listen(config.port || process.env.PORT, function () {
+ console.log(String('Node.js REST server listening on port: ' + config.port).verbose);
+});
-//Dynamic rest server
-var rest = require('./routes/rest').rest;
//Socket server
var socket = require('./routes/socketserver').SocketServer;
//Initialize socket server and rest server
-socket.init(
- rest.init(config)
-);
+socket.init(auth);
+
+
+
//Create proxy server and proxy requests
@@ -115,46 +110,3 @@ proxyServer = httpProxy.createServer(options, function (req, res, proxy) {
//Start the proxy server
proxyServer.listen(options.port);
-
-
-/**
- * Test Email
- */
-var email = require("emailjs");
-var server = email.server.connect({
- user: config.email.username,
- password: config.email.password,
- host: "smtp.gmail.com",
- ssl: false
-});
-
-var message = {
- text: "i hope this works",
- from: "you ",
- to: "jonniespratley ",
- cc: "angular.cms ",
- subject: "testing angular-cms emailjs",
- attachment: [
- {data: "i hope this works!", alternative: true}
- // {path:"path/to/file.zip", type:"application/zip", name:"renamed.zip"}
- ]
-};
-
-// send the message and get a callback with an error or details of the message that was sent
-//server.send(message, function(err, message) { console.log(err || message); });
-
-// you can continue to send more messages with successive calls to 'server.send',
-// they will be queued on the same smtp connection
-
-// or you can create a new server connection with 'email.server.connect'
-// to asynchronously send individual emails instead of a queue
-
-
-/*
- * fs.readFile(req.files.displayImage.path, function (err, data) {
- // ...
- var newPath = __dirname + "/uploads/uploadedFileName";
- fs.writeFile(newPath, data, function (err) {
- res.redirect("back");
- });
- });*/
From 15d488a0f3c7b2d3f6bc3a6742a598ca3124a9c9 Mon Sep 17 00:00:00 2001
From: Jonnie Spratley
Date: Sat, 6 Dec 2014 17:25:35 -0800
Subject: [PATCH 08/39] updated aut
---
config/config.json | 1 +
package.json | 3 +
routes/cms-auth.js | 168 ++++++++++++++++++++++++++++++++++++++++++++-
3 files changed, 171 insertions(+), 1 deletion(-)
diff --git a/config/config.json b/config/config.json
index ae12d79..c71b0f8 100644
--- a/config/config.json
+++ b/config/config.json
@@ -4,6 +4,7 @@
"apiBase": "/api/v2",
"version": "v2",
"security": {"salt": ""},
+ "mongodb": "angularcms:angularcms@paulo.mongohq.com:10089/app19632340",
"db": {
"name": "angular-cms",
"username": "amadmin",
diff --git a/package.json b/package.json
index 853cc0f..ef039a2 100755
--- a/package.json
+++ b/package.json
@@ -28,6 +28,8 @@
"body-parser": "^1.9.3",
"body-parser-json": "^1.9.2",
"colors": "~0.6.2",
+ "connect-flash": "^0.1.1",
+ "cookie-parser": "^1.3.3",
"easyimage": "~0.1.6",
"emailjs": "~0.3.6",
"express": "~3.4.6",
@@ -44,6 +46,7 @@
"npmlog": "^0.1.1",
"passport": "^0.2.1",
"passport-google": "^0.3.0",
+ "passport-local": "^1.0.0",
"promised-io": "~0.3.4",
"request": "~2.34.0",
"socket.io": "~0.9.16"
diff --git a/routes/cms-auth.js b/routes/cms-auth.js
index b7944a5..51f7fb4 100644
--- a/routes/cms-auth.js
+++ b/routes/cms-auth.js
@@ -1 +1,167 @@
-var passport = require('passport'), GoogleStrategy = require('passport-google').Strategy, log = require('npmlog');
var cmsAuth = function (options, app) {
if (!app) {
throw new Error('Must provide express application!');
}
console.warn('cmsAuth', options);
var baseUrl = options.host + ':' + options.port;
var authed = function(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
res.json(503, {
error: "service_unavailable", reason: "authentication_unavailable"
});
}
};
//Setup
app.use(passport.initialize());
app.use(passport.session());
app.all('*', function(req, res, next){
console.warn('cmsAuth', req.params);
next();
});
app.get('/api/user', authed, function(req, res){
res.json(req.user);
});
app.get('/auth/google/:return?', passport.authenticate('google', { successRedirect: baseUrl }) );
app.get('/auth/logout', function(req, res){
req.logout();
res.redirect(options.apiBase);
});
passport.use(new GoogleStrategy({
returnURL: baseUrl + '/auth/google/return',
realm: baseUrl
},
function (identifier, profile, done) {
profile.identifier = identifier;
return done(null, profile);
}));
passport.serializeUser(function (user, done) {
done(null, user.identifier);
});
passport.deserializeUser(function (id, done) {
done(null, {identifier: id});
});
return app;
};
module.exports = cmsAuth;
\ No newline at end of file
+var passport = require('passport'),
+ express = require('express'),
+ LocalStrategy = require('passport-local').Strategy,
+ GoogleStrategy = require('passport-google').Strategy,
+ log = require('npmlog'),
+ flash = require('connect-flash'),
+ DS = require('jps-ds').DS;
+var cookieParser = require('cookie-parser');
+
+function cmsAuth(options, app) {
+ var self = this;
+ if (!app) {
+ throw new Error('Must provide express application!');
+ }
+
+ console.warn('cmsAuth', options);
+
+ self._ds = DS;
+
+ var baseUrl = options.host + ':' + options.port;
+ var users = [
+ {id: 1, username: 'bob', password: 'secret', email: 'bob@example.com'}
+ , {id: 2, username: 'joe', password: 'birthday', email: 'joe@example.com'}
+ ];
+
+ function findById(id, fn) {
+ var idx = id - 1;
+ console.log('findById', id);
+ if (users[idx]) {
+
+ fn(null, users[idx]);
+ } else {
+ fn(new Error('User ' + id + ' does not exist'));
+ }
+ }
+
+ function findByUsername(username, fn) {
+ console.log('findByUsername', username);
+ for (var i = 0, len = users.length; i < len; i++) {
+ var user = users[i];
+ if (user.username === username) {
+ return fn(null, user);
+ }
+ }
+ return fn(null, null);
+ }
+
+// Simple route middleware to ensure user is authenticated.
+// Use this route middleware on any resource that needs to be protected. If
+// the request is authenticated (typically via a persistent login session),
+// the request will proceed. Otherwise, the user will be redirected to the
+// login page.
+ function ensureAuthenticated(req, res, next) {
+ if (req.isAuthenticated()) {
+ return next();
+ }
+ res.redirect('/auth/login');
+ }
+
+// Passport session setup.
+// To support persistent login sessions, Passport needs to be able to
+// serialize users into and deserialize users out of the session. Typically,
+// this will be as simple as storing the user ID when serializing, and finding
+// the user by ID when deserializing.
+ passport.serializeUser(function (user, done) {
+ done(null, user.id);
+ });
+
+ passport.deserializeUser(function (id, done) {
+ findById(id, function (err, user) {
+ done(err, user);
+ });
+ });
+
+
+// Use the LocalStrategy within Passport.
+// Strategies in passport require a `verify` function, which accept
+// credentials (in this case, a username and password), and invoke a callback
+// with a user object. In the real world, this would query a database;
+// however, in this example we are using a baked-in set of users.
+ passport.use(new LocalStrategy(function (username, password, done) {
+ // asynchronous verification, for effect...
+ process.nextTick(function () {
+
+ // Find the user by username. If there is no user with the given
+ // username, or the password is not correct, set the user to `false` to
+ // indicate failure and set a flash message. Otherwise, return the
+ // authenticated `user`.
+ findByUsername(username, function (err, user) {
+ if (err) {
+ return done(err);
+ }
+ if (!user) {
+ return done(null, false, {message: 'Unknown user ' + username});
+ }
+ if (user.password != password) {
+ return done(null, false, {message: 'Invalid password'});
+ }
+ return done(null, user);
+ })
+ });
+ }
+ ));
+
+ passport.use(new GoogleStrategy({
+ returnURL: 'http://localhost:8181/auth/google/return', realm: 'http://localhost:8181/auth'
+ },
+ function (identifier, profile, done) {
+ profile.identifier = identifier;
+ return done(null, profile);
+ }
+ ));
+
+
+ //Setup
+ app.configure(function () {
+ app.set('views', __dirname + '/www');
+ app.use(flash());
+ app.use(cookieParser);
+ app.use(passport.initialize());
+ app.use(passport.session());
+
+ app.use(express.session({secret: 'angular-cms'}));
+ });
+ app.all('*', function (req, res, next) {
+ console.warn('cmsAuth', req.params);
+ next();
+ });
+ app.get('/auth', function (req, res) {
+ if (!req.user) {
+ // res.json(200, {message: 'Please login'});
+ res.render('login', { user: req.user, message: req.flash('error') });
+ }
+ });
+
+ app.get('/account', ensureAuthenticated, function (req, res) {
+ res.json(200, {user: req.user});
+ });
+
+ app.get('auth/login', function (req, res) {
+ res.render('login', { user: req.user, message: req.flash('error') });
+ });
+ app.get('/auth/user', ensureAuthenticated, function (req, res) {
+ res.json(200, req.user);
+ });
+ app.get('/auth/google/:return?', passport.authenticate('google', {successRedirect: '/auth/account'}));
+ app.get('/auth/logout', function (req, res) {
+ req.logout();
+ res.redirect(options.apiBase);
+ });
+ app.get('/auth/logout', function (req, res) {
+ req.logout();
+ res.redirect('/');
+ });
+
+
+
+ app.post('/auth/login',
+ passport.authenticate('local', { failureRedirect: '/auth/login', failureFlash: true }),
+ function(req, res) {
+ res.redirect('/');
+ });
+ return app;
+};
+
+
+module.exports = cmsAuth;
From 5709abebe5949ec4388531b3107c964d552242c8 Mon Sep 17 00:00:00 2001
From: Jonnie Spratley
Date: Sat, 6 Dec 2014 17:47:07 -0800
Subject: [PATCH 09/39] added some views
---
.DS_Store | Bin 6148 -> 0 bytes
package.json | 3 +++
routes/cms-auth.js | 61 +++++++++++++++++++++++++++------------------
www/account.ejs | 3 +++
www/index.ejs | 6 +++++
www/layout.ejs | 26 +++++++++++++++++++
www/login.ejs | 25 +++++++++++++++++++
7 files changed, 100 insertions(+), 24 deletions(-)
delete mode 100644 .DS_Store
create mode 100644 www/account.ejs
create mode 100644 www/index.ejs
create mode 100644 www/layout.ejs
create mode 100644 www/login.ejs
diff --git a/.DS_Store b/.DS_Store
deleted file mode 100644
index ccac949f6256a23e91da77b305df68633fab0ce2..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 6148
zcmeH~&x_MQ6vyAR)lICr5fpa8!{EhBk=E|EyC4{96~T*;#XY!ElTFzM(oASmd&owE
zCx5Jeg&>H6e~DM|;ve9D;hP_=DRse%;>tXj`M#MqFF!s*W-t9Hz
zTsd`m#V`%y?A~q=`E1%@lgJ-GbOvnd1b*LhM~{S`xXEPPaYrI@-%SP>5&jNiA^Ll2
z^lsoMgPygPrW?(6jb7j0%xW}kx9c^!(cH>1(=bizopI^PwHtSL+{5hYvs_XmxX1`Q
zr*tOI(J6xm0Yu?J!`Wv;wfvCFKO;ld?fR2sAK>$y??)n4arVMboKY0A
z=m6WZNth4P&Iu);X40sh(C62WtqEuXe~tiOA1D^Cw$faxSURv0M*!3cb_+wFpCxz>
zRcb5ErD6n)$W&CBO4Jd9$aL(dYMiY!mnzeNh&$tT)SZbsp%8I*?5AQl5L>FQH33av
zkw95CEx!NXKK}f_n50{pfF|%?5g?VW)9v6Zsl9dS<@jDpu{_4YjgQNviWIEWb}Sse
e6|Z3thB3+=R9k5-6?@S1kAT3SD^1|968HgzouMfJ
diff --git a/package.json b/package.json
index ef039a2..2511767 100755
--- a/package.json
+++ b/package.json
@@ -31,8 +31,11 @@
"connect-flash": "^0.1.1",
"cookie-parser": "^1.3.3",
"easyimage": "~0.1.6",
+ "ejs": "^1.0.0",
+ "ejs-locals": "^1.0.2",
"emailjs": "~0.3.6",
"express": "~3.4.6",
+ "express-flash": "0.0.2",
"http-proxy": "^1.3.0",
"jps-ds": "~0.0.2",
"jquery": "~2.1.0",
diff --git a/routes/cms-auth.js b/routes/cms-auth.js
index 51f7fb4..c5701f3 100644
--- a/routes/cms-auth.js
+++ b/routes/cms-auth.js
@@ -3,7 +3,8 @@ var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
GoogleStrategy = require('passport-google').Strategy,
log = require('npmlog'),
- flash = require('connect-flash'),
+ path = require('path'),
+ flash = require('express-flash'),
DS = require('jps-ds').DS;
var cookieParser = require('cookie-parser');
@@ -114,32 +115,50 @@ function cmsAuth(options, app) {
//Setup
app.configure(function () {
- app.set('views', __dirname + '/www');
- app.use(flash());
- app.use(cookieParser);
- app.use(passport.initialize());
- app.use(passport.session());
+ app.set('views', path.resolve(__dirname, '../www'));
+ app.set('view engine', 'ejs');
+ app.engine('ejs', require('ejs-locals'));
+ app.use(express.logger());
+ app.use(express.cookieParser());
+ app.use(express.bodyParser());
+ app.use(express.methodOverride());
+ app.use(express.session({secret: 'angular-cms'}));
+ app.use(express.session({ cookie: { maxAge: 60000 }}));
+ app.use(flash());
+ // Initialize Passport! Also use passport.session() middleware, to support
+ // persistent login sessions (recommended).
+ app.use(passport.initialize());
+ app.use(passport.session());
+ app.use(app.router);
+
- app.use(express.session({secret: 'angular-cms'}));
});
+
+
+
app.all('*', function (req, res, next) {
console.warn('cmsAuth', req.params);
next();
});
- app.get('/auth', function (req, res) {
- if (!req.user) {
- // res.json(200, {message: 'Please login'});
- res.render('login', { user: req.user, message: req.flash('error') });
- }
- });
- app.get('/account', ensureAuthenticated, function (req, res) {
- res.json(200, {user: req.user});
+ app.get('/', function(req, res){
+
+ res.render('index', { user: req.user });
});
- app.get('auth/login', function (req, res) {
- res.render('login', { user: req.user, message: req.flash('error') });
- });
+app.get('/account', ensureAuthenticated, function(req, res){
+ res.render('account', { user: req.user });
+});
+
+app.get('/login', function(req, res){
+ res.render('login', { user: req.user, message: 'Please login' });
+});
+app.post('/login', passport.authenticate('local', { failureRedirect: '/login', failureFlash: false }), function(req, res) {
+ res.redirect('/');
+});
+
+
+
app.get('/auth/user', ensureAuthenticated, function (req, res) {
res.json(200, req.user);
});
@@ -154,12 +173,6 @@ function cmsAuth(options, app) {
});
-
- app.post('/auth/login',
- passport.authenticate('local', { failureRedirect: '/auth/login', failureFlash: true }),
- function(req, res) {
- res.redirect('/');
- });
return app;
};
diff --git a/www/account.ejs b/www/account.ejs
new file mode 100644
index 0000000..d69ad21
--- /dev/null
+++ b/www/account.ejs
@@ -0,0 +1,3 @@
+<% layout('layout') -%>
+
Username: <%= user.username %>
+
Email: <%= user.email %>
\ No newline at end of file
diff --git a/www/index.ejs b/www/index.ejs
new file mode 100644
index 0000000..e70df3e
--- /dev/null
+++ b/www/index.ejs
@@ -0,0 +1,6 @@
+<% layout('layout') -%>
+<% if (!user) { %>
+
Welcome! Please log in.
+<% } else { %>
+
Hello, <%= user.username %>.
+<% } %>
diff --git a/www/layout.ejs b/www/layout.ejs
new file mode 100644
index 0000000..264c217
--- /dev/null
+++ b/www/layout.ejs
@@ -0,0 +1,26 @@
+
+
+
+
+
+ Passport-Local Example
+
+
+
+
+ <% if (!user) { %>
+