Files
webshop/shop/app/api/admin/send-test-email/route.ts
DanielS bab2930b97
Some checks failed
Staging Build / build (push) Failing after 27s
Add cookies handling to send-test-email route
2026-06-23 00:26:08 +02:00

49 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// API route to send a test email protected by Supabase admin check
import { NextResponse } from 'next/server';
import { sendMail } from '@/utils/mail';
import { createServerClient } from '@supabase/ssr';
import { cookies } from 'next/headers';
export async function POST(request: Request) {
const cookieStore = await cookies();
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL ?? '',
process.env.SUPABASE_SERVICE_ROLE_KEY ?? '',
{
cookies: {
getAll() {
return cookieStore.getAll()
},
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options)
)
} catch {
// Kann in einer API-Route ignoriert werden, wenn nur gelesen wird
}
},
},
}
);
// Verify admin rights expecting a user with role "admin" in the "users" table
const { data: { session } } = await supabase.auth.getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { data: user } = await supabase.from('users').select('role').eq('id', session.user.id).single();
if (!user || user.role !== 'admin') {
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
}
const { to, subject, text, html } = await request.json();
try {
const info = await sendMail({ to, subject, text, html });
return NextResponse.json({ message: 'Email sent', info });
} catch (err) {
console.error('Mail error', err);
return NextResponse.json({ error: 'Failed to send email' }, { status: 500 });
}
}