You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

65 line
2.4 KiB

  1. import { NextResponse } from 'next/server';
  2. import { revalidatePath } from 'next/cache'; // ADD THIS
  3. import { getPortals, savePortals } from '@/lib/db';
  4. import { isValidHexColor, sanitizeWelcomeText } from '@/lib/sanitize';
  5. import { validatePortal } from '@/lib/validation';
  6. import { Portal } from '@/types';
  7. export const dynamic = 'force-dynamic';
  8. export async function GET() {
  9. const portals = await getPortals();
  10. return NextResponse.json(portals[0] || null);
  11. }
  12. export async function POST(request: Request) {
  13. try {
  14. const incomingPortal: Portal = await request.json();
  15. // Sanifica l'HTML del welcome text prima di validare la lunghezza, così il counter
  16. // riflette il contenuto effettivamente persistito.
  17. if (typeof incomingPortal.welcomeText === 'string') {
  18. incomingPortal.welcomeText = sanitizeWelcomeText(incomingPortal.welcomeText);
  19. }
  20. const { valid, errors } = validatePortal(incomingPortal);
  21. if (!valid) {
  22. return NextResponse.json(
  23. { error: 'The portal settings could not be saved because some fields are invalid. See the highlighted errors and fix them, then try again.', errors },
  24. { status: 400 },
  25. );
  26. }
  27. // themeColor goes into a <style dangerouslySetInnerHTML> in PublicGrid,
  28. // so reject anything that is not a strict #RRGGBB.
  29. if (incomingPortal.themeColor !== undefined && !isValidHexColor(incomingPortal.themeColor)) {
  30. return NextResponse.json(
  31. {
  32. error: 'Invalid theme color: expected a hex code in the form #RRGGBB (e.g. #1e3a8a).',
  33. errors: [{ field: 'themeColor', message: 'Theme color must be a hex code like #RRGGBB.' }],
  34. },
  35. { status: 400 },
  36. );
  37. }
  38. const portals = await getPortals();
  39. if (portals.length > 0) {
  40. portals[0] = { ...portals[0], ...incomingPortal };
  41. } else {
  42. portals.push({ ...incomingPortal, id: 'default-portal', tenantId: 'default' });
  43. }
  44. await savePortals(portals);
  45. // Rivalida sia la home che il layout (il font @font-face è applicato nel layout root)
  46. revalidatePath('/', 'layout');
  47. return NextResponse.json(portals[0], { status: 200 });
  48. } catch {
  49. return NextResponse.json(
  50. { error: 'Unexpected error while saving the portal settings. The changes were not saved. Check the server logs and try again.' },
  51. { status: 500 },
  52. );
  53. }
  54. }