import { AuthOptions, Session } from "next-auth"; import CredentialsProvider from "next-auth/providers/credentials"; import { LOGIN_API_PATH } from "./api"; export interface SessionWithTokens extends Session { accessToken?: string; refreshToken?: string; } export const authOptions: AuthOptions = { debug: process.env.NODE_ENV === "development", providers: [ CredentialsProvider({ id: "credentials", name: "Credentials", credentials: { username: { label: "Username", type: "text" }, password: { label: "Password", type: "password" }, }, async authorize(credentials, req) { const res = await fetch(LOGIN_API_PATH, { method: "POST", body: JSON.stringify(credentials), headers: { "Content-Type": "application/json" }, }); const user = await res.json(); if (res.ok && user) { return user; } return null; }, }), ], pages: { signIn: "/login", }, callbacks: { jwt(params) { // Add the data from user to the token const { token, user } = params; const newToken = { ...token, ...user }; return newToken; }, session({ session, token }) { const sessionWithToken: SessionWithTokens = { ...session, // Add the data from the token to the session accessToken: token.accessToken as string | undefined, refreshToken: token.refreshToken as string | undefined, }; return sessionWithToken; }, }, };