Skip to content

Commit

Permalink
Add method to get an strategy instance from authenticator
Browse files Browse the repository at this point in the history
Closes #309
  • Loading branch information
sergiodxa committed Nov 28, 2024
1 parent d8afa90 commit 581bf6b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
7 changes: 7 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,11 @@ describe(Authenticator.name, () => {
await auth.authenticate("mock", new Request("http://remix.auth/test")),
).toEqual({ id: 1 });
});

test("#get", () => {
let auth = new Authenticator();
let strategy = new MockStrategy(async () => ({ id: 1 }));
expect(auth.use(strategy)).toBe(auth);
expect(auth.get("mock")).toBe(strategy);
});
});
18 changes: 12 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,20 +41,26 @@ export class Authenticator<User = unknown> {
return this;
}

/**
* Call this method with the name of a strategy you want to get.
* It returns the Strategy instance or null if the strategy is not found.
* @param name
* @returns
*/
get(name: string) {
return this.strategies.get(name) ?? null;
}

/**
* 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 });
* let user = await auth.authenticate("strategy-name", request);
* };
*/
authenticate(strategy: string, request: Request): Promise<User> {
let instance = this.strategies.get(strategy);
let instance = this.get(strategy);
if (!instance) throw new ReferenceError(`Strategy ${strategy} not found.`);
return instance.authenticate(new Request(request.url, request));
}
Expand Down

0 comments on commit 581bf6b

Please sign in to comment.