Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(common): adding getSession method #160

Merged
merged 1 commit into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions packages/auth-common/src/components/__tests__/getSession.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { type HeadersLike, getSession } from "..";

describe("getSession", () => {
const clientId = "testClient";

it("should return empty string if no session is found", () => {
const headers: HeadersLike = {};
expect(getSession({ headers, clientId })).toBe("");
});

it("should extract session from cookie", () => {
const session = "some-session";
const headers: HeadersLike = {
cookie: `auth.${clientId}.session=${session};`,
};
expect(getSession({ headers, clientId })).toBe(session);
});

it("should return empty string if cookie does not contain the session", () => {
const headers: HeadersLike = {
cookie: "someOtherCookie=value;",
};
expect(getSession({ headers, clientId })).toBe("");
});
});
31 changes: 31 additions & 0 deletions packages/auth-common/src/components/getSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { HeadersLike } from "./getToken";

const getFromCookie = (headers: HeadersLike, clientId: string) => {
const cookie = headers?.cookie;
if (typeof cookie !== "string") {
return;
}
const re = new RegExp(`auth.${clientId}.session=(.+?)(?:;|$)`);
const match = cookie.match(re);
if (!match) {
return;
}
return match[1];
};

/**
* Get a Session Id from a request.
*
* @param headers An object containing the request headers, usually `req.headers`.
* @param clientId The client ID to use.
*
*/
type GetSessionProps = {
clientId: string;
headers: HeadersLike;
};
export const getSession = ({ headers, clientId }: GetSessionProps): string => {
const fromCookie = getFromCookie(headers, clientId);

return fromCookie || "";
};
1 change: 1 addition & 0 deletions packages/auth-common/src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from "./verifyToken";
export * from "./pkce";
export * from "./getToken";
export * from "./isGranted";
export * from "./getSession";