Files
estimation-flow/src/auth.config.ts
T

62 lines
1.7 KiB
TypeScript

import type { NextAuthConfig } from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { z } from 'zod';
import db from '@/lib/db';
export const authConfig = {
pages: {
signIn: '/login',
},
providers: [
Credentials({
async authorize(credentials) {
const parsedCredentials = z
.object({ email: z.string().email(), password: z.string().min(1) })
.safeParse(credentials);
if (parsedCredentials.success) {
const { email, password } = parsedCredentials.data;
try {
const userStmt = db.prepare('SELECT * FROM users WHERE email = ?');
const user = userStmt.get(email) as any;
if (!user) return null;
// WARNING: Storing passwords in plaintext is insecure.
// This is for demonstration purposes only.
// In a real application, you MUST hash and salt passwords.
const passwordsMatch = password === user.password;
if (passwordsMatch) return user;
} catch (e) {
console.error(e)
return null
}
}
return null;
},
}),
],
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
const isOnAdmin = nextUrl.pathname.startsWith('/admin');
if (isOnAdmin) {
return isLoggedIn;
} else if (isLoggedIn) {
// Redirect logged-in users from the login page to the admin dashboard
if (nextUrl.pathname === '/login') {
return Response.redirect(new URL('/admin', nextUrl));
}
return true;
}
return true;
},
},
} satisfies NextAuthConfig;