mirror of
https://github.com/vercel/next-learn.git
synced 2026-06-23 20:55:50 +00:00
* Update to latest + refactoring. * idk, fuck it * Trying to make it work * add `next-auth` fixes (#211) Co-authored-by: Balázs Orbán <info@balazsorban.com> * Another one * test * bump `next` and `next-auth`, `bcrypt` -> `bcryptjs` * simplify * upgrade types * add basic html form validatoin * add zod validation * update * remove non next-auth changes * revert * revert * revert * revert * uses bcrypt * fix imports * tweaks * revert * revert * revert --------- Co-authored-by: Lee Robinson <lrobinson2011@gmail.com> Co-authored-by: Delba de Oliveira <delbabrown@gmail.com>
52 lines
1.5 KiB
TypeScript
52 lines
1.5 KiB
TypeScript
import NextAuth from 'next-auth';
|
|
import Credentials from 'next-auth/providers/credentials';
|
|
import bcrypt from 'bcrypt';
|
|
import { sql } from '@vercel/postgres';
|
|
import { z } from 'zod';
|
|
import type { User } from '@/app/lib/definitions';
|
|
import { authConfig } from './auth.config';
|
|
|
|
async function getUser(email: string) {
|
|
try {
|
|
const user = await sql<User>`SELECT * from USERS where email=${email}`;
|
|
return user.rows[0];
|
|
} catch (error) {
|
|
console.error('Failed to fetch user:', error);
|
|
throw new Error('Failed to fetch user.');
|
|
}
|
|
}
|
|
|
|
export const { auth, signIn, signOut } = NextAuth({
|
|
...authConfig,
|
|
providers: [
|
|
Credentials({
|
|
name: 'Sign-In with Credentials',
|
|
credentials: {
|
|
password: { label: 'Password', type: 'password' },
|
|
email: { label: 'Email', type: 'email' },
|
|
},
|
|
async authorize(credentials) {
|
|
const validatedCredentials = z
|
|
.object({ email: z.string().email(), password: z.string().min(6) })
|
|
.safeParse(credentials);
|
|
|
|
if (!validatedCredentials.success) {
|
|
console.log('Invalid credentials');
|
|
return null;
|
|
}
|
|
|
|
const { email, password } = validatedCredentials.data;
|
|
const user = await getUser(email);
|
|
const passwordsMatch = await bcrypt.compare(password, user.password);
|
|
|
|
if (!passwordsMatch) {
|
|
console.log('Invalid credentials');
|
|
return null;
|
|
}
|
|
|
|
return { ...user, id: user.id.toString() };
|
|
},
|
|
}),
|
|
],
|
|
});
|