import postgres from 'npm:postgres@3.4.4'; import bcrypt from 'npm:bcryptjs@2.4.3'; import jwt from 'npm:jsonwebtoken@9.0.2'; function getDb() { return postgres({ host: Deno.env.get('PG_HOST'), port: parseInt(Deno.env.get('PG_PORT') || '5432'), user: Deno.env.get('PG_USER'), password: Deno.env.get('PG_PASSWORD'), database: Deno.env.get('PG_DBNAME'), ssl: false, max: 1, }); } function verifyToken(body) { const token = body._auth_token; if (!token) { return { error: true, status: 401, message: 'Neautorizovaný prístup' }; } try { return jwt.verify(token, Deno.env.get('JWT_SECRET')); } catch { return { error: true, status: 401, message: 'Neplatný token' }; } } Deno.serve(async (req) => { const sql = getDb(); try { const body = await req.json(); const user = verifyToken(body); if (user.error) { await sql.end(); return Response.json({ error: user.message }, { status: user.status }); } if (user.role !== 'admin') { await sql.end(); return Response.json({ error: 'Prístup len pre administrátora' }, { status: 403 }); } const { action } = body; if (action === 'list') { const users = await sql` SELECT id, email, full_name, role, created_at FROM app_users ORDER BY created_at DESC `; await sql.end(); return Response.json({ users }); } if (action === 'create') { const { email, password, full_name, role } = body; if (!email || !password) { await sql.end(); return Response.json({ error: 'Email a heslo sú povinné' }, { status: 400 }); } const hash = await bcrypt.hash(password, 10); const result = await sql` INSERT INTO app_users (email, password_hash, full_name, role) VALUES (${email}, ${hash}, ${full_name || ''}, ${role || 'user'}) RETURNING id `; await sql.end(); return Response.json({ success: true, id: result[0].id }); } if (action === 'delete') { if (body.userId === user.id) { await sql.end(); return Response.json({ error: 'Nemôžete vymazať vlastný účet' }, { status: 400 }); } await sql`DELETE FROM app_users WHERE id = ${body.userId}`; await sql.end(); return Response.json({ success: true }); } if (action === 'changePassword') { if (!body.newPassword) { await sql.end(); return Response.json({ error: 'Nové heslo je povinné' }, { status: 400 }); } const hash = await bcrypt.hash(body.newPassword, 10); await sql`UPDATE app_users SET password_hash = ${hash} WHERE id = ${body.userId}`; await sql.end(); return Response.json({ success: true }); } await sql.end(); return Response.json({ error: 'Neznáma akcia' }, { status: 400 }); } catch (error) { await sql.end(); return Response.json({ error: error.message }, { status: 500 }); } });