sec commit
This commit is contained in:
85
shared/code/backend/user-auth.js
Normal file
85
shared/code/backend/user-auth.js
Normal file
@@ -0,0 +1,85 @@
|
||||
// 用户认证模块 - 后端代码
|
||||
// 文件位置: shared/code/backend/user-auth.js
|
||||
// 创建时间: 2026-03-31 20:56
|
||||
// 开发者: 后端工程师 (BE)
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
// 用户登录接口
|
||||
router.post('/login', async (req, res) => {
|
||||
try {
|
||||
const { username, password } = req.body;
|
||||
|
||||
// 验证用户凭据
|
||||
const user = await validateCredentials(username, password);
|
||||
|
||||
if (!user) {
|
||||
return res.status(401).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
// 生成JWT token
|
||||
const token = jwt.sign(
|
||||
{ userId: user.id, username: user.username },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '7d' }
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
token,
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
email: user.email
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// 用户注册接口
|
||||
router.post('/register', async (req, res) => {
|
||||
try {
|
||||
const { username, password, email } = req.body;
|
||||
|
||||
// 检查用户是否已存在
|
||||
const existingUser = await findUserByUsername(username);
|
||||
if (existingUser) {
|
||||
return res.status(400).json({ error: 'Username already exists' });
|
||||
}
|
||||
|
||||
// 创建新用户
|
||||
const newUser = await createUser({ username, password, email });
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'User registered successfully',
|
||||
userId: newUser.id
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Registration error:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// 辅助函数
|
||||
async function validateCredentials(username, password) {
|
||||
// 实际实现中这里会查询数据库
|
||||
return { id: 1, username: 'testuser', email: 'test@example.com' };
|
||||
}
|
||||
|
||||
async function findUserByUsername(username) {
|
||||
// 实际实现中这里会查询数据库
|
||||
return null;
|
||||
}
|
||||
|
||||
async function createUser(userData) {
|
||||
// 实际实现中这里会插入数据库
|
||||
return { id: 1, ...userData };
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user