Files
smalltown/app/api/auth/register/route.ts

83 lines
2.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
import crypto from 'crypto';
const DATA_DIR = path.join(process.cwd(), 'data');
const USERS_FILE = path.join(DATA_DIR, '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 [];
}
}
async function writeUsers(users: User[]): Promise<void> {
await fs.writeFile(USERS_FILE, JSON.stringify(users, null, 2));
}
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 });
}
if (username.length < 3 || password.length < 6) {
return NextResponse.json({ error: '用户名至少3位密码至少6位' }, { status: 400 });
}
const users = await readUsers();
if (users.find(u => u.username === username)) {
return NextResponse.json({ error: '用户名已存在' }, { status: 400 });
}
const token = generateToken();
const newUser: User = {
id: crypto.randomUUID(),
username,
passwordHash: hashPassword(password),
token,
createdAt: new Date().toISOString()
};
users.push(newUser);
await writeUsers(users);
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 });
}
}