Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Pointing all routes to the home page and adding a small script to set…

… the RouteManagers location based on the URL requested. (Client Side Routing Implemented)
  • Loading branch information...
commit 62ca37224f25475513b3f49436ea489f1926af9b 1 parent f94fa61
@distracteddev authored
View
110 app.js
@@ -6,33 +6,35 @@ var flatiron = require('flatiron'),
fs = require('fs'),
//qs = require('querystring'),
passport = require('passport'),
+ User = require('./models').User();
LocalStrategy = require('passport-local').Strategy;
app = flatiron.app;
var routes = require('./routes');
-
-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;
- if (users[idx]) {
- fn(null, users[idx]);
- } else {
- fn(new Error('User ' + id + ' does not exist'));
- }
-}
-
-function findByUsername(username, fn) {
- 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);
+var animalRoutes = require('./routes/animals.js')
+
+u = User.new(
+ {
+ "username": "zeus",
+ "password": "zeuszeus",
+ "email": "lalkaka.zeus@gmail.com"
+ }
+);
+
+u.save();
+
+function findByUsername(username, done) {
+ User.find({"username":username}, function(err, user) {
+ if (err) {
+ return done(err, null);
+ }
+ else if (user) {
+ return done(null, user[0]);
+ }
+ else {
+ return done(null, null);
+ }
+ });
}
passport.use(new LocalStrategy(
@@ -47,6 +49,9 @@ passport.use(new LocalStrategy(
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unkown user ' + username }); }
+ debugger;
+ console.log(password);
+ console.log(user.password);
if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
return done(null, user);
})
@@ -56,18 +61,17 @@ passport.use(new LocalStrategy(
passport.serializeUser(function(user, done) {
- done(null, user.id);
+ done(null, user.username);
});
-passport.deserializeUser(function(id, done) {
- findById(id, function (err, user) {
+passport.deserializeUser(function(username, done) {
+ findByUsername(username, function (err, user) {
done(err, user);
});
});
app.use(flatiron.plugins.http, {
before: [
- //connect.bodyParser(),
connect.favicon('./public/favicon.ico'),
connect.cookieParser('lolcats'),
connect.session({secret: "9ajk21mas8"}),
@@ -80,24 +84,6 @@ app.use(flatiron.plugins.http, {
after: []
});
-var bark = function (color, text) {
- if (!color) color = "";
- if (!text) text = "";
- var json = {};
- var key = (color.length < 1) ? 'dogs' : color + " dogs";
- var secondValue = (text.length < 1) ? '' : " " + text.toString();
- json[key] = 'bark' + secondValue;
- var response = JSON.stringify(json);
- this.res.end(response);
-};
-
-var meow = function () {
- this.res.json({ 'cats': 'meow' });
-};
-
-var hello = function () {
- this.res.json({ 'hello': 'animal world' });
-};
app.router.path('/', function () {
this.get(function () {
@@ -113,14 +99,26 @@ app.router.path('/', function () {
});
});
+ this.get('/:name', function(name) {
+ var self = this;
+ fs.readFile('public/index.html', function(err, data) {
+ if(err) {
+ self.res.writeHead(404, {'Content-Type': 'text/html'});
+ self.res.end(__dirname + " 404:\n" + JSON.stringify(err));
+ return;
+ }
+ self.res.writeHead(200, {'Content-Type': 'text/html'});
+ self.res.end(data);
+ });
+ });
+
this.post('jsonTest', function () {
console.log(this.req.body);
- var self = this;
- //self.res.end(JSON.stringify(this.req.isAuthenticated()) + '\n');
+ var self = this;
self.res.end(JSON.stringify(self.req.body) + '\n');
});
- this.get('/tags',routes.getTags);
+ this.get('services/tags',routes.getTags);
this.post('/login',
function() {
@@ -153,29 +151,29 @@ app.router.path('/\/markdown', function() {
});
-app.router.path('/\/blog_posts/', function() {
+app.router.path('/services/blog_posts/', function() {
this.get(routes.getBP);
this.post(routes.postBP);
});
-app.router.path('/\/blog_posts/:id', function() {
+app.router.path('/services/blog_posts/:id', function() {
this.get(routes.getBP);
this.post(routes.postBP);
this.put(routes.postBP);
this.delete(routes.deleteBP);
});
-app.router.path('/\/blog_settings', function() {
+app.router.path('/services/blog_settings', function() {
this.get(routes.getSettings);
this.post(routes.postSettings);
});
app.router.path('/\/animals', function () {
- this.get(hello);
- this.get('/dog/', bark);
- this.get('/dog/:color', bark);
- this.get('/dog/:color/:text', bark);
- this.get('/cat/', meow);
+ this.get(animalRoutes.hello);
+ this.get('/dog/', animalRoutes.bark);
+ this.get('/dog/:color', animalRoutes.bark);
+ this.get('/dog/:color/:text', animalRoutes.bark);
+ this.get('/cat/', animalRoutes.meow);
});
View
26 models/index.js
@@ -1,6 +1,5 @@
var Resourceful = require('resourceful');
-
var tagFilter = {
map: function (post) {
post.tags.forEach(function (tag) {
@@ -20,16 +19,17 @@ var options = {
var BlogPost = Resourceful.define('blogpost', function () {
this.use('couchdb', {
- uri: 'couchdb://zeus.iriscouch.com/blogposts'
+ uri: 'couchdb://127.0.0.1:5984/blogposts'
//uri: 'couchdb://127.0.0.1:5984/blogposts'
});
this.string('title');
this.string('subTitle');
- // the body property holds the HTML version of the body text
+ this.bool('published');
+ // the body property holds the HTML version of the body text
this.string('body');
- // the body_raw property holds the Raw Markdown version of the body text.
- this.string('body_raw');
+ // the body_raw property holds the Raw Markdown version of the body text.
+ this.string('body_raw');
this.array('tags');
this.timestamps();
debugger;
@@ -44,7 +44,7 @@ exports.BlogPost = function() {
var BlogSettings = Resourceful.define('settings', function () {
this.use('couchdb', {
- uri: 'couchdb://zeus.iriscouch.com/settings'
+ uri: 'couchdb://127.0.0.1:5984/settings'
});
this.string('blog_itle');
@@ -56,3 +56,17 @@ var BlogSettings = Resourceful.define('settings', function () {
exports.BlogSettings = function () {
return BlogSettings;
};
+
+var User = Resourceful.define('users', function() {
+
+ this.use('memory');
+ this.string('username');
+ this.string('password');
+ this.object('settings');
+ this.string('email');
+ this.timestamps();
+});
+
+exports.User = function() {
+ return User;
+}
View
156 public/app.js
@@ -67,6 +67,27 @@ Ember.registerBoundHelper = function(name, func) {
// END OF BOUND HANDLEBARS HELPER DEFINITION
+// START OF PATH REPLACEMENT
+ setTimeout(function() {
+ var path = window.location.pathname;
+
+ if (path !== "/") {
+ console.log("PATH:" + path);
+ //newState = window.location.origin
+ // + "/#" + (window.location.pathname.slice(1
+ // Turns /pathName into pathName
+ var newState = (window.location.pathname.slice(1));
+ //App.routeManager.set('baseURI', window.location.origin);
+ //window.history.pushState(null, null, window.location.origin);
+ console.log(newState);
+ App.routeManager.set('location', newState);
+ //window.location.pathname = "";
+ //window.location.hash = newState;
+
+ }
+ }, 10);
+// END OF PATH REPLACEMENT
+
var App = Em.Application.create();
// Custom Ember Data Structure to Store an Array of tags
@@ -83,8 +104,11 @@ DS.attr.transforms.array = {
// Initialize the Data Store provided by Ember-Data.
App.store = DS.Store.create({
revision: 4,
- // Use the default REST adapter.
- adapter: DS.RESTAdapter.create({bulkCommit: false})
+ // Use the default REST adapter.
+ adapter: DS.RESTAdapter.create({
+ bulkCommit: false,
+ namespace: 'services'
+ })
});
/*
@@ -109,37 +133,38 @@ App.BlogSetting = DS.Model.extend({
App.BlogPost = DS.Model.extend({
title: DS.attr('string'),
sub_title: DS.attr('string'),
- // body holds the HTML String of the post content
+ published: DS.attr('boolean'),
+ // body holds the HTML String of the post content
body: DS.attr('string'),
- // body_raw holds the Raw Markdown of the post content
- body_raw: DS.attr('string'),
- // Custom Data Type gets presented to the front end as a comma seperated string of values
- // e.g "First Tag, Second Tag, Another Tag"
+ // body_raw holds the Raw Markdown of the post content
+ body_raw: DS.attr('string'),
+ // Custom Data Type gets presented to the front end as a comma seperated string of values
+ // e.g "First Tag, Second Tag, Another Tag"
tags: DS.attr('array'),
_id: DS.attr('string'),
_rev: DS.attr('string'),
ctime: DS.attr('date'),
mtime: DS.attr('date'),
- primaryKey: "_id",
+ primaryKey: "title",
- tags_array: function() {
- return this.get('tags').split(', ');
- }.property('tags').cacheable(),
+ tags_array: function() {
+ return this.get('tags').split(', ');
+ }.property('tags').cacheable(),
didLoad: function() {
console.log(this.get('ctime'));
},
- didUpdate: function() {
- console.log(this.get("body") + " was updated");
- // Refresh the view so that it updates with the latest content
- // TODO: Refactor this so that Ember native observers work as intended
- Ember.run.later(function() {
- App.layout.set('content', '');
- App.layout.set('content', App.selectedPostView);
- console.log("later");
- }, 800);
- }
+ didUpdate: function() {
+ console.log(this.get("body") + " was updated");
+ // Refresh the view so that it updates with the latest content
+ // TODO: Refactor this so that Ember native observers work as intended
+ Ember.run.later(function() {
+ App.layout.set('content', '');
+ App.layout.set('content', App.selectedPostView);
+ console.log("later");
+ }, 800);
+ }
});
App.Tag = DS.Model.extend({
@@ -228,7 +253,8 @@ App.PostController = Ember.ArrayController.create({
tags: "Enter, a, Comma, Seperated, List, of, Tags",
title: "Blog Title",
sub_title: "Enter Witty Sub-Title Here",
- body: "Double Click to Start Editing"
+ body: "Double Click to Start Editing",
+ published: false
});
// Set it as the selected post
var lastIdx = this.get("content").get("length")
@@ -261,27 +287,29 @@ App.PostController = Ember.ArrayController.create({
getPostPreview: function() {
if (this.get('selectedPost')) {
- var rawMarkdown = this.get('selectedPost').get('body_raw');
- var obj = {};
- obj.md = rawMarkdown;
- var that = this;
- $.post('/markdown', obj, function(data) {
- window.d = data;
- console.log('getPostPreview fired');
- //return $(data).children();
- that.propertyWillChange('postPreview');
- that.set('postPreview',data);
- that.propertyDidChange('postPreview');
- var editedPost = that.get('selectedPost');
- editedPost.propertyWillChange('body');
- editedPost.set('body', data);
- editedPost.propertyDidChange('body');
- }, 'text');
+ var rawMarkdown = this.get('selectedPost').get('body_raw');
+ var obj = {};
+ obj.md = rawMarkdown;
+ var that = this;
+ $.post('/markdown', obj, function(data) {
+ window.d = data;
+ console.log('getPostPreview fired');
+ //return $(data).children();
+ that.propertyWillChange('postPreview');
+ that.set('postPreview',data);
+ that.propertyDidChange('postPreview');
+ var editedPost = that.get('selectedPost');
+ editedPost.propertyWillChange('body');
+ editedPost.set('body', data);
+ editedPost.propertyDidChange('body');
+ }, 'text');
}
return this.get('postPreview');
}.observes('selectedPost.body_raw')
+
+
});
App.TagController = Ember.ArrayProxy.create({
@@ -334,7 +362,14 @@ App.PreviewView = Ember.View.extend({
// Fetch the data models from the server and pass them into our
// controllers
App.HeaderController.set('content', App.store.find(App.BlogSetting));
-App.PostController.set('content', App.store.find(App.BlogPost));
+// Load all Blog Posts
+var allPosts = App.store.find(App.BlogPost);
+// Filter out the unpublished posts and add the remaining objects
+// to the PostController's content attribute
+var publishedPosts = App.store.filter(App.BlogPost, function(post) {
+ return post.get('published');
+});
+App.PostController.set('content', publishedPosts);
App.TagController.set('content', App.store.find(App.Tag));
// CUSTOM FIELD VIEW FOR EMBER TO ALLOW FOR INLINE PAGE EDITING
// This field uses the property 'isEditing' as a signal to its
@@ -436,21 +471,32 @@ Ember.Handlebars.registerHelper('date', function(path, options) {
*START OF EMBER ROUTE MANAGER
*/
App.routeManager = Ember.RouteManager.create({
+
enableLogging: true,
rootView: App.layout,
- home: Em.State.create({
- //viewClass: App.postView
- }),
+
+ home: Em.State.create({}),
+
login: Em.State.create({
route: 'login',
- //view: App.layout,
index: Em.State.create({
enter: function(statemanager, transition) {
this._super(statemanager, transition);
$("#reveal-Login").reveal();
}
})
- })
+ }),
+
+ show: Em.State.create({
+ route: ':id',
+ enter: function(stateManager, transition) {
+ this._super(stateManager, transition);
+ var params = stateManager.get('params');
+ var postId = params.id;
+ console.log(postId);
+ }
+ })
+
});
/*
@@ -478,6 +524,9 @@ ExposedAuthor = function() {
App.PostController.propertyWillChange('authorized');
authorized = true;
App.PostController.propertyDidChange('authorized');
+ App.PostController.propertyWillChange('content');
+ App.PostController.set('content', allPosts);
+ App.PostController.propertyDidChange('content');
$("#reveal-Login").trigger("reveal:close");
}
else {
@@ -508,6 +557,7 @@ var Author = new objectHider(ExposedAuthor);
// function.
$(function() {
Ember.run(function() {
+
// Start the Route Manager so that it listens for URL changes
App.routeManager.start();
// Initialize my layout and append it to the body
@@ -527,12 +577,18 @@ $(function() {
});
Ember.run.next(function() {
- $(".alert-box").delegate("a.close", "click", function(event) {
- event.preventDefault();
- $(this).closest(".alert-box").fadeOut(function(event){
- $(this).remove();
- });
- });
+ $(".alert-box").delegate("a.close", "click", function(event) {
+ event.preventDefault();
+ $(this).closest(".alert-box").fadeOut(function(event){
+ $(this).remove();
+ });
+ });
+
+ $("#login").click(function() {
+ console.log(" I RAN ");
+ App.routeManager.set('location', 'login');
+ return false;
+ });
});
$('body').bind("soapbox:blog_posts_loaded.soapbox",function() {
View
45 public/index.html
@@ -43,11 +43,11 @@
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
- <script type="text/x-handlebars" data-template-name="posts">
+ <!-- <script type="text/x-handlebars" data-template-name="posts">
{{#each content}}
<div class="row">
{{#if isDirty}}
- <section class="post columns one">
+ <section class="post columns one">
</br>
</br>
{{#view App.PostButton action="save"}}Save{{/view}}
@@ -64,7 +64,7 @@
</section>
</div>
{{/each}}
- </script>
+ </script> -->
<script type="text/x-handlebars" data-template-name="single-post">
{{#with App.PostController.selectedPost}}
@@ -88,6 +88,7 @@ <h5 class="post-sub-title">{{editable sub_title}}</h5>
<div class="post-body post row">
<section class="post post-sidebar">
{{#if App.PostController.authorized}}
+ {{view Ember.Checkbox title="Published" valueBinding="published"}}
{{#view App.PostButton action="save" classNames="button green" tagName="button"}}
Save
{{/view}}
@@ -115,12 +116,10 @@ <h5 class="post-sub-title">{{editable sub_title}}</h5>
Go Write Some Shit.
<a href="#" class="close">&times;</a>
</div>
-
- {{#each content}}
- <a href="#login" id="login">
- <img src="images/logo.png" alt="Zeus Lalkaka's Logo" id="logo"/>
- </a>
- {{/each}}
+
+ <a href="" id="login">
+ <img src="/images/logo.png" alt="Zeus Lalkaka's Logo" id="logo"/>
+ </a>
<div class="ctr-ctn">
<dl class="sub-nav ctr-block">
@@ -218,20 +217,20 @@ <h5 class="post-sub-title">{{editable sub_title}}</h5>
<body>
<!--Load Javascript within the body so it doesn't slow down page rendering-->
- <script src="javascripts/jquery.min.js"></script>
- <script src="javascripts/jquery.reveal.js"></script>
- <script src="javascripts/jquery.orbit-1.4.0.js"></script>
- <script src="javascripts/jquery.customforms.js"></script>
- <script src="javascripts/jquery.placeholder.min.js"></script>
- <script src="javascripts/jquery.tooltips.js"></script>
- <script src="javascripts/jquery.text-expander.js"></script>
- <script src="javascripts/lib/ember.js"></script>
- <script src="javascripts/lib/ember-data.js"></script>
- <script src="javascripts/lib/ember-routemanager.js"></script>
- <script src="javascripts/lib/ember-layout.js"></script>
- <script src="javascripts/lib/move.js"></script>
- <script src="javascripts/app.js"></script>
- <script src="app.js"></script>
+ <script src="/javascripts/jquery.min.js"></script>
+ <script src="/javascripts/jquery.reveal.js"></script>
+ <script src="/javascripts/jquery.orbit-1.4.0.js"></script>
+ <script src="/javascripts/jquery.customforms.js"></script>
+ <script src="/javascripts/jquery.placeholder.min.js"></script>
+ <script src="/javascripts/jquery.tooltips.js"></script>
+ <script src="/javascripts/jquery.text-expander.js"></script>
+ <script src="/javascripts/lib/ember.js"></script>
+ <script src="/javascripts/lib/ember-data.js"></script>
+ <script src="/javascripts/lib/ember-routemanager.js"></script>
+ <script src="/javascripts/lib/ember-layout.js"></script>
+ <script src="/javascripts/lib/move.js"></script>
+ <script src="/javascripts/app.js"></script>
+ <script src="/app.js"></script>
<div class="reveal-modal" id="reveal-Login">
View
7 public/javascripts/lib/ember-routemanager.js
@@ -7,6 +7,7 @@ var get = Ember.get, set = Ember.set;
*/
var supportsHistory = !!(window.history && window.history.pushState);
+//var supportsHistory = true;
/**
Whether the browser supports the hashchange event.
*/
@@ -47,7 +48,7 @@ Ember.RouteManager = Ember.StateManager.extend({
@property
@type {Boolean}
*/
- wantsHistory: false,
+ wantsHistory: true,
/**
A read-only boolean indicating whether or not HTML5 history is used. Based
@@ -80,7 +81,7 @@ Ember.RouteManager = Ember.StateManager.extend({
@property
@type {String}
*/
- baseURI: document.baseURI,
+ baseURI: window.location.origin,
/** @private
A boolean value indicating whether or not the ping method has been called
@@ -173,7 +174,7 @@ Ember.RouteManager = Ember.StateManager.extend({
if(this.usesHistory) {
if(encodedValue.length > 0) {
encodedValue = '/' + encodedValue;
- }
+ }
window.history.pushState(null, null, get(this, 'baseURI') + encodedValue);
} else if(encodedValue.length > 0 || window.location.hash.length > 0) {
window.location.hash = encodedValue;
View
28 routes/animals.js
@@ -0,0 +1,28 @@
+exports.bark = function (color, text, unused) {
+ if (!color) color = "";
+ if (!text) text = "";
+
+ if (arguments.length < 3) {
+ text = null;
+ }
+ else if (arguments.length < 2) {
+ color = null;
+ text = null;
+ }
+
+ console.log(arguments);
+ var json = {};
+ var key = (typeof color !== 'string') ? 'dogs' : color + " dogs";
+ var secondValue = (!text) ? '' : " " + text.toString();
+ json[key] = 'bark' + secondValue;
+ var response = JSON.stringify(json);
+ this.res.end(response);
+};
+
+exports.meow = function () {
+ this.res.json({ 'cats': 'meow' });
+};
+
+exports.hello = function () {
+ this.res.json({ 'hello': 'animal world' });
+};
View
26 routes/index.js
@@ -1,7 +1,7 @@
var Resourceful = require('resourceful'),
winston = require('winston'),
- marked = require('marked'),
- highlighter = require('highlight').Highlight,
+ marked = require('marked'),
+ highlighter = require('highlight').Highlight,
BlogSettings = require('../models').BlogSettings(),
BlogPost = require('../models').BlogPost();
@@ -33,17 +33,24 @@ exports.parseMarkdown = function() {
// Get all blog posts, or a single blog post when an ID is provided.
exports.getBP = function(id) {
+ // Return all posts
var self = this;
if (arguments.length < 2) {
BlogPost.all(function(err, posts) {
- if (err) throw err;
- posts.sort(function(a, b) {
- return b.ctime-a.ctime;
- });
+ if (err) {
+ winston.error(err);
+ throw err;
+ }
+ // Sort the returned array of posts by their creation
+ // time
+ posts.sort(function(a, b) {
+ return b.ctime-a.ctime;
+ });
self.res.end('{"blog_posts":' + JSON.stringify(posts) + "}");
return posts;
});
}
+ // Return a single post with a specific ID
else {
console.log('ID: ' + id);
BlogPost.find({_id:id}, function(err, post) {
@@ -70,7 +77,7 @@ exports.postBP = function (id) {
if (typeof id !== "string") {
BlogPost.create(self.req.body.blog_post, function (err, doc) {
if (err) {
- winston.log(err);
+ winston.error(JSON.stringify(err));
throw new(Error)(err);
}
@@ -120,7 +127,10 @@ exports.getTags = function () {
exports.getSettings = function () {
var self = this;
var settings = BlogSettings.all(function (err, settings) {
- if (err) throw err;
+ if (err) {
+ winston.error(JSON.stringify(err));
+ throw err;
+ }
// Check if the function has been called
// as a response handler.
if (self !== undefined) {
View
12 test/animal-test.js
@@ -7,14 +7,14 @@ suite.discuss('Testing SoapBox')
.discuss('Get Requests:')
.use('localhost', 9000)
//.setHeader('Content-Type', 'application/json')
- .get('/')
- .expect(200, { hello: 'world' })
- .get('/cat/')
+ .get('animals')
+ .expect(200, { hello: 'animal world' })
+ .get('animals/cat/')
.expect(200, { cats: 'meow' })
- .get('/dog/')
+ .get('animals/dog/')
.expect(200, { dogs: 'bark' })
- .get('/dog/blue/')
+ .get('animals/dog/blue/')
.expect(200, { "blue dogs": 'bark' })
- .get('/dog/green/')
+ .get('animals/dog/green/')
.expect(200, { "green dogs": 'bark' })
.export(module);
View
22 test/login-test.js
@@ -0,0 +1,22 @@
+var APIeasy = require('api-easy'),
+ assert = require('assert');
+
+var suite = APIeasy.describe('login');
+
+suite.discuss('Testing SoapBox Login Functions')
+ .discuss('Get Requests:')
+ .use('localhost', 9000)
+ .setHeader('Content-Type', 'application/json')
+ .post('login')
+ .expect('No Credentials Submitted', 200, function(ctx, args) {
+ assert.equal(args.body, 'false');
+ })
+ .post('login', {username:'bob', password:'secret'})
+ .expect('Wrong Credentials Submitted', 200, function(ctx, args) {
+ assert.equal(args.body, 'false');
+ })
+ .post('login', {username:'zeus', password:'zeuszeus'})
+ .expect('Correct Credentials Submitted', 200, function(ctx, args) {
+ assert.equal(args.body, 'true');
+ })
+ .export(module);
Please sign in to comment.
Something went wrong with that request. Please try again.