feat: add cookie-based auth utilities for browser user flows
This commit is contained in:
48
test/auth.test.js
Normal file
48
test/auth.test.js
Normal file
@@ -0,0 +1,48 @@
|
||||
"use strict";
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const {
|
||||
COOKIE_NAME,
|
||||
parseCookies,
|
||||
serializeUserCookie,
|
||||
clearUserCookie,
|
||||
getAuthenticatedUserId,
|
||||
} = require("../src/lib/auth");
|
||||
|
||||
test("parseCookies handles multiple cookies", () => {
|
||||
const cookies = parseCookies("a=1; xartaudio_user=user-1; b=hello%20world");
|
||||
assert.equal(cookies.a, "1");
|
||||
assert.equal(cookies.xartaudio_user, "user-1");
|
||||
assert.equal(cookies.b, "hello world");
|
||||
});
|
||||
|
||||
test("serializeUserCookie builds secure-ish cookie string", () => {
|
||||
const cookie = serializeUserCookie("user-1", 120);
|
||||
assert.match(cookie, new RegExp(`^${COOKIE_NAME}=user-1;`));
|
||||
assert.match(cookie, /HttpOnly/);
|
||||
assert.match(cookie, /SameSite=Lax/);
|
||||
assert.match(cookie, /Max-Age=120/);
|
||||
});
|
||||
|
||||
test("clearUserCookie expires session cookie", () => {
|
||||
const cookie = clearUserCookie();
|
||||
assert.match(cookie, /Max-Age=0/);
|
||||
});
|
||||
|
||||
test("getAuthenticatedUserId prefers x-user-id header", () => {
|
||||
const userId = getAuthenticatedUserId({
|
||||
"x-user-id": "header-user",
|
||||
cookie: "xartaudio_user=cookie-user",
|
||||
});
|
||||
|
||||
assert.equal(userId, "header-user");
|
||||
});
|
||||
|
||||
test("getAuthenticatedUserId falls back to cookie", () => {
|
||||
const userId = getAuthenticatedUserId({
|
||||
cookie: "xartaudio_user=cookie-user",
|
||||
});
|
||||
|
||||
assert.equal(userId, "cookie-user");
|
||||
});
|
||||
Reference in New Issue
Block a user