49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import crypto from 'crypto';
|
|
import pool from '@/lib/db';
|
|
|
|
function hashPassword(password: string): string {
|
|
return crypto.createHash('sha256').update(password).digest('hex');
|
|
}
|
|
|
|
function generateToken(): string {
|
|
return crypto.randomBytes(32).toString('hex');
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
let connection;
|
|
try {
|
|
const { username, password } = await request.json();
|
|
|
|
if (!username || !password) {
|
|
return NextResponse.json({ error: '用户名和密码不能为空' }, { status: 400 });
|
|
}
|
|
|
|
connection = await pool.getConnection();
|
|
|
|
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();
|
|
await connection.query('UPDATE users SET token = ? WHERE id = ?', [newToken, rows[0].id]);
|
|
|
|
const response = NextResponse.json({ success: true, username });
|
|
response.cookies.set('auth_token', newToken, {
|
|
httpOnly: true,
|
|
secure: false,
|
|
sameSite: 'lax',
|
|
maxAge: 60 * 60 * 24 * 7,
|
|
path: '/'
|
|
});
|
|
|
|
return response;
|
|
} catch (error) {
|
|
console.error('Login error:', error);
|
|
return NextResponse.json({ error: '登录失败' }, { status: 500 });
|
|
} finally {
|
|
if (connection) connection.release();
|
|
}
|
|
} |