This commit is contained in:
StephDietz
2023-09-21 15:45:35 -05:00
parent dbc2216ef4
commit 456e76f4cf
2 changed files with 54 additions and 50 deletions

View File

@@ -1,53 +1,6 @@
import NextAuth, { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import bcrypt from 'bcrypt';
import { fetchUser } from '../../../lib/data';
import { User } from '@/app/lib/definitions';
const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: 'credentials',
credentials: {},
// TODO: Not sure how to type authorize function correctly
// @ts-ignore
async authorize(credentials: {
email: string;
password: string;
}): Promise<User | null | undefined> {
const { email, password } = credentials;
try {
const user = await fetchUser(email);
if (!user) {
return null;
}
const passwordsMatch = await bcrypt.compare(password, user.password);
if (!passwordsMatch) {
console.log('Passwords do not match');
return null;
}
return user;
} catch (error) {
console.log('Error: ', error);
}
},
}),
],
session: {
strategy: 'jwt',
},
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: '/login',
},
};
import { authOptions } from '@/auth';
import NextAuth from 'next-auth';
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST, authOptions };
export { handler as GET, handler as POST };

View File

@@ -0,0 +1,51 @@
import { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import bcrypt from 'bcrypt';
import { User } from '@/app/lib/definitions';
import { sql } from '@vercel/postgres';
async function getUser(email: string) {
try {
const user = await sql`SELECT * from USERS where email=${email}`;
console.log('USER', user);
return user.rows[0] as User;
} catch (error) {
console.error('Failed to fetch user:', error);
throw new Error('Failed to fetch user.');
}
}
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: 'credentials',
credentials: {
password: { label: 'Password', type: 'password' },
email: { label: 'Email', type: 'email' },
},
// @ts-ignore
async authorize(credentials) {
console.log('debugging credentials', credentials);
const { email, password } = credentials ?? {};
const user = await getUser(email as string);
if (!user || !password) {
console.log('Missing credentials');
return null;
}
const passwordsMatch = await bcrypt.compare(password, user.password);
if (!passwordsMatch) {
console.log('Invalid credentials');
return null;
}
return user;
},
}),
],
pages: {
signIn: '/login',
},
};