Skip to content

Commit

Permalink
Add http basic auth integration for a list of credentials
Browse files Browse the repository at this point in the history
  • Loading branch information
carlgu committed Oct 25, 2024
1 parent a0f008f commit f213ca5
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
2.3.1
=====

* (improvement) Add method `integrateHttpBasicAuth()` for handling a list of Http Basic Auth Credentials
* (deprecation) Deprecate `handleHttpBasicAuth` method

2.3.0
=====

Expand Down
35 changes: 31 additions & 4 deletions src/next/middleware/http-auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import type {NextRequest} from "next/server";

export interface Credentials {
username: string;
password: string;
}

/**
* Handles basic authentication
*
* @deprecated Use the new method 'integrateHttpBasicAuth' allowing a list of credentials to check against instead
*/
export function handleHttpBasicAuth (
request: NextRequest,
Expand All @@ -10,6 +17,24 @@ export function handleHttpBasicAuth (
responseText: string = "Auth required",
realmLabel: string = "Secure Area",
) : Response | undefined
{
return integrateHttpBasicAuth(
request,
[{username: username, password: password}],
responseText,
realmLabel
);
}

/**
* Handles basic authentication
*/
export function integrateHttpBasicAuth (
request: NextRequest,
users: Credentials[],
responseText: string = "Auth required",
realmLabel: string = "Secure Area",
) : Response | undefined
{
const auth = request.headers.get("authorization");
const authToken = /^Basic (?<token>.*?)$/.exec(auth || "");
Expand All @@ -20,10 +45,12 @@ export function handleHttpBasicAuth (
.toString()
.split(":");

if (givenUser === username && givenPassword === password)
{
return;
}
users.forEach((item) => {
if (givenUser === item.username && givenPassword === item.password)
{
return;
}
})
}

return new Response(responseText, {
Expand Down

0 comments on commit f213ca5

Please sign in to comment.