67 lines
1.8 KiB
TypeScript
67 lines
1.8 KiB
TypeScript
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 [];
|
|
}
|
|
}
|
|
|
|
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) {
|
|
try {
|
|
const { username, password } = await request.json();
|
|
|
|
if (!username || !password) {
|
|
return NextResponse.json({ error: '用户名和密码不能为空' }, { status: 400 });
|
|
}
|
|
|
|
const users = await readUsers();
|
|
const user = users.find(u => u.username === username);
|
|
|
|
if (!user || user.passwordHash !== hashPassword(password)) {
|
|
return NextResponse.json({ error: '用户名或密码错误' }, { status: 401 });
|
|
}
|
|
|
|
const newToken = generateToken();
|
|
user.token = newToken;
|
|
await fs.writeFile(USERS_FILE, JSON.stringify(users, null, 2));
|
|
|
|
const response = NextResponse.json({ success: true, username: user.username });
|
|
response.cookies.set('auth_token', newToken, {
|
|
httpOnly: true,
|
|
secure: process.env.NODE_ENV === 'production',
|
|
sameSite: 'lax',
|
|
maxAge: 60 * 60 * 24 * 7,
|
|
path: '/'
|
|
});
|
|
|
|
return response;
|
|
} catch (error) {
|
|
console.error('Login error:', error);
|
|
return NextResponse.json({ error: '登录失败' }, { status: 500 });
|
|
}
|
|
}
|