Skip to content

Instantly share code, notes, and snippets.

@royhowie
Last active August 29, 2015 14:22
Show Gist options
  • Save royhowie/3894041b40ffffab6e5b to your computer and use it in GitHub Desktop.
Save royhowie/3894041b40ffffab6e5b to your computer and use it in GitHub Desktop.
Why Function.prototype.bind is useful (but mostly how I set up my node.js projects)
module.exports = {
// lots of other files are also exported
localLogin: function (passport, req, res, next) {
passport.authenticate("login", {
successRedirect: "/order/admin",
failureRedirect : "/order/admin/login",
failureFlash : true
})(req, res, next);
},
localSignup: function (passport, req, res, next) {
passport.authenticate("register", {
successRedirect : "/order/admin",
failureRedirect : "/order/register",
failureFlash : true
})(req, res, next);
}
}
var r = require("routing.js")
module.exports = function (app, passport) {
// lots of routes here, e.g.:
app.get(["/", "/order"], r.general.index);
// to register (as an admin)
app.route("/order/register")
.get(r.accounts.getRegister)
// note the use of `Function.prototype.bind`
.post(r.accounts.localSignup.bind(null, passport));
// to login (as an admin)
app.route("/order/admin/login")
.get(r.accounts.getLogin)
.post(r.accounts.localLogin.bind(null, passport));
}
// main routing file
var rekwire = require("rekwire");
module.exports = {
accounts : rekwire("app/routes/accounts")
, admin : rekwire("app/routes/admin")
, api : rekwire("app/routes/api")
, errors : rekwire("app/routes/errors")
, general : rekwire("app/routes/general")
, middleware : rekwire("app/routes/middleware")
, params : rekwire("app/routes/params")
}
// require passport, since it's being use to authenticate
var passport = require("passport")
// start express
var app = module.exports = express();
// config/passport.js configures the library
require("./config/passport")(passport);
// initializes passport and starts a new session
app.use(passport.initialize());
app.use(passport.session());
// require my routing file, routes.js
require("./app/routes.js")(app, passport);
/* lots of other code is midding */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment