Spaces:
Sleeping
Sleeping
File size: 2,271 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 | 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' } }
);
}
}; |