-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
58 lines (52 loc) · 1.46 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { SpeedInsights } from "@vercel/speed-insights/next";
import { kv } from '@vercel/kv';
export const config = {
matcher: '/l/:path*'
};
export async function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
if (pathname === '/l') {
const basicAuth = request.headers.get('authorization');
const url = request.nextUrl;
if (basicAuth) {
const authValue = basicAuth.split(' ')[1];
const [user, pwd] = Buffer.from(authValue, 'base64').toString().split(':');
if (user === 'root' && pwd === process.env.LINK_SHORTENER_PW) {
return NextResponse.next();
}
}
url.pathname = '/';
return new NextResponse('401 Unauthorized', {
headers: {
'WWW-authenticate': 'Basic realm="Secure Area"'
},
status: 401
});
} else {
const short_url = pathname.substring(3);
const long_url = await kv.hget(`link:${short_url}`, 'target');
if (long_url) {
let url = null;
try {
url = new URL(long_url as string).toString();
} catch (e) {
return new NextResponse('Invalid Long URL: ' + long_url);
}
return new NextResponse('', {
headers: {
'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
Pragma: 'no-cache',
Expires: 'Mon, 01 Jan 1990 00:00:00 GMT',
Location: url
},
status: 301
});
} else {
return new NextResponse('404 Not Found', {
status: 404
});
}
}
}