-
Notifications
You must be signed in to change notification settings - Fork 3
/
[...nextauth].ts
49 lines (44 loc) · 1.34 KB
/
[...nextauth].ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import NextAuth, { NextAuthOptions } from "next-auth";
import KeycloakProvider from "next-auth/providers/keycloak";
import { ensureUserFromSub } from "@/db/user";
import { KEYCLOAK_ID, KEYCLOAK_SECRET, KEYCLOAK_ISSUER } from "@/domain/env";
import { truthy } from "@/domain/types";
import type { NextApiRequest, NextApiResponse } from "next";
const providers = [
KEYCLOAK_ID && KEYCLOAK_SECRET
? KeycloakProvider({
clientId: KEYCLOAK_ID as string,
clientSecret: KEYCLOAK_SECRET as string,
issuer: KEYCLOAK_ISSUER as string,
})
: null,
].filter(truthy);
export const nextAuthOptions = {
providers,
callbacks: {
/**
* When the user is logged in, ensures it creates on our side and save its id
* on the session.
*/
session: async ({ session, token }) => {
if (session.user && token.sub) {
session.user.sub = token.sub;
const user = await ensureUserFromSub(token.sub, token.name);
session.user.id = user.id;
}
return session;
},
/** Necessary otherwise we cannot sign out */
jwt: async ({ token }) => {
return token;
},
},
} as NextAuthOptions;
export default async function auth(req: NextApiRequest, res: NextApiResponse) {
try {
await NextAuth(req, res, nextAuthOptions);
} catch (e) {
console.error(e);
throw e;
}
}