source: server/authjs-handler.ts@ 8ee4553

main
Last change on this file since 8ee4553 was 8ee4553, checked in by Bati <no-reply@…>, 7 months ago

scaffold Vike app with Bati

  • Property mode set to 100644
File size: 2.9 KB
Line 
1import { Auth, type AuthConfig, createActionURL, setEnvDefaults } from "@auth/core";
2import CredentialsProvider from "@auth/core/providers/credentials";
3import type { Session } from "@auth/core/types";
4import { enhance, type UniversalHandler, type UniversalMiddleware } from "@universal-middleware/core";
5
6const authjsConfig = {
7 basePath: "/api/auth",
8 trustHost: true,
9 // TODO: Replace secret {@see https://authjs.dev/reference/core#secret}
10 secret: "MY_SECRET",
11 providers: [
12 // TODO: Choose and implement providers
13 CredentialsProvider({
14 name: "Credentials",
15 credentials: {
16 username: { label: "Username", type: "text", placeholder: "jsmith" },
17 password: { label: "Password", type: "password" },
18 },
19 async authorize() {
20 // Add logic here to look up the user from the credentials supplied
21 const user = { id: "1", name: "J Smith", email: "jsmith@example.com" };
22
23 // Any object returned will be saved in `user` property of the JWT
24 // If you return null then an error will be displayed advising the user to check their details.
25 // You can also Reject this callback with an Error thus the user will be sent to the error page with the error message as a query parameter
26 return user ?? null;
27 },
28 }),
29 ],
30} satisfies Omit<AuthConfig, "raw">;
31
32/**
33 * Retrieve Auth.js session from Request
34 */
35export async function getSession(req: Request, config: Omit<AuthConfig, "raw">): Promise<Session | null> {
36 setEnvDefaults(process.env, config);
37 const requestURL = new URL(req.url);
38 const url = createActionURL("session", requestURL.protocol, req.headers, process.env, config);
39
40 const response = await Auth(new Request(url, { headers: { cookie: req.headers.get("cookie") ?? "" } }), config);
41
42 const { status = 200 } = response;
43
44 const data = await response.json();
45
46 if (!data || !Object.keys(data).length) return null;
47 if (status === 200) return data as Session;
48 throw new Error(typeof data === "object" && "message" in data ? (data.message as string) : undefined);
49}
50
51/**
52 * Add Auth.js session to context
53 * @link {@see https://authjs.dev/getting-started/session-management/get-session}
54 **/
55export const authjsSessionMiddleware: UniversalMiddleware = enhance(
56 async (request, context) => {
57 try {
58 return {
59 ...context,
60 session: await getSession(request, authjsConfig),
61 };
62 } catch (error) {
63 console.debug("authjsSessionMiddleware:", error);
64 return {
65 ...context,
66 session: null,
67 };
68 }
69 },
70 {
71 name: "my-app:authjs-middleware",
72 immutable: false,
73 },
74);
75
76/**
77 * Auth.js route
78 * @link {@see https://authjs.dev/getting-started/installation}
79 **/
80export const authjsHandler = enhance(
81 async (request) => {
82 return Auth(request, authjsConfig);
83 },
84 {
85 name: "my-app:authjs-handler",
86 path: "/api/auth/**",
87 method: ["GET", "POST"],
88 immutable: false,
89 },
90) satisfies UniversalHandler;
Note: See TracBrowser for help on using the repository browser.