Skip to content

Instantly share code, notes, and snippets.

@Anveio
Last active March 10, 2024 23:47
Show Gist options
  • Save Anveio/da89dc50fca4ab7760155f896b252f93 to your computer and use it in GitHub Desktop.
Save Anveio/da89dc50fca4ab7760155f896b252f93 to your computer and use it in GitHub Desktop.
import { NextRequest, NextResponse } from 'next/server';
import { kv } from '@vercel/kv';
import { WorkOS } from '@workos-inc/node';
const workos = new WorkOS(process.env.WORKOS_API_KEY);
export async function POST(request: NextRequest) {
const { email, password } = await request.json();
const ip = request.ip;
// Check if the IP is rate limited
const rateLimitKey = `ratelimit:${ip}`;
const requests = await kv.incr(rateLimitKey);
if (requests === 1) {
await kv.expire(rateLimitKey, 60); // Rate limit for 60 seconds
}
const maxRequests = 5;
if (requests > maxRequests) {
return NextResponse.json({ error: 'Too many requests' }, { status: 429 });
}
// Check if the IP is blocked
const blockedIpKey = `blockedip:${ip}`;
const isBlocked = await kv.get(blockedIpKey);
if (isBlocked) {
return NextResponse.json({ error: 'IP blocked' }, { status: 403 });
}
try {
// Authenticate the user using WorkOS
const { profile } = await workos.passwordAuth({
username: email,
password,
});
// Authentication successful
// Generate and return a session token or JWT
const token = generateToken(profile);
return NextResponse.json({ token });
} catch (error) {
// Authentication failed
console.error('Authentication error:', error);
// Increment the failed attempts counter for the IP
const failedAttemptsKey = `failedattempts:${ip}`;
const failedAttempts = await kv.incr(failedAttemptsKey);
if (failedAttempts === 1) {
await kv.expire(failedAttemptsKey, 3600); // Track failed attempts for 1 hour
}
const maxFailedAttempts = 3;
if (failedAttempts >= maxFailedAttempts) {
// Block the IP
await kv.set(blockedIpKey, '1');
await kv.expire(blockedIpKey, 86400); // Block for 24 hours
}
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
}
}
function generateToken(profile) {
// Generate and return a session token or JWT based on the user profile
// Implement your own token generation logic here
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment