refactor: 优化项目结构和代码
- 更新 .gitignore 文件,排除 Idea 项目配置 - 移除 vuepress 缓存目录 - 优化 app.js 中的错误处理和状态码导入- 调整 CORS 配置,移除未使用的 allowdHeaders - 更新 hashUtils.js 中的密码处理函数 - 优化 index.js 中的路由定义 - 更新 mongodbConfig.js 中的数据库连接逻辑 - 升级 express到 5.0.0- 更新 mongoose 到 8.7.1
This commit is contained in:
parent
352323262c
commit
8741389ef5
2
.gitignore
vendored
2
.gitignore
vendored
@ -102,7 +102,6 @@ dist
|
||||
|
||||
# vuepress v2.x temp and cache directory
|
||||
.temp
|
||||
.cache
|
||||
|
||||
# Docusaurus cache and generated files
|
||||
.docusaurus
|
||||
@ -128,3 +127,4 @@ dist
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.*
|
||||
/.idea/
|
||||
|
||||
8
app.js
8
app.js
@ -15,6 +15,7 @@ require('dotenv').config()
|
||||
// mongodb数据库连接
|
||||
const { connectMongoDB } = require('./config/mongodbConfig')
|
||||
const loginUtil = require('./utils/loginUtil')
|
||||
const { HTTP_STATUS } = require('./common/constant/httpStatus')
|
||||
|
||||
// 初始化 Redis 客户端
|
||||
const redisClient = new Redis({
|
||||
@ -48,8 +49,7 @@ app.use(
|
||||
const corsOptions = {
|
||||
origin: 'http://localhost:5173', // 指定允许的源
|
||||
credentials: true, // 允许发送凭据(如 cookies)
|
||||
optionsSuccessStatus: 200,
|
||||
allowdHeaders: ['Content-Type', 'Authorization']
|
||||
optionsSuccessStatus: 200
|
||||
}
|
||||
|
||||
app.use(cors(corsOptions))
|
||||
@ -63,7 +63,7 @@ async function startServer() {
|
||||
}
|
||||
}
|
||||
|
||||
startServer()
|
||||
startServer().then((r) => logger(r))
|
||||
|
||||
app.use('/', indexRouter)
|
||||
app.use('/user', loginUtil.authenticateSession, userRouter)
|
||||
@ -75,7 +75,7 @@ app.use(function (req, res, next) {
|
||||
})
|
||||
|
||||
// error handler
|
||||
app.use(function (err, req, res, next) {
|
||||
app.use(function (err, req, res) {
|
||||
// set locals, only providing error in development
|
||||
res.locals.message = err.message
|
||||
res.locals.error = req.app.get('env') === 'development' ? err : {}
|
||||
|
||||
57
bin/www
57
bin/www
@ -3,50 +3,47 @@
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var app = require('../app');
|
||||
var debug = require('debug')('express:server');
|
||||
var http = require('http');
|
||||
const app = require('../app')
|
||||
const debug = require('debug')('express:server')
|
||||
const http = require('http')
|
||||
|
||||
/**
|
||||
* Get port from environment and store in Express.
|
||||
*/
|
||||
|
||||
var port = normalizePort(process.env.PORT || '3000');
|
||||
app.set('port', port);
|
||||
const port = normalizePort(process.env.PORT || '3000')
|
||||
app.set('port', port)
|
||||
|
||||
/**
|
||||
* Create HTTP server.
|
||||
*/
|
||||
|
||||
var server = http.createServer(app);
|
||||
const server = http.createServer(app)
|
||||
|
||||
/**
|
||||
* Listen on provided port, on all network interfaces.
|
||||
*/
|
||||
|
||||
server.listen(port);
|
||||
server.on('error', onError);
|
||||
server.on('listening', onListening);
|
||||
server.listen(port)
|
||||
server.on('error', onError)
|
||||
server.on('listening', onListening)
|
||||
|
||||
/**
|
||||
* Normalize a port into a number, string, or false.
|
||||
*/
|
||||
|
||||
function normalizePort(val) {
|
||||
var port = parseInt(val, 10);
|
||||
const port = parseInt(val, 10)
|
||||
|
||||
if (isNaN(port)) {
|
||||
// named pipe
|
||||
return val;
|
||||
return val
|
||||
}
|
||||
|
||||
if (port >= 0) {
|
||||
// port number
|
||||
return port;
|
||||
return port
|
||||
}
|
||||
|
||||
return false;
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
@ -55,25 +52,25 @@ function normalizePort(val) {
|
||||
|
||||
function onError(error) {
|
||||
if (error.syscall !== 'listen') {
|
||||
throw error;
|
||||
throw error
|
||||
}
|
||||
|
||||
var bind = typeof port === 'string'
|
||||
const bind = typeof port === 'string'
|
||||
? 'Pipe ' + port
|
||||
: 'Port ' + port;
|
||||
: 'Port ' + port
|
||||
|
||||
// handle specific listen errors with friendly messages
|
||||
switch (error.code) {
|
||||
case 'EACCES':
|
||||
console.error(bind + ' requires elevated privileges');
|
||||
process.exit(1);
|
||||
break;
|
||||
console.error(bind + ' requires elevated privileges')
|
||||
process.exit(1)
|
||||
break
|
||||
case 'EADDRINUSE':
|
||||
console.error(bind + ' is already in use');
|
||||
process.exit(1);
|
||||
break;
|
||||
console.error(bind + ' is already in use')
|
||||
process.exit(1)
|
||||
break
|
||||
default:
|
||||
throw error;
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@ -82,9 +79,9 @@ function onError(error) {
|
||||
*/
|
||||
|
||||
function onListening() {
|
||||
var addr = server.address();
|
||||
var bind = typeof addr === 'string'
|
||||
const addr = server.address()
|
||||
const bind = typeof addr === 'string'
|
||||
? 'pipe ' + addr
|
||||
: 'port ' + addr.port;
|
||||
debug('Listening on ' + bind);
|
||||
: 'port ' + addr.port
|
||||
debug('Listening on ' + bind)
|
||||
}
|
||||
|
||||
@ -23,7 +23,7 @@ exports.connectMongoDB = async function () {
|
||||
try {
|
||||
const mongoDBUrl = `mongodb://${account}:${password}@${host}:${port}`
|
||||
|
||||
mongoose.connect(mongoDBUrl)
|
||||
await mongoose.connect(mongoDBUrl)
|
||||
|
||||
mongoose.connection.on('open', () => {
|
||||
console.log('MongoDB 连接成功')
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
const { body, validationResult } = require('express-validator')
|
||||
const logger = require('morgan')
|
||||
const userService = require('../services/userService')
|
||||
const FetchResult = require('../common/web/fetchResult')
|
||||
const messages = require('../config/messages')
|
||||
@ -50,7 +51,7 @@ exports.createUser = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
const user = req.body
|
||||
await userService.create_user(user)
|
||||
await userService.createUser(user)
|
||||
return FetchResult.formatResult(res, HTTP_STATUS.CREATED, messages.user.created)
|
||||
} catch (err) {
|
||||
logger('Error creating user: ', err)
|
||||
@ -88,9 +89,7 @@ exports.login = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
const { account, password } = req.body
|
||||
|
||||
const user = await userService.login(account, password)
|
||||
req.session.user = user
|
||||
req.session.user = await userService.login(account, password)
|
||||
return FetchResult.formatResult(res, 200, messages.user.login)
|
||||
} catch (err) {
|
||||
if (err.message === messages.user.not_found) {
|
||||
|
||||
@ -22,8 +22,7 @@ UserSchema.pre('save', async function (next) {
|
||||
try {
|
||||
console.log(user.password)
|
||||
|
||||
const hashedPassword = await hashPassword(user.password)
|
||||
user.password = hashedPassword
|
||||
user.password = await hashPassword(user.password)
|
||||
next()
|
||||
} catch (error) {
|
||||
next(error)
|
||||
|
||||
929
package-lock.json
generated
929
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -13,14 +13,14 @@
|
||||
"cors": "^2.8.5",
|
||||
"debug": "~2.6.9",
|
||||
"dotenv": "^16.4.7",
|
||||
"express": "^4.19.2",
|
||||
"express": "5.0.0",
|
||||
"express-async-handler": "^1.2.0",
|
||||
"express-session": "^1.18.1",
|
||||
"express-validator": "^7.2.0",
|
||||
"http-errors": "~1.6.3",
|
||||
"ioredis": "^5.4.2",
|
||||
"jade": "^0.29.0",
|
||||
"mongoose": "^8.3.4",
|
||||
"mongoose": "8.7.1",
|
||||
"morgan": "~1.9.1",
|
||||
"nodemon": "^3.1.0",
|
||||
"redis": "^4.7.0"
|
||||
|
||||
@ -2,21 +2,21 @@ const UserModel = require('../models/userModel')
|
||||
const { SearchResult } = require('../models/Search')
|
||||
|
||||
exports.startTransaction = async () => {
|
||||
const seesion = await UserModel.startSession()
|
||||
seesion.startTransaction()
|
||||
return seesion
|
||||
const session = await UserModel.startSession()
|
||||
session.startTransaction()
|
||||
return session
|
||||
}
|
||||
|
||||
exports.commitTransaction = async (session) => {
|
||||
return await session.commitTransaction()
|
||||
return session.commitTransaction()
|
||||
}
|
||||
|
||||
exports.rollbackTransaction = async (session) => {
|
||||
return await session.abortTransaction()
|
||||
return session.abortTransaction()
|
||||
}
|
||||
|
||||
exports.selectAllUser = async () => {
|
||||
return await UserModel.find()
|
||||
return UserModel.find()
|
||||
}
|
||||
|
||||
exports.selectUserList = async (search = {}) => {
|
||||
@ -58,23 +58,23 @@ exports.selectUserList = async (search = {}) => {
|
||||
}
|
||||
|
||||
exports.selectUserById = async (id) => {
|
||||
return await UserModel.findById(id)
|
||||
return UserModel.findById(id)
|
||||
}
|
||||
|
||||
exports.selectUserByAccount = async (account) => {
|
||||
return await UserModel.findOne({ account: account })
|
||||
return UserModel.findOne({ account: account })
|
||||
}
|
||||
|
||||
exports.selectUserByEmail = async (email) => {
|
||||
return await UserModel.findOne({ email: email })
|
||||
return UserModel.findOne({ email: email })
|
||||
}
|
||||
|
||||
exports.selectUserByUsername = async (username) => {
|
||||
return await UserModel.findOne({ username: username })
|
||||
return UserModel.findOne({ username: username })
|
||||
}
|
||||
|
||||
exports.selectUserByPhone = async (phone) => {
|
||||
return await UserModel.findOne({ phone: phone })
|
||||
return UserModel.findOne({ phone: phone })
|
||||
}
|
||||
|
||||
exports.selectUserByAccountExist = async (account) => {
|
||||
@ -83,21 +83,21 @@ exports.selectUserByAccountExist = async (account) => {
|
||||
}
|
||||
|
||||
exports.createUser = async (user) => {
|
||||
return await UserModel.create(user)
|
||||
return UserModel.create(user)
|
||||
}
|
||||
|
||||
exports.updateUserById = async (id, user) => {
|
||||
return await UserModel.findByIdAndUpdate(id, user)
|
||||
return UserModel.findByIdAndUpdate(id, user)
|
||||
}
|
||||
|
||||
exports.updateUserByLoginDate = async (id, loginDate) => {
|
||||
return await UserModel.findByIdAndUpdate(id, { last_login_date: loginDate })
|
||||
return UserModel.findByIdAndUpdate(id, { last_login_date: loginDate })
|
||||
}
|
||||
|
||||
exports.deleteUserById = async (id) => {
|
||||
return await UserModel.findByIdAndDelete(id)
|
||||
return UserModel.findByIdAndDelete(id)
|
||||
}
|
||||
|
||||
exports.deleteAllUser = async () => {
|
||||
return await UserModel.deleteMany()
|
||||
return UserModel.deleteMany()
|
||||
}
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
var express = require('express')
|
||||
var router = express.Router()
|
||||
const express = require('express')
|
||||
const router = express.Router()
|
||||
const userController = require('../controllers/userController')
|
||||
|
||||
router.get('/', function (req, res, next) {
|
||||
router.get('/', function (req, res) {
|
||||
if (!req.session.views) {
|
||||
req.session.views = 1
|
||||
} else {
|
||||
|
||||
@ -2,7 +2,6 @@ const userMapper = require('../repositories/userRepository')
|
||||
const logger = require('morgan')
|
||||
const messages = require('../config/messages')
|
||||
const { comparePassword } = require('../utils/hashUtils')
|
||||
const { SearchQuery } = require('../models/Search')
|
||||
|
||||
/**
|
||||
* 用户登录
|
||||
@ -64,7 +63,7 @@ exports.createUser = async (user) => {
|
||||
// 检查用户是否已存在
|
||||
const existingUser = await userMapper.selectUserByAccount(account)
|
||||
if (existingUser) {
|
||||
throw new Error(messages.user.already_exists)
|
||||
return new Error(messages.user.already_exists)
|
||||
}
|
||||
|
||||
// 创建新用户
|
||||
|
||||
@ -9,11 +9,11 @@ exports.isNotEmpty = function (obj) {
|
||||
}
|
||||
|
||||
if (obj instanceof String) {
|
||||
return obj === '' ? false : true
|
||||
return obj !== ''
|
||||
}
|
||||
|
||||
if (obj instanceof Array) {
|
||||
return Array.length(obj) === 0 ? false : true
|
||||
return Array.length(obj) !== 0
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@ -2,21 +2,19 @@ const bcrypt = require('bcrypt')
|
||||
|
||||
async function hashPassword(password) {
|
||||
try {
|
||||
const hashedPassword = await bcrypt.hash(password, 10)
|
||||
return hashedPassword
|
||||
} catch (error) {
|
||||
console.error('Error hashing password:', error)
|
||||
throw error // 重新抛出错误以便调用方处理
|
||||
return await bcrypt.hash(password, 10)
|
||||
} catch (err) {
|
||||
console.error('Error hashing password:', err)
|
||||
throw err // 重新抛出错误以便调用方处理
|
||||
}
|
||||
}
|
||||
|
||||
async function comparePassword(password, hashedPassword) {
|
||||
try {
|
||||
const isMatch = await bcrypt.compare(password, hashedPassword)
|
||||
return isMatch
|
||||
} catch (error) {
|
||||
console.error('Error comparing password:', error)
|
||||
throw error // 重新抛出错误以便调用方处理
|
||||
return await bcrypt.compare(password, hashedPassword)
|
||||
} catch (err) {
|
||||
console.error('Error comparing password:', err)
|
||||
throw err // 重新抛出错误以便调用方处理
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user