Files
Nexus_Mat/pages/api/v1/auth/register.ts
SpecialX d2468e9fca
Some checks failed
docker-push / build-and-push (push) Failing after 18s
docker-push / deploy (push) Has been skipped
fix: user registration with email support
2025-11-28 19:29:49 +08:00

72 lines
2.6 KiB
TypeScript

import { NextApiRequest, NextApiResponse } from 'next';
import { UserService } from '../../../../backend/services/userService';
import { generateToken } from '../../../../lib/auth';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ success: false, error: 'Method not allowed' });
}
try {
const { username, password, email } = req.body;
// Validate input
if (!username || !password) {
return res.status(400).json({ success: false, error: 'Username and password are required' });
}
if (username.length < 3) {
return res.status(400).json({ success: false, error: 'Username must be at least 3 characters' });
}
if (password.length < 6) {
return res.status(400).json({ success: false, error: 'Password must be at least 6 characters' });
}
if (email && !email.includes('@')) {
return res.status(400).json({ success: false, error: 'Invalid email format' });
}
// Check if username already exists
const existingUser = await UserService.getUserByUsername(username);
if (existingUser) {
return res.status(409).json({ success: false, error: 'Username already taken' });
}
if (email) {
const existingEmail = await UserService.getUserByEmail(email);
if (existingEmail) {
return res.status(409).json({ success: false, error: 'Email already registered' });
}
}
// Create new user
const user = await UserService.createUser(username, password, email);
// Generate JWT token
const token = generateToken(user.id);
// Set HTTP-only cookie
res.setHeader('Set-Cookie', `token=${token}; HttpOnly; Path=/; Max-Age=${7 * 24 * 60 * 60}; SameSite=Strict`);
// Return user data (without password)
return res.status(201).json({
success: true,
data: {
user: {
id: user.id,
username: user.username,
email: user.email,
avatarUrl: user.avatarUrl,
role: user.role,
status: user.status
},
token // Also return token in body for non-cookie clients
}
});
} catch (error) {
console.error('Registration error details:', error);
return res.status(500).json({ success: false, error: 'Registration failed' });
}
}