Skip to content

Commit

Permalink
feat(common): adding getSession method (#160)
Browse files Browse the repository at this point in the history
  • Loading branch information
aversini authored Aug 19, 2024
1 parent 0122832 commit 2454df2
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
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";

0 comments on commit 2454df2

Please sign in to comment.