Skip to content

Commit

Permalink
✨ added authentication and authtorisation, disabled state for buttons…
Browse files Browse the repository at this point in the history
… while isPending
  • Loading branch information
MammaSonnim committed Jul 26, 2024
1 parent d43a117 commit 0c96a18
Show file tree
Hide file tree
Showing 13 changed files with 173 additions and 24 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Based on [Next.js App Router Course](https://nextjs.org/learn), but I also imple
### Stack:

- Next.js
- Vercel + Postgres
- React Server Components
- Tailwind CSS
- Playwright
Expand Down
21 changes: 21 additions & 0 deletions app/lib/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { z } from 'zod';
import { sql } from '@vercel/postgres';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { AuthError } from 'next-auth';
import { signIn } from '@/auth';

const FormSchema = z.object({
id: z.string(),
Expand Down Expand Up @@ -125,3 +127,22 @@ export async function deleteInvoice(id: string) {

revalidatePath('/dashboard/invoices');
}

export async function authenticate(
prevState: string | undefined,
formData: FormData,
) {
try {
await signIn('credentials', formData);
} catch (error) {
if (error instanceof AuthError) {
switch (error.type) {
case 'CredentialsSignin':
return 'Invalid credentials.';
default:
return 'Something went wrong.';
}
}
throw error;
}
}
17 changes: 17 additions & 0 deletions app/login/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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>
);
}
2 changes: 1 addition & 1 deletion app/ui/button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function Button({ children, className, ...rest }: ButtonProps) {
<button
{...rest}
className={clsx(
'flex h-10 items-center rounded-lg bg-blue-500 px-4 text-sm font-medium text-white transition-colors hover:bg-blue-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500 active:bg-blue-600 aria-disabled:cursor-not-allowed aria-disabled:opacity-50',
'flex h-10 items-center rounded-lg bg-blue-500 px-4 text-sm font-medium text-white transition-colors hover:bg-blue-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500 active:bg-blue-600 aria-disabled:pointer-events-none aria-disabled:opacity-50',
className,
)}
>
Expand Down
9 changes: 8 additions & 1 deletion app/ui/dashboard/sidenav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Link from 'next/link';
import NavLinks from '@/app/ui/dashboard/nav-links';
import AcmeLogo from '@/app/ui/acme-logo';
import { PowerIcon } from '@heroicons/react/24/outline';
import { signOut } from '@/auth';

export default function SideNav() {
return (
Expand All @@ -17,7 +18,13 @@ export default function SideNav() {
<div className="flex grow flex-row justify-between space-x-2 md:flex-col md:space-x-0 md:space-y-2">
<NavLinks />
<div className="hidden h-auto w-full grow rounded-md bg-gray-50 md:block"></div>
<form>
<form
// eslint-disable-next-line @typescript-eslint/no-misused-promises
action={async () => {
'use server';
await signOut();
}}
>
<button className="flex h-[48px] w-full grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3">
<PowerIcon className="w-6" />
<div className="hidden md:block">Sign Out</div>
Expand Down
7 changes: 5 additions & 2 deletions app/ui/invoices/buttons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function UpdateInvoice({ id }: { id: string }) {

export function DeleteInvoice({ id }: { id: string }) {
const deleteInvoiceWithId = deleteInvoice.bind(null, id);
const [state, formAction] = useActionState(deleteInvoiceWithId, {
const [state, formAction, isPending] = useActionState(deleteInvoiceWithId, {
message: '',
});
const { setMessage } = useNotification();
Expand All @@ -44,7 +44,10 @@ export function DeleteInvoice({ id }: { id: string }) {

return (
<form action={formAction}>
<button className="rounded-md border p-2 hover:bg-gray-100">
<button
className="rounded-md border p-2 hover:bg-gray-100 aria-disabled:pointer-events-none aria-disabled:opacity-50"
aria-disabled={isPending}
>
<span className="sr-only">Delete</span>
<TrashIcon className="w-5" />
</button>
Expand Down
6 changes: 4 additions & 2 deletions app/ui/invoices/create-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { createInvoice } from '@/app/lib/actions';
import { useNotification } from '../notification-context';

export default function Form({ customers }: { customers: CustomerField[] }) {
const [state, formAction] = useActionState(createInvoice, {
const [state, formAction, isPending] = useActionState(createInvoice, {
message: '',
errors: {},
});
Expand Down Expand Up @@ -147,7 +147,9 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
>
Cancel
</Link>
<Button type="submit">Create Invoice</Button>
<Button type="submit" aria-disabled={isPending}>
Create Invoice
</Button>
</div>
</form>
);
Expand Down
6 changes: 4 additions & 2 deletions app/ui/invoices/edit-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default function EditInvoiceForm({
customers: CustomerField[];
}) {
const updateInvoiceWithId = updateInvoice.bind(null, invoice.id);
const [state, formAction] = useActionState(updateInvoiceWithId, {
const [state, formAction, isPending] = useActionState(updateInvoiceWithId, {
message: '',
errors: {},
});
Expand Down Expand Up @@ -157,7 +157,9 @@ export default function EditInvoiceForm({
>
Cancel
</Link>
<Button type="submit">Edit Invoice</Button>
<Button type="submit" aria-disabled={isPending}>
Edit Invoice
</Button>
</div>
</form>
);
Expand Down
26 changes: 22 additions & 4 deletions app/ui/login-form.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
'use client';

import { lusitana } from '@/app/ui/fonts';
import { AtSymbolIcon, KeyIcon } from '@heroicons/react/24/outline';
import {
AtSymbolIcon,
KeyIcon,
ExclamationCircleIcon,
} from '@heroicons/react/24/outline';
import { ArrowRightIcon } from '@heroicons/react/20/solid';
import { useActionState } from 'react';
import { Button } from './button';
import { authenticate } from '@/app/lib/actions';

export default function LoginForm() {
const [errorMessage, formAction, isPending] = useActionState(
authenticate,
undefined,
);

return (
<form className="space-y-3">
<form action={formAction} 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.
Expand Down Expand Up @@ -51,11 +64,16 @@ export default function LoginForm() {
</div>
</div>
</div>
<Button className="mt-4 w-full">
<Button className="mt-4 w-full" aria-disabled={isPending}>
Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" />
</Button>
<div className="flex h-8 items-end space-x-1">
{/* Add form errors here */}
{errorMessage && (
<>
<ExclamationCircleIcon className="h-5 w-5 text-red-500" />
<p className="text-sm text-red-500">{errorMessage}</p>
</>
)}
</div>
</div>
</form>
Expand Down
24 changes: 24 additions & 0 deletions auth.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { NextAuthConfig } from 'next-auth';

export const authConfig = {
pages: {
signIn: '/login',
},
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = Boolean(auth?.user);
const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');

if (isOnDashboard) {
return isLoggedIn;
}

if (isLoggedIn) {
return Response.redirect(new URL('/dashboard', nextUrl));
}

return true;
},
},
providers: [], // Add providers with an empty array for now
} satisfies NextAuthConfig;
42 changes: 42 additions & 0 deletions auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { authConfig } from './auth.config';
import { z } from 'zod';
import { sql } from '@vercel/postgres';
import type { User } from '@/app/lib/definitions';
import bcrypt from 'bcrypt';

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;
},
}),
],
});
9 changes: 9 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
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$).*)'],
};
27 changes: 15 additions & 12 deletions scripts/seed.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable */
const { db } = require('@vercel/postgres');
const {
invoices,
Expand Down Expand Up @@ -26,11 +27,12 @@ async function seedUsers(client) {
const insertedUsers = await Promise.all(
users.map(async (user) => {
const hashedPassword = await bcrypt.hash(user.password, 10);

return client.sql`
INSERT INTO users (id, name, email, password)
VALUES (${user.id}, ${user.name}, ${user.email}, ${hashedPassword})
ON CONFLICT (id) DO NOTHING;
`;
INSERT INTO users (id, name, email, password)
VALUES (${user.id}, ${user.name}, ${user.email}, ${hashedPassword})
ON CONFLICT (id) DO NOTHING;
`;
}),
);

Expand All @@ -52,14 +54,14 @@ async function seedInvoices(client) {

// Create the "invoices" table if it doesn't exist
const createTable = await client.sql`
CREATE TABLE IF NOT EXISTS invoices (
id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
customer_id UUID NOT NULL,
amount INT NOT NULL,
status VARCHAR(255) NOT NULL,
date DATE NOT NULL
);
`;
CREATE TABLE IF NOT EXISTS invoices (
id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
customer_id UUID NOT NULL,
amount INT NOT NULL,
status VARCHAR(255) NOT NULL,
date DATE NOT NULL
);
`;

console.log(`Created "invoices" table`);

Expand Down Expand Up @@ -177,3 +179,4 @@ main().catch((err) => {
err,
);
});
/* eslint-enable */

0 comments on commit 0c96a18

Please sign in to comment.