103 lines
2.5 KiB
TypeScript
103 lines
2.5 KiB
TypeScript
import NextAuth, { NextAuthOptions } from "next-auth";
|
|
import { prisma } from '@/lib/prisma';
|
|
import CredentialsProvider from 'next-auth/providers/credentials';
|
|
|
|
declare module "next-auth" {
|
|
interface Session {
|
|
user: {
|
|
id: string;
|
|
name?: string | null;
|
|
email?: string | null;
|
|
image?: string | null;
|
|
username: string;
|
|
first_name: string;
|
|
last_name: string;
|
|
role: string[];
|
|
};
|
|
accessToken: string;
|
|
}
|
|
|
|
interface JWT {
|
|
accessToken: string;
|
|
refreshToken: string;
|
|
accessTokenExpires: number;
|
|
role: string[];
|
|
username: string;
|
|
first_name: string;
|
|
last_name: string;
|
|
}
|
|
}
|
|
|
|
const authOptions: NextAuthOptions = {
|
|
providers: [
|
|
CredentialsProvider({
|
|
name: 'Credentials',
|
|
credentials: {
|
|
email: { label: 'Email', type: 'email' },
|
|
password: { label: 'Password', type: 'password' }
|
|
},
|
|
async authorize(credentials) {
|
|
if (!credentials?.email || !credentials?.password) {
|
|
return null;
|
|
}
|
|
|
|
const user = await prisma.user.findUnique({
|
|
where: { email: credentials.email },
|
|
});
|
|
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
return {
|
|
id: user.id,
|
|
email: user.email,
|
|
username: user.username || user.email.split('@')[0],
|
|
first_name: user.first_name || '',
|
|
last_name: user.last_name || '',
|
|
role: user.role || [],
|
|
};
|
|
}
|
|
})
|
|
],
|
|
session: {
|
|
strategy: 'jwt' as const,
|
|
},
|
|
pages: {
|
|
signIn: '/login',
|
|
},
|
|
callbacks: {
|
|
async jwt({ token, user }: { token: any; user: any }) {
|
|
if (user) {
|
|
token.id = user.id;
|
|
token.email = user.email;
|
|
token.username = user.username;
|
|
token.first_name = user.first_name;
|
|
token.last_name = user.last_name;
|
|
token.role = user.role;
|
|
}
|
|
return token;
|
|
},
|
|
async session({ session, token }: { session: any; token: any }) {
|
|
if (token) {
|
|
session.user = {
|
|
id: token.id as string,
|
|
email: token.email as string | null,
|
|
name: token.name as string | null,
|
|
image: token.picture as string | null,
|
|
username: token.username as string,
|
|
first_name: token.first_name as string,
|
|
last_name: token.last_name as string,
|
|
role: token.role as string[],
|
|
};
|
|
session.accessToken = token.accessToken as string;
|
|
}
|
|
return session;
|
|
}
|
|
}
|
|
};
|
|
|
|
const handler = NextAuth(authOptions);
|
|
export { handler as GET, handler as POST };
|
|
|