webdev-service / lib /auth.ts
underrate's picture
Initial commit
34ed5b1 verified
Raw
History Blame Contribute Delete
2.26 kB
import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
import { z } from "zod"
export const { handlers, signIn, signOut, auth } = NextAuth({
session: {
strategy: "jwt",
maxAge: 24 * 60 * 60, // 24 hours
},
pages: {
signIn: "/admin/login",
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id
token.role = (user as any).role
token.tokenVersion = (user as any).tokenVersion
}
return token
},
async session({ session, token }) {
if (session.user && token) {
(session.user as any).id = token.id as string
(session.user as any).role = token.role as string
(session.user as any).tokenVersion = token.tokenVersion as number
}
return session
},
},
providers: [
Credentials({
async authorize(credentials) {
const parsedCredentials = z
.object({ email: z.string().email(), password: z.string().min(6) })
.safeParse(credentials)
if (parsedCredentials.success) {
const { email, password } = parsedCredentials.data
try {
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000/api';
const res = await fetch(`${apiUrl}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
const data = await res.json();
if (res.ok && data.user) {
return data.user;
}
console.error("Login failed:", data.error);
} catch (e) {
console.error("Auth error", e);
}
}
return null
},
}),
],
})