65 lines
1.6 KiB
JavaScript
65 lines
1.6 KiB
JavaScript
const express = require('express');
|
|
const session = require('express-session');
|
|
const bodyParser = require('body-parser');
|
|
|
|
const app = express();
|
|
const port = 3000;
|
|
|
|
// 设置中间件
|
|
app.use(bodyParser.urlencoded({ extended: false }));
|
|
app.use(bodyParser.json());
|
|
|
|
// 配置 session 中间件
|
|
app.use(session({
|
|
secret: 'hello kitty',
|
|
resave: false,
|
|
saveUninitialized: true,
|
|
cookie: { secure: false } // 在生产环境中设置为 true
|
|
}));
|
|
|
|
|
|
// 创建登录接口
|
|
app.post('/login', (req, res) => {
|
|
const { username, password } = req.body;
|
|
|
|
if (username === 'admin' && password === '123456') {
|
|
req.session.user = { id: 1, username };
|
|
res.send('User logged in');
|
|
} else {
|
|
res.status(401).send('Invalid credentials');
|
|
}
|
|
});
|
|
|
|
// 创建注销接口
|
|
app.post('/logout', (req, res) => {
|
|
req.session.destroy((err) => {
|
|
if (err) {
|
|
return res.status(500).send('Could not log out.');
|
|
}
|
|
res.send('Logout successful');
|
|
});
|
|
});
|
|
|
|
// 认证中间件
|
|
function isAuthenticated(req, res, next) {
|
|
if (req.session.user) {
|
|
next();
|
|
} else {
|
|
res.status(401).send('You are not authenticated!');
|
|
}
|
|
}
|
|
|
|
// 创建保护路由
|
|
app.get('/protected', isAuthenticated, (req, res) => {
|
|
res.send('This is a protected route');
|
|
});
|
|
|
|
// 实现基于 Session 的身份认证机制
|
|
app.get('/profile', isAuthenticated, (req, res) => {
|
|
res.send(`Welcome ${req.session.user.username}`);
|
|
});
|
|
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Server is running on http://localhost:${port}`);
|
|
}); |