56 lines
1.7 KiB
TypeScript
56 lines
1.7 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 });
|
||
}
|
||
|
||
if (username.length < 3 || password.length < 6) {
|
||
return NextResponse.json({ error: '用户名至少3位,密码至少6位' }, { status: 400 });
|
||
}
|
||
|
||
connection = await pool.getConnection();
|
||
|
||
const [rows] = await connection.query<any[]>('SELECT id FROM users WHERE username = ?', [username]);
|
||
|
||
if (rows.length > 0) {
|
||
return NextResponse.json({ error: '用户名已存在' }, { status: 400 });
|
||
}
|
||
|
||
const token = generateToken();
|
||
await connection.query(
|
||
'INSERT INTO users (id, username, password_hash, token, created_at) VALUES (?, ?, ?, ?, ?)',
|
||
[crypto.randomUUID(), username, hashPassword(password), token, new Date()]
|
||
);
|
||
|
||
const response = NextResponse.json({ success: true, username });
|
||
response.cookies.set('auth_token', token, {
|
||
httpOnly: true,
|
||
secure: false,
|
||
sameSite: 'lax',
|
||
maxAge: 60 * 60 * 24 * 7,
|
||
path: '/'
|
||
});
|
||
|
||
return response;
|
||
} catch (error) {
|
||
console.error('Register error:', error);
|
||
return NextResponse.json({ error: '注册失败' }, { status: 500 });
|
||
} finally {
|
||
if (connection) connection.release();
|
||
}
|
||
} |