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

Use a Cookie object instead of SessionStorage #299

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
301 changes: 159 additions & 142 deletions README.md

Large diffs are not rendered by default.

Binary file modified bun.lockb
Binary file not shown.
113 changes: 0 additions & 113 deletions docs/authenticator.md

This file was deleted.

33 changes: 0 additions & 33 deletions docs/avoid-redirects.md

This file was deleted.

52 changes: 0 additions & 52 deletions docs/testing.md

This file was deleted.

13 changes: 4 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,25 +38,20 @@
"uuid": "^10.0.0"
},
"peerDependencies": {
"@remix-run/react": "^1.0.0 || ^2.0.0",
"@remix-run/server-runtime": "^1.0.0 || ^2.0.0"
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.16.4",
"@babel/preset-react": "^7.13.13",
"@biomejs/biome": "^1.8.3",
"@remix-run/node": "^2.0.1",
"@remix-run/react": "^2.0.1",
"@remix-run/serve": "^2.0.1",
"@remix-run/server-runtime": "^2.0.1",
"@remix-run/node": "^2.12.1",
"@remix-run/server-runtime": "^1.0.0 || ^2.0.0",
"@total-typescript/tsconfig": "^1.0.4",
"@types/bun": "^1.1.6",
"@types/react": "^18.2.20",
"@types/uuid": "^10.0.0",
"consola": "^3.2.3",
"react": "^18.2.0",
"typedoc": "^0.26.5",
"typedoc-plugin-mdn-links": "^3.2.6",
"typescript": "^5.5.4"
"typescript": "^5.5.4",
"zod": "^3.23.8"
}
}
60 changes: 60 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { beforeEach, describe, expect, mock, test } from "bun:test";
import { createCookie } from "@remix-run/node";
import { Authenticator } from "./index.js";
import { Strategy } from "./strategy.js";

class MockStrategy<User> extends Strategy<User, Record<string, never>> {
name = "mock";

async authenticate() {
let user = await this.verify({});
if (user) return user;
throw new Error("Invalid credentials");
}
}

const cookie = createCookie("auth", { secrets: ["s3cr3t"] });

describe(Authenticator.name, () => {
beforeEach(() => mock.restore());

test("#constructor", () => {
let auth = new Authenticator(cookie);
expect(auth).toBeInstanceOf(Authenticator);
});

test("#use", () => {
let auth = new Authenticator(cookie);

expect(auth.use(new MockStrategy(async () => ({ id: 1 })))).toBe(auth);

expect(
auth.authenticate("mock", new Request("http://remix.auth/test")),
).resolves.toEqual({ id: 1 });
});

test("#unuse", () => {
let auth = new Authenticator(cookie).use(
new MockStrategy(async () => null),
);

expect(auth.unuse("mock")).toBe(auth);

expect(
async () =>
await auth.authenticate("mock", new Request("http://remix.auth/test")),
).toThrow(new ReferenceError("Strategy mock not found."));
});

test("#authenticate", async () => {
let auth = new Authenticator(cookie).use(
new MockStrategy(async () => ({ id: 1 })),
);

expect(
await auth.authenticate("mock", new Request("http://remix.auth/test"), {
context: {},
}),
).toEqual({ id: 1 });
});
});
89 changes: 80 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,82 @@
// biome-ignore lint/performance/noReExportAll: <explanation>
// biome-ignore lint/performance/noBarrelFile: <explanation>
export * from "./lib/authenticator.js";
import type { Cookie } from "@remix-run/server-runtime";
import type { Strategy } from "./strategy.js";

// biome-ignore lint/performance/noReExportAll: <explanation>
// biome-ignore lint/performance/noBarrelFile: <explanation>
export * from "./lib/error.js";
export class Authenticator<User = unknown> {
/**
* A map of the configured strategies, the key is the name of the strategy
* @private
*/
private strategies = new Map<string, Strategy<User, never>>();

// biome-ignore lint/performance/noReExportAll: <explanation>
// biome-ignore lint/performance/noBarrelFile: <explanation>
export * from "./lib/strategy.js";
/**
* Create a new instance of the Authenticator.
*
* It receives a instance of a Cookie created using Remix's createCookie.
*
* It optionally receives an object with extra options. The supported options
* are:
* @example
* import { createCookie } from "@remix-run/node";
* let cookie = createCookie("auth", { path: "/", maxAge: 3600 });
* let auth = new Authenticator(cookie);
* @example
* import { createCookie } from "@remix-run/cloudflare";
* let cookie = createCookie("auth", { path: "/", maxAge: 3600 });
* let auth = new Authenticator(cookie);
* @example
* import { createCookie } from "@remix-run/deno";
* let cookie = createCookie("auth", { path: "/", maxAge: 3600 });
* let auth = new Authenticator(cookie);
*/
constructor(private cookie: Cookie) {}

/**
* Call this method with the Strategy, the optional name allows you to setup
* the same strategy multiple times with different names.
* It returns the Authenticator instance for concatenation.
* @example
* auth.use(new SomeStrategy({}, (user) => Promise.resolve(user)));
* auth.use(new SomeStrategy({}, (user) => Promise.resolve(user)), "another");
*/
use(strategy: Strategy<User, never>, name?: string): Authenticator<User> {
this.strategies.set(name ?? strategy.name, strategy);
return this;
}

/**
* Call this method with the name of the strategy you want to remove.
* It returns the Authenticator instance for concatenation.
* @example
* auth.unuse("another").unuse("some");
*/
unuse(name: string): Authenticator {
this.strategies.delete(name);
return this;
}

/**
* Call this to authenticate a request using some strategy. You pass the name
* of the strategy you want to use and the request to authenticate.
* @example
* async function action({ request }: ActionFunctionArgs) {
* let user = await auth.authenticate("some", request);
* };
* @example
* async function action({ request, context }: ActionFunctionArgs) {
* let user = await auth.authenticate("some", request, { context });
* };
*/
authenticate(
strategy: string,
request: Request,
options: Pick<Strategy.AuthenticateOptions, "context"> = {},
): Promise<User> {
const obj = this.strategies.get(strategy);
if (!obj) throw new ReferenceError(`Strategy ${strategy} not found.`);
return obj.authenticate(new Request(request.url, request), {
...options,
cookie: this.cookie,
name: strategy,
});
}
}
Loading