forked from lyc8503/UptimeFlare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
27 lines (24 loc) · 900 Bytes
/
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
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { workerConfig } from './uptime.config'
export async function middleware(request: NextRequest) {
// @ts-ignore
const passwordProtection = workerConfig.passwordProtection
if (passwordProtection) {
const authHeader = request.headers.get('Authorization')
let authenticated = false
const expected = 'Basic ' + btoa(passwordProtection)
if (authHeader && authHeader.length === expected.length) {
// a simple timing-safe compare
authenticated = true;
for (let i = 0; i < authHeader.length; i++) {
if (authHeader[i] !== expected[i]) authenticated = false;
}
}
if (!authenticated) {
return NextResponse.json(
{ code: 401, message: "Not authenticated" }, { status: 401, headers: { 'WWW-Authenticate': 'Basic' } }
)
}
}
}