// /api/cs2/sharecode/route.ts import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/app/lib/auth' import { prisma } from '@/app/lib/prisma' import { decrypt, encrypt } from '@/app/lib/crypto' // Maximal 30 Tage gültig const EXPIRY_DAYS = 30 export async function GET(req: NextRequest) { const session = await getServerSession(authOptions(req)) const steamId = session?.user?.steamId if (!steamId) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } try { const user = await prisma.user.findUnique({ where: { steamId }, select: { authCode: true, lastKnownShareCode: true, lastKnownShareCodeDate: true, }, }) const authCode = user?.authCode ? decrypt(user.authCode) : null const lastKnownShareCode = user?.lastKnownShareCode ?? null const lastKnownShareCodeDate = user?.lastKnownShareCodeDate ?? null let reason: 'expired' | null = null if ( lastKnownShareCodeDate && new Date().getTime() - new Date(lastKnownShareCodeDate).getTime() > EXPIRY_DAYS * 24 * 60 * 60 * 1000 ) { reason = 'expired' } return NextResponse.json({ authCode, lastKnownShareCode, lastKnownShareCodeDate, reason, }) } catch (error) { console.error('[GET /api/cs2/sharecode]', error) return NextResponse.json({ error: 'Fehler beim Abrufen' }, { status: 500 }) } } export async function PUT(req: NextRequest) { const session = await getServerSession(authOptions(req)) const steamId = session?.user?.steamId if (!steamId) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const { authCode, lastKnownShareCode } = await req.json() // Optional: zusätzliche Validierung für authCode const isValidAuthCode = !authCode || /^[A-Z0-9]{4}-[A-Z0-9]{5}-[A-Z0-9]{4}$/.test(authCode) const isValidShareCode = !lastKnownShareCode || /^CSGO(-[a-zA-Z0-9]{5}){5}$/.test(lastKnownShareCode) if (!isValidShareCode) { return NextResponse.json({ error: 'expired-sharecode' }, { status: 400 }) } try { await prisma.user.update({ where: { steamId }, data: { authCode: authCode && isValidAuthCode ? encrypt(authCode) : undefined, lastKnownShareCode: lastKnownShareCode || undefined, lastKnownShareCodeDate: lastKnownShareCode ? new Date() : undefined, }, }) return new NextResponse(null, { status: 204 }) } catch (error) { console.error('[PUT /api/cs2/sharecode]', error) return NextResponse.json({ error: 'Fehler beim Speichern' }, { status: 500 }) } }