Skip to content

Commit 539f6a7

Browse files
committed
Add AsyncLocalStorage docs for passing extra data in MyStrategy authentication
1 parent 41173ff commit 539f6a7

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

README.md

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,55 @@ export class MyStrategy<User> extends Strategy<User, MyStrategy.VerifyOptions> {
353353
}
354354
```
355355

356-
#### Accept Autn
356+
#### Use AsyncLocalStorage to pass extra data to authenticate
357+
358+
If you need more than the request object to authenticate the user, you can use the `AsyncLocalStorage` API to pass data to the `authenticate` method.
359+
360+
```ts
361+
import { AsyncLocalStorage } from "async_hooks";
362+
363+
export const asyncLocalStorage = new AsyncLocalStorage<{
364+
someValue: string;
365+
// more values
366+
}>();
367+
368+
export class MyStrategy<User> extends Strategy<User, MyStrategy.VerifyOptions> {
369+
name = "my-strategy";
370+
371+
constructor(
372+
protected cookieName: string,
373+
verify: Strategy.VerifyFunction<User, MyStrategy.VerifyOptions>
374+
) {
375+
super(verify);
376+
}
377+
378+
async authenticate(request: Request): Promise<User> {
379+
let store = asyncLocalStorage.getStore();
380+
if (!store) throw new Error("Failed to get AsyncLocalStorage store");
381+
let { someValue } = store;
382+
// More code
383+
}
384+
}
385+
```
386+
387+
Then you can set the value in the `authenticate` method.
388+
389+
```ts
390+
export async function action({ request }: Route.ActionArgs) {
391+
// Set the value in the AsyncLocalStorage
392+
let user = await asyncLocalStorage.run({ someValue: "some value" }, () =>
393+
authenticator.authenticate("user-pass", request)
394+
);
395+
396+
let session = await sessionStorage.getSession(request.headers.get("cookie"));
397+
398+
session.set("user", user);
399+
400+
return redirect("/dashboard", {
401+
headers: { "Set-Cookie": await commitSession(session) },
402+
});
403+
}
404+
```
357405

358406
## License
359407

0 commit comments

Comments
 (0)