Skip to content

Commit

Permalink
Merge pull request #42 from 21TORR/httpauth-list
Browse files Browse the repository at this point in the history
Add http basic auth integration for a list of credentials
  • Loading branch information
apfelbox authored Oct 25, 2024
2 parents a0f008f + 12d55e2 commit 665ae5d
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
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
1 change: 1 addition & 0 deletions UPGRADE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
==========

* The `createEvent` helper was removed, use `new CustomEvent()` directly.
* The `handleHttpBasicAuth()` method was removed, use `integrateHttpBasicAuth()` directly


1.x to 2.0
Expand Down
29 changes: 28 additions & 1 deletion 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, 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,7 +45,9 @@ export function handleHttpBasicAuth (
.toString()
.split(":");

if (givenUser === username && givenPassword === password)
const hasValidUser = users.some(item => givenUser === item.username && givenPassword === item.password);

if (hasValidUser)
{
return;
}
Expand Down

0 comments on commit 665ae5d

Please sign in to comment.