implemented login
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -26,7 +26,6 @@ yarn-error.log*
|
|||||||
|
|
||||||
# local env files
|
# local env files
|
||||||
.env*.local
|
.env*.local
|
||||||
.env
|
|
||||||
|
|
||||||
# vercel
|
# vercel
|
||||||
.vercel
|
.vercel
|
||||||
|
|||||||
15
README.md
15
README.md
@@ -5,4 +5,17 @@
|
|||||||
* multi-user support
|
* multi-user support
|
||||||
* bill amount entry
|
* bill amount entry
|
||||||
* monthly bill amount summery
|
* monthly bill amount summery
|
||||||
* build & deploy via docker
|
* build & deploy via docker
|
||||||
|
|
||||||
|
|
||||||
|
# Authentication
|
||||||
|
Authentication consists of the following parts:
|
||||||
|
* `next-auth` boilerplate
|
||||||
|
* `middleware.ts` = hooks-up `next-auth` into the page processing pipeline
|
||||||
|
* `auth.config.ts` = defines how user session is to be checked and redirects anonymous user to login page
|
||||||
|
* `auth.ts` = verifies user credentials during the log-in action (i.e. against a database)
|
||||||
|
* exports `auth`, `signIn`, `signOut` actions
|
||||||
|
* UI boilerplate
|
||||||
|
* `sidenav.tsx` = implements logout action - calls `signOut` from `auth.ts`
|
||||||
|
* `login-form.tsx` = implements login form
|
||||||
|
* `actions.ts` = handles login-form validation and submition - calls `signIn` from `auth.ts`
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { z } from 'zod';
|
|||||||
import { revalidatePath } from 'next/cache';
|
import { revalidatePath } from 'next/cache';
|
||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
import clientPromise from './mongodb';
|
import clientPromise from './mongodb';
|
||||||
import { BillAttachment, Bill, BillingLocation } from './db-types';
|
import { BillAttachment, BillingLocation } from './db-types';
|
||||||
import { ObjectId } from 'mongodb';
|
import { ObjectId } from 'mongodb';
|
||||||
|
|
||||||
export type State = {
|
export type State = {
|
||||||
|
|||||||
12
app/lib/global.d.ts
vendored
12
app/lib/global.d.ts
vendored
@@ -1,8 +1,8 @@
|
|||||||
import { MongoClient } from "mongodb";
|
import { MongoClient } from "mongodb";
|
||||||
|
|
||||||
declare global {
|
// declare global {
|
||||||
namespace globalThis {
|
// namespace globalThis {
|
||||||
/** global Mongo Client used in development */
|
// /** global Mongo Client used in development */
|
||||||
var _mongoClientPromise: Promise<MongoClient>
|
// var _mongoClientPromise: Promise<MongoClient>
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
21
app/lib/loginActions.ts
Normal file
21
app/lib/loginActions.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { signIn } from '@/auth';
|
||||||
|
import { AuthError } from 'next-auth';
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
import { Client, QueryResult, QueryResultRow } from 'pg';
|
|
||||||
|
|
||||||
const client = new Client({
|
|
||||||
// connectionString: process.env.DATABASE_URL,
|
|
||||||
host: process.env.POSTGRES_HOST,
|
|
||||||
user: process.env.POSTGRES_USER,
|
|
||||||
password: process.env.POSTGRES_PASSWORD,
|
|
||||||
database: process.env.POSTGRES_DB
|
|
||||||
});
|
|
||||||
|
|
||||||
client.connect();
|
|
||||||
|
|
||||||
/** an adapter function which simulates @vercel/postgres `sql` function */
|
|
||||||
export function sql<T extends QueryResultRow>(strings: TemplateStringsArray, ...values: any[]): Promise<QueryResult<T>> {
|
|
||||||
// string values need to be wrapped in single quotes
|
|
||||||
const fixedValues = values.map((value) => {
|
|
||||||
if (typeof value === 'string') {
|
|
||||||
return `'${value}'`;
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
});
|
|
||||||
|
|
||||||
const query = String.raw(strings, ...fixedValues);
|
|
||||||
return client.query<T>(query);
|
|
||||||
}
|
|
||||||
6
app/lib/types/User.ts
Normal file
6
app/lib/types/User.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export type User = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
};
|
||||||
11
app/login/page.tsx
Normal file
11
app/login/page.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import LoginForm from '@/app/ui/LoginForm';
|
||||||
|
|
||||||
|
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">
|
||||||
|
<LoginForm />
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
91
app/ui/LoginForm.tsx
Normal file
91
app/ui/LoginForm.tsx
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { lusitana } from '@/app/ui/fonts';
|
||||||
|
import {
|
||||||
|
AtSymbolIcon,
|
||||||
|
KeyIcon,
|
||||||
|
ExclamationCircleIcon,
|
||||||
|
} from '@heroicons/react/24/outline';
|
||||||
|
import { ArrowRightIcon } from '@heroicons/react/20/solid';
|
||||||
|
import { Button } from './button';
|
||||||
|
import { useFormState } from 'react-dom';
|
||||||
|
import { authenticate } from '@/app/lib/loginActions';
|
||||||
|
|
||||||
|
export default function LoginForm() {
|
||||||
|
|
||||||
|
const [errorMessage, dispatch] = useFormState(authenticate, undefined);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form className="space-y-3" action={dispatch}>
|
||||||
|
<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.
|
||||||
|
</h1>
|
||||||
|
<div className="w-full">
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
className="mb-3 mt-5 block text-xs font-medium text-gray-900"
|
||||||
|
htmlFor="email"
|
||||||
|
>
|
||||||
|
Email
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<input
|
||||||
|
className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
name="email"
|
||||||
|
placeholder="Enter your email address"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<AtSymbolIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4">
|
||||||
|
<label
|
||||||
|
className="mb-3 mt-5 block text-xs font-medium text-gray-900"
|
||||||
|
htmlFor="password"
|
||||||
|
>
|
||||||
|
Password
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<input
|
||||||
|
className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
name="password"
|
||||||
|
placeholder="Enter password"
|
||||||
|
required
|
||||||
|
minLength={6}
|
||||||
|
/>
|
||||||
|
<KeyIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<LoginButton />
|
||||||
|
<div className="flex h-8 items-end space-x-1">
|
||||||
|
<div
|
||||||
|
className="flex h-8 items-end space-x-1"
|
||||||
|
aria-live="polite"
|
||||||
|
aria-atomic="true"
|
||||||
|
>
|
||||||
|
{errorMessage && (
|
||||||
|
<>
|
||||||
|
<ExclamationCircleIcon className="h-5 w-5 text-red-500" />
|
||||||
|
<p className="text-sm text-red-500">{errorMessage}</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LoginButton() {
|
||||||
|
return (
|
||||||
|
<Button className="mt-4 w-full">
|
||||||
|
Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" />
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
24
auth.config.ts
Normal file
24
auth.config.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
/**
|
||||||
|
* @module auth.config.ts
|
||||||
|
* @description defines how user session is to be checked and redirects anonymous user to login page
|
||||||
|
*/
|
||||||
|
import type { NextAuthConfig } from 'next-auth';
|
||||||
|
|
||||||
|
export const authConfig = {
|
||||||
|
pages: {
|
||||||
|
signIn: '/login',
|
||||||
|
},
|
||||||
|
// this will prevent users from accessing the dashboard pages unless they are logged in
|
||||||
|
callbacks: {
|
||||||
|
// The authorized callback is used to verify if the request is authorized to access a
|
||||||
|
// page via Next.js Middleware. It is called before a request is completed, and it
|
||||||
|
// receives an object with the auth and request properties.
|
||||||
|
// The auth property contains the user's session, and the request property contains
|
||||||
|
// the incoming request.
|
||||||
|
authorized({ auth, request: { nextUrl } }) {
|
||||||
|
const isLoggedIn = !!auth?.user;
|
||||||
|
return(isLoggedIn);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
providers: [], // Add providers with an empty array for now
|
||||||
|
} satisfies NextAuthConfig;
|
||||||
67
auth.ts
Normal file
67
auth.ts
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
/**
|
||||||
|
* @module auth
|
||||||
|
* @description verifies user credentials during the log-in action (i.e. against a database)
|
||||||
|
* @exports exports `auth`, `signIn`, `signOut` actions
|
||||||
|
*/
|
||||||
|
import NextAuth from 'next-auth';
|
||||||
|
import { authConfig } from './auth.config';
|
||||||
|
import Credentials from 'next-auth/providers/credentials';
|
||||||
|
import { z } from 'zod';
|
||||||
|
// import bcrypt from 'bcrypt';
|
||||||
|
import { User } from '@/app/lib/types/User';
|
||||||
|
|
||||||
|
const dummyUser:User = {
|
||||||
|
id: "1",
|
||||||
|
email: "nikola.derezic@gmail.com",
|
||||||
|
password: "123456",
|
||||||
|
name: "Nikola Derezic"
|
||||||
|
};
|
||||||
|
|
||||||
|
async function getUser(email: string): Promise<User | undefined> {
|
||||||
|
// temporary use dummyUser instead of db
|
||||||
|
if(email === dummyUser.email) {
|
||||||
|
return dummyUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 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) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { email, password } = parsedCredentials.data;
|
||||||
|
|
||||||
|
const user = await getUser(email);
|
||||||
|
|
||||||
|
if (!user) return null;
|
||||||
|
|
||||||
|
// const passwordsMatch = await bcrypt.compare(password, user.password);
|
||||||
|
const passwordsMatch = password === user.password;
|
||||||
|
|
||||||
|
if (!passwordsMatch) return null;
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
],
|
||||||
|
});
|
||||||
14
middleware.ts
Normal file
14
middleware.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
/**
|
||||||
|
* @module middleware
|
||||||
|
* @description hooks-up `next-auth` into the page processing pipeline
|
||||||
|
*/
|
||||||
|
|
||||||
|
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$).*)'],
|
||||||
|
};
|
||||||
2
package-lock.json
generated
2
package-lock.json
generated
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"name": "rezije",
|
"name": "evidencija-rezija",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
|
|||||||
Reference in New Issue
Block a user