feat: 切换为MariaDB数据库存储

This commit is contained in:
Cuishibing
2026-03-22 22:10:41 +08:00
parent a105f4aecb
commit fbd5f94a43
10 changed files with 346 additions and 299 deletions

View File

@@ -1,26 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
import crypto from 'crypto';
const USERS_FILE = path.join(process.cwd(), 'data/users.json');
interface User {
id: string;
username: string;
passwordHash: string;
token: string;
createdAt: string;
}
async function readUsers(): Promise<User[]> {
try {
const data = await fs.readFile(USERS_FILE, 'utf-8');
return JSON.parse(data);
} catch {
return [];
}
}
import pool from '@/lib/db';
function hashPassword(password: string): string {
return crypto.createHash('sha256').update(password).digest('hex');
@@ -31,6 +11,7 @@ function generateToken(): string {
}
export async function POST(request: NextRequest) {
let connection;
try {
const { username, password } = await request.json();
@@ -38,18 +19,18 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: '用户名和密码不能为空' }, { status: 400 });
}
const users = await readUsers();
const user = users.find(u => u.username === username);
connection = await pool.getConnection();
if (!user || user.passwordHash !== hashPassword(password)) {
const [rows] = await connection.query<any[]>('SELECT * FROM users WHERE username = ?', [username]);
if (rows.length === 0 || rows[0].password_hash !== hashPassword(password)) {
return NextResponse.json({ error: '用户名或密码错误' }, { status: 401 });
}
const newToken = generateToken();
user.token = newToken;
await fs.writeFile(USERS_FILE, JSON.stringify(users, null, 2));
await connection.query('UPDATE users SET token = ? WHERE id = ?', [newToken, rows[0].id]);
const response = NextResponse.json({ success: true, username: user.username });
const response = NextResponse.json({ success: true, username });
response.cookies.set('auth_token', newToken, {
httpOnly: true,
secure: false,
@@ -62,5 +43,7 @@ export async function POST(request: NextRequest) {
} catch (error) {
console.error('Login error:', error);
return NextResponse.json({ error: '登录失败' }, { status: 500 });
} finally {
if (connection) connection.release();
}
}
}