// 导入必要的模块
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const winston = require('winston');
const expressWinston = require('express-winston');
// 创建Express应用
const app = express();
// 配置body-parser中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 配置express-session中间件
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 1000 * 60 * 60 } // 设置session的有效期为1小时
}));
// 配置passport本地策略中间件
passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
// 实现用户验证逻辑
// 例如,通过数据库查询用户信息
User.findOne({ email: email.toLowerCase() }, (err, user) => {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: '无效的邮箱地址' });
}
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) { return done(err); }
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: '密码错误' });
}
});
});
}));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
// 配置passport中间件
app.use(passport.initialize());
app.use(passport.session());
// 配置日志中间件
const myLogger = expressWinston.logger({
transports: [new winston.transports.Console()],
format: winston.format.json(),
meta: true, // optional: control whether you want to log the meta data about the request (default true)
msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will remove time from meta log.
colorStatus: true, // Color the status code, using the Express/morgan color palette (default green, red, blue, cyan)
// ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or respo