forked from labd/nextjs-basic-auth-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
66 lines (58 loc) · 1.9 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
import type { NextRequest } from 'next/server'
// eslint-disable-next-line no-duplicate-imports
import { NextResponse } from 'next/server'
import { basicAuthentication } from './lib/auth.js'
import {
AuthCredentials,
compareCredentials,
parseCredentials,
} from './lib/credentials'
import { MiddlewareOptions } from './types'
/**
* Creates a default Next middleware function that returns `NextResponse.next()` if the basic auth passes
* @param req Next middleware request
* @param options Options object based on MiddlewareOptions
* @returns Either a 401 error or goes to the next page
*/
export const createNextAuthMiddleware =
({
pathname = '/api/auth',
users = [],
message = 'Authentication failed',
realm = 'protected',
}: MiddlewareOptions = {}) =>
(req: NextRequest) =>
nextBasicAuthMiddleware({ pathname, users, message, realm }, req)
export const nextBasicAuthMiddleware = (
{
pathname = '/api/auth',
users = [],
message = 'Authentication failed',
realm = 'protected',
}: MiddlewareOptions = {},
req: NextRequest
) => {
// Check if credentials are set up
const environmentCredentials = process.env.BASIC_AUTH_CREDENTIALS || ''
if (environmentCredentials.length === 0 && users.length === 0) {
// No credentials set up, continue rendering the page as normal
return NextResponse.next()
}
const credentialsObject: AuthCredentials =
environmentCredentials.length > 0
? parseCredentials(environmentCredentials)
: users
const authHeader = req.headers.get('authorization')
if (authHeader) {
const currentUser = basicAuthentication(authHeader)
if (currentUser && compareCredentials(currentUser, credentialsObject)) {
return NextResponse.next()
}
}
const url = req.nextUrl
url.pathname = pathname
return new NextResponse(message, {
status: 401,
headers: { 'WWW-Authenticate': `Basic realm="${realm}"` },
})
}