Created
July 31, 2025 02:32
-
-
Save mathislajs/68fc144ed1d3387719a7e64234a7947a to your computer and use it in GitHub Desktop.
PRC API Key Request Validate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextResponse } from 'next/server' | |
import { Redis } from '@upstash/redis' | |
import { supabase } from '@/lib/supabase' | |
import CryptoJS from 'crypto-js' | |
const redis = new Redis({ | |
url: process.env.UPSTASH_REDIS_REST_URL!, | |
token: process.env.UPSTASH_REDIS_REST_TOKEN!, | |
}) | |
const RATE_LIMIT_DURATION = 60 // 1 minute | |
const MAX_REQUESTS = 30 // maximum requests per minute | |
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || 'your-fallback-secret' | |
export async function POST(request: Request) { | |
try { | |
const { apiKey } = await request.json() | |
if (!apiKey?.trim()) { | |
return NextResponse.json( | |
{ error: 'API key is required' }, | |
{ status: 400 } | |
) | |
} | |
const rateLimitKey = 'prc_api_calls' | |
const currentCount = await redis.incr(rateLimitKey) | |
if (currentCount === 1) { | |
await redis.expire(rateLimitKey, RATE_LIMIT_DURATION) | |
} | |
if (currentCount > MAX_REQUESTS) { | |
return NextResponse.json( | |
{ error: 'Rate limit exceeded. Please try again later.' }, | |
{ status: 429 } | |
) | |
} | |
const encryptedApiKey = CryptoJS.AES.encrypt(apiKey, ENCRYPTION_KEY).toString() | |
const { data: existingServer, error: dbError } = await supabase | |
.from('servers') | |
.select('id, name') | |
.eq('api_key', encryptedApiKey) | |
.maybeSingle() | |
if (dbError) { | |
console.error('Database error:', dbError) | |
return NextResponse.json( | |
{ error: 'Failed to validate API key' }, | |
{ status: 500 } | |
) | |
} | |
if (existingServer) { | |
return NextResponse.json( | |
{ error: `This API key is already linked to server "${existingServer.name}"` }, | |
{ status: 400 } | |
) | |
} | |
const prcResponse = await fetch('https://api.policeroleplay.community/v1/server', { | |
headers: { | |
'Server-Key': apiKey | |
} | |
}) | |
if (!prcResponse.ok) { | |
return NextResponse.json( | |
{ error: 'Invalid API key' }, | |
{ status: prcResponse.status } | |
) | |
} | |
const prcData = await prcResponse.json() | |
return NextResponse.json({ | |
...prcData, | |
encryptedApiKey | |
}) | |
} catch (error) { | |
console.error('Validation error:', error) | |
return NextResponse.json( | |
{ error: 'Failed to validate API key' }, | |
{ status: 500 } | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment