-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver-3.js
71 lines (62 loc) · 1.78 KB
/
server-3.js
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Created by liyang9 on 2016/10/17.
*/
var express = require('express');
var morgan = require('morgan');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var hostname = 'localhost';
var port = 3000;
var app = express();
app.use(morgan('dev'));
app.use(session({
name:'session-id',
secret: '12345-67890-09876-54321',
saveUninitialized: true,
resave: true,
store: new FileStore()
}));
function auth (req, res, next) {
console.log(req.headers);
if( !req.session.user) {
var authHeader = req.headers.authorization;
if( !authHeader ){
var err = new Error('You are not authenticated!');
err.status = 401;
next(err);
return ;
}
var auth = new Buffer(authHeader.split(' ')[1],'base64').toString().split(':');
var user = auth[0];
var passwd = auth[1];
if (user == 'admin' && passwd == 'admin') {
req.session.user = 'admin';
next();
} else {
var err = new Error('You are not authenticated');
err.status = 401;
next(err);
}
}else {
if(req.session.user =='admin') {
console.log('req.session: ', req.session);
next();
} else {
var err = new Error('You are not authenticated!');
err.status = 401;
next(err);
}
}
}
app.use(auth);
app.use(express.static(__dirname + '/public'));
app.use(function (err, req, res, next) {
res.writeHead(err.status || 500 , {
'WWW-Authenticate':'Basic',
'Content-Type':'text/plain'
});
res.end(err.message);
});
app.listen(port, hostname, function () {
console.log(`server start at htt://${hostname}:${port}/`);
})