File size: 3,047 Bytes
4bea261
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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' } }
    );
  }
};