Files
recipe-app/frontend/auth.ts
T

61 lines
1.9 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; role: string };
return {
id: String(data.userId),
name: data.username,
accessToken: data.accessToken,
role: data.role,
};
} 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 ?? '';
token.role = (user as any).role as string;
}
return token;
},
session({ session, token }) {
session.accessToken = token.accessToken as string;
session.user.id = String(token.userId);
session.user.name = token.username as string;
(session.user as any).role = token.role as string;
return session;
},
},
pages: {
signIn: '/login',
},
session: { strategy: 'jwt' },
});