Skip to content
Myr

index.js

This file

Path

examples/route-middleware/index.js

88 lines · 2.3 KiB · JavaScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 6bc7574 point at it.

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 1–88why, one step back
1/**
2 * Module dependencies.3 */45var express = require('../../lib/express');67var app = express();89// Example requests:10// curl http://localhost:3000/user/011// curl http://localhost:3000/user/0/edit12// curl http://localhost:3000/user/113// curl http://localhost:3000/user/1/edit (unauthorized since this is not you)14// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin)1516// Dummy users17var users = [18 { id: 0, name: 'tj', email: 'tj@vision-media.ca', role: 'member' }19 , { id: 1, name: 'ciaran', email: 'ciaranj@gmail.com', role: 'member' }20 , { id: 2, name: 'aaron', email: 'aaron.heckmann+github@gmail.com', role: 'admin' }21];2223function loadUser(req, res, next) {24 // You would fetch your user from the db25 var user = users[req.params.id];26 if (user) {27 req.user = user;28 next();29 } else {30 next(new Error('Failed to load user ' + req.params.id));31 }32}3334function andRestrictToSelf(req, res, next) {35 // If our authenticated user is the user we are viewing36 // then everything is fine :)37 if (req.authenticatedUser.id == req.user.id) {38 next();39 } else {40 // You may want to implement specific exceptions41 // such as UnauthorizedError or similar so that you42 // can handle these can be special-cased in an error handler43 // (view ./examples/pages for this)44 next(new Error('Unauthorized'));45 }46}4748function andRestrictTo(role) {49 return function(req, res, next) {50 if (req.authenticatedUser.role == role) {51 next();52 } else {53 next(new Error('Unauthorized'));54 }55 }56}5758// Middleware for faux authentication59// you would of course implement something real,60// but this illustrates how an authenticated user61// may interact with middleware6263app.use(function(req, res, next){64 req.authenticatedUser = users[0];65 next();66});6768app.get('/', function(req, res){69 res.redirect('/user/0');70});7172app.get('/user/:id', loadUser, function(req, res){73 res.send('Viewing user ' + req.user.name);74});7576app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){77 res.send('Editing user ' + req.user.name);78});7980app.delete('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){81 res.send('Deleted user ' + req.user.name);82});8384/* istanbul ignore next */85if (!module.parent) {86 app.listen(3000);87 console.log('Express started on port 3000');88}