-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
68 lines (66 loc) · 2.32 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { verifyKey } from '@unkey/api';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { rateLimiter, UNKEY_API_ID } from './lib/unkey';
const module = 'cat'
const getAction = (method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH', withId = false) => {
switch (method) {
case 'GET':
return withId ? 'view' : 'list';
case 'POST':
return `create`
case 'PUT':
return 'update';
case 'DELETE':
return `delete`;
case 'PATCH':
return `update`;
default:
throw new Error(`Invalid method ${method}`)
}
}
const getTokenDetails = async (token: string) => {
const { result, error } = await verifyKey({ key: token, apiId: UNKEY_API_ID });
if (error) {
throw new Error(`Invalid token`)
}
if (!result.valid) {
throw new Error(`Invalid token`)
}
return {
permissions: result.permissions!,
requester: result.ownerId!
}
}
interface Params {
id?: string;
}
export async function middleware(req: NextRequest, context: { params?: Params }) {
try {
const auth = req.headers.get('Authorization') || 'Bearer ';
const token = auth.slice(7); // remove 'Bearer ' from the beginning of the token
if (!token) {
return NextResponse.json({ message: 'Invalid token' }, { status: 401 });
}
const { permissions, requester } = await getTokenDetails(token);
const ratelimit = await rateLimiter.limit(requester)
if (!ratelimit.success) {
return NextResponse.json({ message: 'Rate limit exceeded' }, { status: 429 });
}
const action = getAction(req.method as 'GET' | 'POST', !!context.params?.id);
const foundPermission = permissions.find(permission => permission.startsWith(`${module}.${action}.`));
if (!foundPermission) {
return NextResponse.json({ message: 'Insufficient permissions' }, { status: 403 });
}
const [_, __, scope] = foundPermission.split('.');
const reqHeaders = new Headers(req.headers)
reqHeaders.set('x-api-scope', scope)
reqHeaders.set('x-api-user', requester)
return NextResponse.next({ request: { headers: reqHeaders } })
} catch (error) {
return NextResponse.json({ message: "Something went wrong with this request, please try again later!", data: (error as Error).message }, { status: 500 });
}
}
export const config = {
matcher: '/api/:path*'
}