58 lines
1.8 KiB
TypeScript
58 lines
1.8 KiB
TypeScript
import NextAuth from 'next-auth';
|
|
import Credentials from 'next-auth/providers/credentials';
|
|
|
|
const BACKEND_URL = process.env.NEXT_PUBLIC_API_URL_INTERNAL ?? 'http://recipe-api:8080';
|
|
|
|
export const { handlers, auth, signIn, signOut } = NextAuth({
|
|
providers: [
|
|
Credentials({
|
|
credentials: {
|
|
username: { label: 'Användarnamn', type: 'text' },
|
|
password: { label: 'Lösenord', type: 'password' },
|
|
},
|
|
async authorize(credentials) {
|
|
if (!credentials?.username || !credentials?.password) return null;
|
|
try {
|
|
const res = await fetch(`${BACKEND_URL}/api/auth/login`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
username: credentials.username,
|
|
password: credentials.password,
|
|
}),
|
|
});
|
|
if (!res.ok) return null;
|
|
const data = await res.json() as { accessToken: string; userId: number; username: string };
|
|
return {
|
|
id: String(data.userId),
|
|
name: data.username,
|
|
accessToken: data.accessToken,
|
|
};
|
|
} catch {
|
|
return null;
|
|
}
|
|
},
|
|
}),
|
|
],
|
|
callbacks: {
|
|
jwt({ token, user }) {
|
|
if (user) {
|
|
token.accessToken = (user as any).accessToken as string;
|
|
token.userId = Number(user.id);
|
|
token.username = user.name ?? '';
|
|
}
|
|
return token;
|
|
},
|
|
session({ session, token }) {
|
|
session.accessToken = token.accessToken as string;
|
|
session.user.id = String(token.userId);
|
|
session.user.name = token.username as string;
|
|
return session;
|
|
},
|
|
},
|
|
pages: {
|
|
signIn: '/login',
|
|
},
|
|
session: { strategy: 'jwt' },
|
|
});
|