Spaces:
Sleeping
Sleeping
| import crypto from 'node:crypto'; | |
| import { txasupabase } from '../../../lib/txasupabase.js'; | |
| export const POST = async ({ request, cookies }) => { | |
| try { | |
| const body = await request.json(); | |
| const { identity, password } = body; | |
| // Kiểm tra dữ liệu rỗng đầu vào | |
| if (!identity || !password) { | |
| return new Response( | |
| JSON.stringify({ error: 'Vui lòng điền đầy đủ tài khoản và mật khẩu nha!' }), | |
| { status: 400, headers: { 'Content-Type': 'application/json' } } | |
| ); | |
| } | |
| // Mã hóa mật khẩu đầu vào bằng SHA-256 để so sánh | |
| const hashedPassword = crypto.createHash('sha256').update(password).digest('hex'); | |
| // Tìm kiếm tài khoản trùng khớp (Username hoặc Email) | |
| const { data: user, error } = await txasupabase.supabase | |
| .from('users') | |
| .select('*') | |
| .or(`username.eq.${identity},email.eq.${identity}`) | |
| .eq('password', hashedPassword) | |
| .maybeSingle(); | |
| if (error || !user) { | |
| return new Response( | |
| JSON.stringify({ error: 'Tài khoản hoặc mật khẩu không chính xác rồi bạn ơi!' }), | |
| { status: 401, headers: { 'Content-Type': 'application/json' } } | |
| ); | |
| } | |
| // Khởi tạo thông tin Session đơn giản (Mã hóa Base64) | |
| const userData = { id: user.id, username: user.username, email: user.email, role: user.role, avatar_url: user.avatar_url }; | |
| const token = Buffer.from(JSON.stringify(userData)).toString('base64'); | |
| // Thiết lập HTTP-Only Cookie đảm bảo an toàn bảo mật | |
| cookies.set('auth_token', token, { | |
| path: '/', | |
| httpOnly: true, | |
| secure: process.env.NODE_ENV === 'production', | |
| sameSite: 'lax', | |
| maxAge: 60 * 60 * 24 * 7 // Hiệu lực trong 1 tuần | |
| }); | |
| return new Response( | |
| JSON.stringify({ message: 'Đăng nhập thành công!', user: userData }), | |
| { status: 200, headers: { 'Content-Type': 'application/json' } } | |
| ); | |
| } catch (error) { | |
| console.error('[Auth Login Error]:', error); | |
| return new Response( | |
| JSON.stringify({ error: 'Gặp sự cố lỗi hệ thống khi đăng nhập!' }), | |
| { status: 500, headers: { 'Content-Type': 'application/json' } } | |
| ); | |
| } | |
| }; |