Skip to content
Myr

Merge branch 'features/route-middleware'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tj Holowaychuk · committed by Tj Holowaychuk · parents 72765ba, dd23d60 · Browse files · 4 files+91 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+91 added−1 removed

  • tests:+50 added−0 removed
  • other:+41 added−1 removed

4 files+91 added−1 removed

modified:examples/auth/views/login.ejs+1 added
1<h1>Login</h1>2<%- message %>3Try accessing <a href="/restricted">/restricted</a>.4<form method="post" action="/login">5 <p>6 <label>Username:</label>7 <input type="text" name="username">
9 unmodified lines
modified:examples/auth/app.js+20 added-1 removed
modified:lib/express/server.js+20 added
305 unmodified lines
306// Generate routing methods307308(function(method){309 Server.prototype[method] = function(path, fn){310 var self = this;311312 // Ensure router is mounted313 if (!this.__usedRouter) {314 this.use(this.router);315 }316317 // Route specific middleware support318 if (arguments.length > 2) {319 var args = Array.prototype.slice.call(arguments, 1);320 fn = args.pop();321 (function stack(middleware){322 middleware.forEach(function(fn){323 if (Array.isArray(fn)) {324 stack(fn);325 } else {326 self[method](path, fn);327 }328 });329 })(args);330 }331332 // Generate the route333 this.routes[method](path, fn);334 return this;335 };336 return arguments.callee;
1 unmodified line
modified:test/express.test.js+50 added
319 unmodified lines
320 { body: 'blog post 12' });321 assert.response(blog,322 { url: '/' },323 { body: 'blog index' });324 },325 326 'test route middleware': function(assert){327 var app = express.createServer();328329 function allow(role) {330 return function(req, res, next) {331 // this is totally not real, dont use this :)332 // for tests only333 if (req.headers['x-role'] == role) {334 next();335 } else {336 res.send(401);337 }338 }339 }340 341 function restrictAge(age) {342 return function(req, res, next){343 if (req.headers['x-age'] >= age) {344 next();345 } else {346 res.send(403);347 }348 }349 }350351 app.get('/xxx', allow('member'), restrictAge(18), function(req, res){352 res.send(200);353 });354355 app.get('/booze', [allow('member')], restrictAge(18), function(req, res){356 res.send(200);357 });358359 app.get('/tobi', [allow('member')], [[restrictAge(18)]], function(req, res){360 res.send(200);361 });362363 ['xxx', 'booze', 'tobi'].forEach(function(thing){364 assert.response(app,365 { url: '/' + thing },366 { body: 'Unauthorized', status: 401 });367 assert.response(app,368 { url: '/' + thing, headers: { 'X-Role': 'member' }},369 { body: 'Forbidden', status: 403 });370 assert.response(app,371 { url: '/' + thing, headers: { 'X-Role': 'member', 'X-Age': 18 }},372 { body: 'OK', status: 200 });373 });374 }375};