Spaces:
Sleeping
Sleeping
| import crypto from 'node:crypto'; | |
| import { txasupabase } from '../../../lib/txasupabase.js'; | |
| export const POST = async ({ request }) => { | |
| try { | |
| const body = await request.json(); | |
| const { username, email, password, province, ward } = body; | |
| // Kiểm tra dữ liệu đầu vào phía Backend | |
| if (!username || !email || !password) { | |
| return new Response( | |
| JSON.stringify({ error: 'Thiếu thông tin đăng ký bắt buộc!' }), | |
| { status: 400, headers: { 'Content-Type': 'application/json' } } | |
| ); | |
| } | |
| // Kiểm tra miền email được phép | |
| const allowedDomains = ['gmail.com', 'outlook.com', 'icloud.com', 'hotmail.com.vn']; | |
| const emailDomain = email.split('@')[1]?.toLowerCase(); | |
| if (!allowedDomains.includes(emailDomain)) { | |
| return new Response( | |
| JSON.stringify({ error: 'Chỉ chấp nhận đăng ký bằng các email thuộc: gmail.com, outlook.com, icloud.com, hotmail.com.vn!' }), | |
| { status: 400, headers: { 'Content-Type': 'application/json' } } | |
| ); | |
| } | |
| // Kiểm tra trùng lặp tài khoản hoặc email trong hệ thống | |
| const { data: existingUser, error: checkError } = await txasupabase.supabase | |
| .from('users') | |
| .select('username, email') | |
| .or(`username.eq.${username},email.eq.${email}`) | |
| .maybeSingle(); | |
| if (checkError) { | |
| throw checkError; | |
| } | |
| if (existingUser) { | |
| if (existingUser.username.toLowerCase() === username.toLowerCase()) { | |
| return new Response( | |
| JSON.stringify({ error: 'Tên tài khoản này đã có người đăng ký rồi bạn ơi!' }), | |
| { status: 400, headers: { 'Content-Type': 'application/json' } } | |
| ); | |
| } | |
| if (existingUser.email.toLowerCase() === email.toLowerCase()) { | |
| return new Response( | |
| JSON.stringify({ error: 'Địa chỉ Email này đã tồn tại trên hệ thống!' }), | |
| { status: 400, headers: { 'Content-Type': 'application/json' } } | |
| ); | |
| } | |
| } | |
| // Tiến hành băm mật khẩu (Mã hóa SHA-256) | |
| const hashedPassword = crypto.createHash('sha256').update(password).digest('hex'); | |
| // Khởi tạo Object cấu trúc User mới và lưu vào Supabase | |
| const newUser = { | |
| id: crypto.randomUUID(), | |
| username, | |
| email, | |
| password: hashedPassword, | |
| province: province || '', | |
| ward: ward || '', | |
| role: 'user', | |
| favorites: [], | |
| history: [], | |
| createdAt: new Date().toISOString() | |
| }; | |
| await txasupabase.saveUser(newUser); | |
| return new Response( | |
| JSON.stringify({ message: 'Tạo tài khoản thành công!', user: { username, email } }), | |
| { status: 201, headers: { 'Content-Type': 'application/json' } } | |
| ); | |
| } catch (error) { | |
| console.error('[Auth Register Error]:', error); | |
| return new Response( | |
| JSON.stringify({ error: 'Gặp sự cố lỗi hệ thống khi đăng ký!' }), | |
| { status: 500, headers: { 'Content-Type': 'application/json' } } | |
| ); | |
| } | |
| }; |