Skip to content

Instantly share code, notes, and snippets.

@werelax
Last active August 29, 2015 13:57
Show Gist options
  • Save werelax/9550240 to your computer and use it in GitHub Desktop.
Save werelax/9550240 to your computer and use it in GitHub Desktop.
node.js + mongo + simpleauth.js recipe
/* jshint node: true, laxcomma: true */
/* global __dirname */
/* Dependencies */
"use strict";
var express = require("express")
, Q = require("q")
, auth = require("./simpleauth")
, MongoClient = require("mongodb").MongoClient
, ObjectID = require("mongodb").ObjectID
;
var client = Q.ninvoke(MongoClient,
"connect",
"mongodb://127.0.0.1:27017/cf");
client.fail(function(e) {
console.log("ERROR conectando a Mongo: ", e);
});
var app = express();
app.configure(function() {
app.set("port", process.env.PORT || 8080);
app.use(express.favicon());
app.use(express.logger("short"));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.set("views", __dirname + "/views");
app.set("view engine", "jade");
app.use(express.cookieParser("your secret here"));
app.use(express.session());
app.use(app.router);
app.use(express.static(__dirname + "/public"));
});
/* Utils */
function extend() {
var args = [].slice.call(arguments);
return args.reduce(function(acc, el) {
for (var k in el) {
if (el.hasOwnProperty(k)) { acc[k] = el[k]; }
}
return acc;
});
}
function Model(collection, klass) {
klass = klass || {};
klass._collectionName = collection;
klass._collection = client.then(function(db) {
return db.collection(klass._collectionName);
});
return extend(klass, {
op: function() {
var args = [].slice.call(arguments);
return klass._collection.then(function(col) {
return Q.ninvoke.apply(Q, [col].concat(args));
});
},
makeOp: function() {
var args = [].slice.call(arguments);
return function() {
this.op.apply(this, args);
}.bind(this);
},
create: function(data) {
return klass.op("insert",
extend(data, this.defaults || {}, {date: Date.now()}));
}
});
}
// Remotron approach (simpler, more elegant in my opinion)
function op(colname) {
var args = [].slice.call(arguments, 1),
collections = {};
return client.then(function(db) {
if (!(colname in collections)) { collections[colname] = db.collection(colname); }
return Q.ninvoke.apply(Q, [collections[colname]].concat(args));
})
.fail(function(err) {
console.log("[MongoDB]", err);
throw err;
});
}
function makeOp(col) {
var args = [].slice.call(arguments, 1);
return function () { return col.apply({}, args); };
}
/* Models */
var User = Model("users", {
});
var Post = Model("posts", {
});
// Remotron approach
var users = extend(op.bind({}, "users"), {
});
var posts = extend(op.bind({}, "posts"), {
});
var clients = extend(op.bind({}, "clients"), {
});
/* Auth */
auth.setStrategy({
serializeUser: function(user) {
return user._id;
},
deserializeUser: function(userId, cb) {
users("findOne", { _id: new ObjectID(userId) })
.then(function(user) {
return user;
})
.then(cb)
.done();
},
checkCredentials: function(username, pass, cb) {
users("findOne", { email: username })
.then(function(user) {
cb(null, (user && user.password === pass) ? user : null);
});
}
});
//
// Your stuff here
//
/* Routing */
function resources(app, name, controller) {
if (controller.index) { app.get("/"+name, controller.index); }
if (controller["new"]) { app.get("/"+name+"/new", controller["new"]); }
if (controller.create) { app.post("/"+name, controller.create); }
if (controller.show) { app.get("/"+name+"/:"+name+"id", controller.show); }
if (controller.edit) { app.get("/"+name+"/:"+name+"id/edit", controller.edit); }
if (controller.update) { app.put("/"+name+"/:"+name+"id", controller.update); }
if (controller["delete"]) { app["delete"]("/"+name+"/:"+name+"id", controller["delete"]); }
if (controller.param) { app.param(name + "id", controller.param); }
}
app.post("/session", auth.createSession({ redirect: "/posts" }));
app.get("/logout", auth.destroySession);
app.put("/profile/:profileid", profileController.update);
resources(app, "posts", postsController);
resources(app, "profile", profileController);
resources(app, "clients", clientsController);
auth.withSession(app, function(app) {
/*
resources(app, "posts", postsController);
resources(app, "profile", profileController);
*/
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment