refactor(user): 重构用户相关代码并优化登录功能

- 移除 app.js 中的冗余配置
- 更新 userController.js 中的导入和函数名称
- 修改 Search.js 中的类名
- 重构 userService.js 中的 login 和其他用户相关函数
- 优化错误处理和事务管理
This commit is contained in:
LingandRX 2025-01-01 12:04:27 +08:00
parent 3cd150b106
commit 352323262c
4 changed files with 61 additions and 73 deletions

6
app.js
View File

@ -34,12 +34,11 @@ app.use(cookieParser())
app.use( app.use(
session({ session({
name: 'identityKey', name: 'identityKey',
store: new RedisStore({ client: redisClient }), // 正确的方式,不要使用 new RedisStore(),直接传递配置 store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET, secret: process.env.SESSION_SECRET,
resave: false, resave: false,
saveUninitialized: false, saveUninitialized: false,
cookie: { cookie: {
secure: false,
httpOnly: true, httpOnly: true,
maxAge: 24 * 60 * 60 * 1000 maxAge: 24 * 60 * 60 * 1000
} }
@ -49,7 +48,8 @@ app.use(
const corsOptions = { const corsOptions = {
origin: 'http://localhost:5173', // 指定允许的源 origin: 'http://localhost:5173', // 指定允许的源
credentials: true, // 允许发送凭据(如 cookies credentials: true, // 允许发送凭据(如 cookies
optionsSuccessStatus: 200 // 一些旧的浏览器IE11, various SmartTVs需要这个 optionsSuccessStatus: 200,
allowdHeaders: ['Content-Type', 'Authorization']
} }
app.use(cors(corsOptions)) app.use(cors(corsOptions))

View File

@ -3,7 +3,7 @@ const userService = require('../services/userService')
const FetchResult = require('../common/web/fetchResult') const FetchResult = require('../common/web/fetchResult')
const messages = require('../config/messages') const messages = require('../config/messages')
const { HTTP_STATUS } = require('../common/constant/httpStatus') const { HTTP_STATUS } = require('../common/constant/httpStatus')
const { Search } = require('../models/Search') const { SearchQuery } = require('../models/Search')
exports.getAllUsers = async (res) => { exports.getAllUsers = async (res) => {
try { try {
@ -17,8 +17,8 @@ exports.getAllUsers = async (res) => {
exports.findUserList = async (req, res) => { exports.findUserList = async (req, res) => {
try { try {
const { page, size, sort } = req.query const { page, size, sort } = req.query
const search = new Search({ page: page, size: size, sort: sort }) const search = new SearchQuery({ page: page, size: size, sort: sort })
const result = await userService.find_user_list(search) const result = await userService.getUserList(search)
return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, 'success', result) return FetchResult.formatResult(res, HTTP_STATUS.ACCEPTED, 'success', result)
} catch (err) { } catch (err) {
console.log(err) console.log(err)

View File

@ -1,4 +1,4 @@
class Search { class SearchQuery {
constructor({ size, page, sort, filters }) { constructor({ size, page, sort, filters }) {
this.size = size this.size = size
this.page = page this.page = page
@ -29,4 +29,4 @@ class SearchResult {
} }
} }
module.exports = { Search, SearchResult } module.exports = { SearchQuery, SearchResult }

View File

@ -2,35 +2,34 @@ const userMapper = require('../repositories/userRepository')
const logger = require('morgan') const logger = require('morgan')
const messages = require('../config/messages') const messages = require('../config/messages')
const { comparePassword } = require('../utils/hashUtils') const { comparePassword } = require('../utils/hashUtils')
const { SearchQuery } = require('../models/Search')
/** /**
* @param {string} account * 用户登录
* @param {string} password * @param {string} account - 用户账号
* @returns {Promise<object>} * @param {string} password - 用户密码
* @returns {Promise<Object>} - 登录成功返回用户信息
* @throws {Error} - 如果用户不存在或密码不正确
*/ */
exports.login = async (account, password) => { exports.login = async (account, password) => {
try { const user = await userMapper.selectUserByAccount(account)
const user = await userMapper.selectUserByAccount(account)
if (!user) { // 用户不存在
throw new Error(messages.user.not_found) if (!user) {
} throw new Error(messages.user.not_found)
const isMatch = await comparePassword(password, user.password)
if (!isMatch) {
throw new Error(messages.user.password_incorrect)
}
user.last_login_date = new Date()
await userMapper.updateUserByLoginDate(user.id, user.last_login_date)
return user
} catch (err) {
logger('Error logging in: ', err)
throw err
} }
// 密码不匹配
const isMatch = await comparePassword(password, user.password)
if (!isMatch) {
throw new Error(messages.user.password_incorrect)
}
// 更新用户的最后登录时间
user.last_login_date = new Date()
await userMapper.updateUserByLoginDate(user.id, user.last_login_date)
return user
} }
/** /**
@ -39,57 +38,46 @@ exports.login = async (account, password) => {
* @returns {Promise<boolean>} * @returns {Promise<boolean>}
*/ */
exports.get_user_exist = async (account) => { exports.get_user_exist = async (account) => {
try { return userMapper.selectUserByAccountExist(account)
return await userMapper.selectUserByAccountExist(account)
} catch (err) {
throw err
}
} }
// Removed the unnecessary try-catch block and simplified the function
exports.user_list = async () => { exports.user_list = async () => {
try { return await userMapper.selectAllUser()
const list_users = await userMapper.selectAllUser()
return list_users
} catch (err) {
throw err
}
} }
exports.find_user_list = async (search) => { exports.getUserList = async (searchQuery) => {
try { return userMapper.selectUserList(searchQuery)
return await userMapper.selectUserList(search)
} catch (err) {
throw err
}
} }
exports.create_user = async (user) => { /**
* 创建用户
* @param {Object} user - 用户对象
* @returns {Promise<Object>} - 创建成功的用户信息
* @throws {Error} - 如果用户已存在或事务失败
*/
exports.createUser = async (user) => {
const { account } = user
const session = await userMapper.startTransaction()
try { try {
const { account } = user // 检查用户是否已存在
const existingUser = await userMapper.selectUserByAccount(account)
const session = await userMapper.startTransaction() if (existingUser) {
throw new Error(messages.user.already_exists)
try {
const check_user = await userMapper.selectUserByAccount(account)
if (check_user) {
throw new Error(messages.user.already_exists)
}
const result = await userMapper.createUser(user)
await userMapper.commitTransaction(session)
return result
} catch (err) {
try {
await userMapper.rollbackTransaction(session)
} catch (roolbackErr) {
logger('Error rolling back transaction: ', roolbackErr)
}
throw err
} }
// 创建新用户
const result = await userMapper.createUser(user)
// 提交事务
await userMapper.commitTransaction(session)
return result
} catch (err) { } catch (err) {
logger('Error creating user: ', err) // 回滚事务
throw err await userMapper.rollbackTransaction(session).catch((rollbackErr) => {
logger('Error rolling back transaction: ', rollbackErr)
})
throw err // 将错误抛给调用方Controller 层)
} }
} }