mirror of
https://github.com/vercel/next-learn.git
synced 2026-06-27 14:44:17 +00:00
Add code for chapter 15
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
import { fetchFilteredCustomers } from '@/app/lib/data';
|
||||
import CustomersTable from '@/app/ui/customers/table';
|
||||
import { Metadata } from 'next';
|
||||
|
||||
export default async function Page({
|
||||
searchParams,
|
||||
|
||||
@@ -4,7 +4,6 @@ import { z } from 'zod';
|
||||
import { sql } from '@vercel/postgres';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { signIn } from '@/auth';
|
||||
|
||||
const FormSchema = z.object({
|
||||
id: z.string(),
|
||||
@@ -120,17 +119,3 @@ export async function deleteInvoice(formData: FormData) {
|
||||
return { message: 'Database Error: Failed to Delete Invoice.' };
|
||||
}
|
||||
}
|
||||
|
||||
export async function authenticate(
|
||||
prevState: string | undefined,
|
||||
formData: FormData,
|
||||
) {
|
||||
try {
|
||||
await signIn('credentials', Object.fromEntries(formData));
|
||||
} catch (error) {
|
||||
if ((error as Error).message.includes('CredentialsSignin')) {
|
||||
return 'CredentialsSignin';
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
import AcmeLogo from '@/app/ui/acme-logo';
|
||||
import LoginForm from '@/app/ui/login-form';
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<main className="flex items-center justify-center md:h-screen">
|
||||
<div className="relative mx-auto flex w-full max-w-[400px] flex-col space-y-2.5 p-4 md:-mt-32">
|
||||
<div className="flex h-20 w-full items-end rounded-lg bg-blue-500 p-3 md:h-36">
|
||||
<div className="w-32 text-white md:w-36">
|
||||
<AcmeLogo />
|
||||
</div>
|
||||
</div>
|
||||
<LoginForm />
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
'use client';
|
||||
|
||||
import { authenticate } from '@/app/lib/actions';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import {
|
||||
AtSymbolIcon,
|
||||
@@ -9,14 +8,10 @@ import {
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { ArrowRightIcon } from '@heroicons/react/20/solid';
|
||||
import { Button } from './button';
|
||||
import { useFormState, useFormStatus } from 'react-dom';
|
||||
|
||||
export default function LoginForm() {
|
||||
const [code, action] = useFormState(authenticate, undefined);
|
||||
const { pending } = useFormStatus();
|
||||
|
||||
return (
|
||||
<form action={action} className="space-y-3">
|
||||
<form className="space-y-3">
|
||||
<div className="flex-1 rounded-lg bg-gray-50 px-6 pb-4 pt-8">
|
||||
<h1 className={`${lusitana.className} mb-3 text-2xl`}>
|
||||
Please log in to continue.
|
||||
@@ -62,18 +57,9 @@ export default function LoginForm() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button className="mt-4 w-full" aria-disabled={pending}>
|
||||
Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" />
|
||||
</Button>
|
||||
<LoginButton />
|
||||
<div className="flex h-8 items-end space-x-1">
|
||||
{code === 'CredentialsSignin' && (
|
||||
<>
|
||||
<ExclamationCircleIcon className="h-5 w-5 text-red-500" />
|
||||
<p aria-live="polite" className="text-sm text-red-500">
|
||||
Invalid credentials
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
{/* Add form errors here */}
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -81,10 +67,8 @@ export default function LoginForm() {
|
||||
}
|
||||
|
||||
function LoginButton() {
|
||||
const { pending } = useFormStatus();
|
||||
|
||||
return (
|
||||
<Button className="mt-4 w-full" aria-disabled={pending}>
|
||||
<Button className="mt-4 w-full">
|
||||
Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" />
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import type { NextAuthConfig } from 'next-auth';
|
||||
|
||||
export const authConfig = {
|
||||
pages: {
|
||||
signIn: '/login',
|
||||
},
|
||||
providers: [
|
||||
// added later in auth.ts since it requires bcrypt which is only compatible with Node.js
|
||||
// while this file is also used in non-Node.js environments
|
||||
],
|
||||
callbacks: {
|
||||
authorized({ auth, request: { nextUrl } }) {
|
||||
const isLoggedIn = !!auth?.user;
|
||||
const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');
|
||||
if (isOnDashboard) {
|
||||
if (isLoggedIn) return true;
|
||||
return false; // Redirect unathenticated users to login page
|
||||
} else if (isLoggedIn) {
|
||||
return Response.redirect(new URL('/dashboard', nextUrl));
|
||||
}
|
||||
return true;
|
||||
},
|
||||
},
|
||||
} satisfies NextAuthConfig;
|
||||
@@ -1,43 +0,0 @@
|
||||
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): Promise<User | undefined> {
|
||||
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({
|
||||
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;
|
||||
|
||||
const user = await getUser(email);
|
||||
if (!user) return null;
|
||||
|
||||
const passwordsMatch = await bcrypt.compare(password, user.password);
|
||||
if (passwordsMatch) return user;
|
||||
}
|
||||
|
||||
console.log('Invalid credentials');
|
||||
return null;
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
import NextAuth from 'next-auth';
|
||||
import { authConfig } from './auth.config';
|
||||
|
||||
export default NextAuth(authConfig).auth;
|
||||
|
||||
export const config = {
|
||||
// https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
|
||||
matcher: ['/((?!api|_next/static|_next/image|.png).*)'],
|
||||
};
|
||||
Reference in New Issue
Block a user