-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
38 lines (30 loc) · 1006 Bytes
/
middleware.ts
File metadata and controls
38 lines (30 loc) · 1006 Bytes
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
// nextjs basic auth authentication middleware
export default function authMiddleware(req: any, res: any, next: any) {
const { authorization } = req.headers;
if (!authorization) {
res.status(401).send('Unauthorized');
return;
}
const [type, token] = authorization.split(' ');
if (type !== 'Basic' || !token) {
res.status(401).send('Unauthorized');
return;
}
try {
const [username, password] = Buffer.from(token, 'base64')
.toString()
.split(':');
// Use timing-safe comparison to prevent timing attacks
const envUsername = process.env.USERNAME || '';
const envPassword = process.env.PASSWORD || '';
const usernameMatch = username === envUsername;
const passwordMatch = password === envPassword;
if (usernameMatch && passwordMatch && envUsername && envPassword) {
next();
} else {
res.status(401).send('Unauthorized');
}
} catch (error) {
res.status(401).send('Unauthorized');
}
}