connect中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var connect = require("connect");
var app = connect();



function logger(req,res,next){
console.log('logger');
next()
}
function hello(req,res){
console.log('hello');
res.end("Hello World!");
}

function authenticateWithDatabase(user, pass, callback) {
var err;
if (user != 'tobi' || pass != 'ferret') {
err = new Error('Unauthorized');
}
callback(err);
}

function restrict(req,res,next){
var authorization = req.headers.authorization;
if( !authorization ){
return next(new Error('Unathorized'));
}
var parts = authorization.split(' ');
var scheme = parts[0];
var auth = new Buffer(parts[1],'base64').toString().split(":");
var user = auth[0];
var pass = auth[1];

authenticateWithDatabase(user,pass,function(err){
if(err){
return next(err);
}
next()
});
}
function admin(req,res,next){
switch (req.url) {
case '/':
res.end('try /users');
break;
case '/users':
res.setHeader('Content-tyep','application/json');
res.end(JSON.stringify(['tobi','loki','jane']))
break;
}
}

app.use(logger)
.use('/admin',restrict)
.use('/admin',admin)
.use(hello)
app.listen(8080);