mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-15 20:17:22 +00:00
feat: add helper methods for auth cookie headers
introduced `getAuthCookieHeader` and `removeAuthCookieHeader` methods to simplify header management for authentication cookies. added tests to validate the new methods.
This commit is contained in:
@@ -1,3 +1,41 @@
|
||||
import { Authenticator } from "auth/authenticate/Authenticator";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
|
||||
describe("Authenticator", async () => {});
|
||||
describe("Authenticator", async () => {
|
||||
test("should return auth cookie headers", async () => {
|
||||
const auth = new Authenticator({}, null as any, {
|
||||
jwt: {
|
||||
secret: "secret",
|
||||
fields: [],
|
||||
},
|
||||
cookie: {
|
||||
sameSite: "strict",
|
||||
},
|
||||
});
|
||||
const headers = await auth.getAuthCookieHeader("token");
|
||||
const cookie = headers.get("Set-Cookie");
|
||||
expect(cookie).toStartWith("auth=");
|
||||
expect(cookie).toEndWith("HttpOnly; Secure; SameSite=Strict");
|
||||
|
||||
// now expect it to be removed
|
||||
const headers2 = await auth.removeAuthCookieHeader(headers);
|
||||
const cookie2 = headers2.get("Set-Cookie");
|
||||
expect(cookie2).toStartWith("auth=; Max-Age=0; Path=/; Expires=");
|
||||
expect(cookie2).toEndWith("HttpOnly; Secure; SameSite=Strict");
|
||||
});
|
||||
|
||||
test("should return auth cookie string", async () => {
|
||||
const auth = new Authenticator({}, null as any, {
|
||||
jwt: {
|
||||
secret: "secret",
|
||||
fields: [],
|
||||
},
|
||||
cookie: {
|
||||
sameSite: "strict",
|
||||
},
|
||||
});
|
||||
const cookie = await auth.unsafeGetAuthCookie("token");
|
||||
expect(cookie).toStartWith("auth=");
|
||||
expect(cookie).toEndWith("HttpOnly; Secure; SameSite=Strict");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -327,6 +327,31 @@ export class Authenticator<
|
||||
await setSignedCookie(c, "auth", token, secret, this.cookieOptions);
|
||||
}
|
||||
|
||||
async getAuthCookieHeader(token: string, headers = new Headers()) {
|
||||
const c = {
|
||||
header: (key: string, value: string) => {
|
||||
headers.set(key, value);
|
||||
},
|
||||
};
|
||||
await this.setAuthCookie(c as any, token);
|
||||
return headers;
|
||||
}
|
||||
|
||||
async removeAuthCookieHeader(headers = new Headers()) {
|
||||
const c = {
|
||||
header: (key: string, value: string) => {
|
||||
headers.set(key, value);
|
||||
},
|
||||
req: {
|
||||
raw: {
|
||||
headers,
|
||||
},
|
||||
},
|
||||
};
|
||||
this.deleteAuthCookie(c as any);
|
||||
return headers;
|
||||
}
|
||||
|
||||
async unsafeGetAuthCookie(token: string): Promise<string | undefined> {
|
||||
// this works for as long as cookieOptions.prefix is not set
|
||||
return serializeSigned("auth", token, this.config.jwt.secret, this.cookieOptions);
|
||||
|
||||
Reference in New Issue
Block a user