Spaces:
Sleeping
Sleeping
| import { txasupabase } from '../../../lib/txasupabase.js'; | |
| export const POST = async ({ request }) => { | |
| try { | |
| const body = await request.json(); | |
| const { browser_token, zalo_nickname } = body; | |
| if (!browser_token || !zalo_nickname) { | |
| return new Response(JSON.stringify({ error: 'Thiếu thông tin yêu cầu!' }), { | |
| status: 400, | |
| headers: { 'Content-Type': 'application/json' } | |
| }); | |
| } | |
| // 1. Tạo hoặc cập nhật request vào database | |
| const accessRequest = await txasupabase.createZaloAccessRequest(browser_token, zalo_nickname); | |
| // 2. Ghi lại log hoạt động hệ thống | |
| await txasupabase.createLog( | |
| 'zalo_access_request', | |
| 'info', | |
| `Thành viên Zalo "${zalo_nickname}" gửi yêu cầu truy cập từ trình duyệt ${browser_token}`, | |
| { browser_token, zalo_nickname } | |
| ); | |
| // 3. Gửi email thông báo cho Admin | |
| try { | |
| const settings = await txasupabase.getSettings(); | |
| // Tìm email Admin nhận thông báo | |
| let adminEmail = settings.admin_email || settings.smtp_user; | |
| if (!adminEmail) { | |
| // Tìm user admin đầu tiên từ DB làm dự phòng | |
| const { data: adminUsers } = await txasupabase.supabase | |
| .from('users') | |
| .select('email') | |
| .eq('role', 'admin') | |
| .limit(1); | |
| if (adminUsers && adminUsers.length > 0) { | |
| adminEmail = adminUsers[0].email; | |
| } | |
| } | |
| if (adminEmail && settings.smtp_user && settings.smtp_pass) { | |
| const siteUrl = settings.site_url || 'http://localhost:4321'; | |
| const approveUrl = `${siteUrl}/admin/duyet-zalo`; // Trang duyệt chuyên dụng riêng biệt | |
| await txasupabase.sendMail({ | |
| to: adminEmail, | |
| subject: `[TPHIMX] Yêu cầu duyệt quyền truy cập mới từ Zalo: ${zalo_nickname}`, | |
| templateName: 'zalo_access_request', | |
| placeholders: { | |
| zalo_nickname, | |
| browser_token, | |
| request_time: new Date().toLocaleString('vi-VN'), | |
| approve_url: approveUrl | |
| } | |
| }); | |
| } else { | |
| console.log('[Access Request API]: SMTP not configured or Admin email missing, skipped email notification.'); | |
| } | |
| } catch (mailErr) { | |
| console.error('[Access Request Mail Error]:', mailErr); | |
| await txasupabase.createLog( | |
| 'zalo_access_request_mail_failed', | |
| 'warn', | |
| `Lỗi gửi mail thông báo Zalo access cho "${zalo_nickname}": ${mailErr.message}` | |
| ); | |
| } | |
| return new Response(JSON.stringify({ | |
| success: true, | |
| message: 'Gửi yêu cầu thành công! Vui lòng chờ Admin duyệt nick Zalo của bạn.', | |
| data: accessRequest | |
| }), { | |
| status: 200, | |
| headers: { 'Content-Type': 'application/json' } | |
| }); | |
| } catch (err) { | |
| console.error('Error handling access request API:', err); | |
| return new Response(JSON.stringify({ error: 'Có lỗi xảy ra trên hệ thống!' }), { | |
| status: 500, | |
| headers: { 'Content-Type': 'application/json' } | |
| }); | |
| } | |
| }; | |