db authentication replaced by Google
This commit is contained in:
3
.env
3
.env
@@ -1,6 +1,5 @@
|
||||
AUTH_SECRET=Gh0jQ35oq6DR8HkLR3heA8EaEDtxYN/xkP6blvukZ0w=
|
||||
MONGODB_URI=mongodb://root:example@localhost:27017/
|
||||
|
||||
GOOGLE_ID=355397364527-adjrokm6hromcaaar0qfhk050mfr35ou.apps.googleusercontent.com
|
||||
GOOGLE_SECRET=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
|
||||
NEXT_AUTH_SECRET=Gh0jQ35oq6DR8HkLR3heA8EaEDtxYN/xkP6blvukZ0w=
|
||||
AUTH_SECRET=Gh0jQ35oq6DR8HkLR3heA8EaEDtxYN/xkP6blvukZ0w=
|
||||
|
||||
1
app/api/auth/[...nextauth]/route.ts
Normal file
1
app/api/auth/[...nextauth]/route.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { GET, POST } from '@/app/lib/auth.google';
|
||||
@@ -2,6 +2,18 @@ import NextAuth, { NextAuthConfig } from 'next-auth';
|
||||
import GoogleProvider from 'next-auth/providers/google';
|
||||
|
||||
export const authConfig:NextAuthConfig = {
|
||||
callbacks: {
|
||||
async signIn({ account, profile }) {
|
||||
if (account?.provider === "google") {
|
||||
return profile?.email_verified === true && profile?.email?.endsWith("@google.com") === true
|
||||
}
|
||||
return true // Do different verification for other providers that don't have `email_verified`
|
||||
},
|
||||
authorized({ auth, request: { nextUrl } }) {
|
||||
const isLoggedIn = !!auth?.user;
|
||||
return(isLoggedIn);
|
||||
},
|
||||
},
|
||||
providers: [
|
||||
GoogleProvider({
|
||||
clientId: process.env.GOOGLE_ID,
|
||||
29
app/lib/auth.google.ts
Normal file
29
app/lib/auth.google.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import NextAuth, { NextAuthConfig } from 'next-auth';
|
||||
import GoogleProvider from 'next-auth/providers/google';
|
||||
|
||||
const authConfig: NextAuthConfig = {
|
||||
callbacks: {
|
||||
// This method verifies if the user is logged in or not
|
||||
// It is called by Next-Auth when the midleware calls
|
||||
// the `auth` method (exported below)
|
||||
authorized({ auth, request: { nextUrl } }) {
|
||||
const isLoggedIn = !!auth?.user;
|
||||
return (isLoggedIn);
|
||||
},
|
||||
},
|
||||
providers: [
|
||||
GoogleProvider({
|
||||
clientId: process.env.GOOGLE_ID,
|
||||
clientSecret: process.env.GOOGLE_SECRET,
|
||||
}),
|
||||
],
|
||||
secret: process.env.AUTH_SECRET,
|
||||
session: {
|
||||
// Use JSON Web Tokens for session instead of database sessions.
|
||||
// This option can be used with or without a database for users/accounts.
|
||||
// Note: `jwt` is automatically set to `true` if no database is specified.
|
||||
strategy: 'jwt'
|
||||
},
|
||||
};
|
||||
|
||||
export const { auth, handlers: { GET, POST } } = NextAuth(authConfig);
|
||||
@@ -1,23 +0,0 @@
|
||||
'use server';
|
||||
|
||||
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,11 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
13
app/page.tsx
13
app/page.tsx
@@ -5,6 +5,8 @@ import { AddLocationButton } from './ui/AddLocationButton';
|
||||
import clientPromise from './lib/mongodb';
|
||||
import { BillingLocation } from './lib/db-types';
|
||||
import { PageFooter } from './ui/PageFooter';
|
||||
import { auth } from '@/app/lib/auth.google';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
const getNextYearMonth = (yearMonth:number) => {
|
||||
return(yearMonth % 100 === 12 ? yearMonth + 89 : yearMonth + 1);
|
||||
@@ -12,9 +14,11 @@ const getNextYearMonth = (yearMonth:number) => {
|
||||
|
||||
export const Page = async () => {
|
||||
|
||||
const session = await auth();
|
||||
|
||||
const client = await clientPromise;
|
||||
const db = client.db("rezije");
|
||||
|
||||
|
||||
const locations = await db.collection<BillingLocation>("lokacije")
|
||||
.find({})
|
||||
.sort({ yearMonth: -1, name: 1 }) // sort by yearMonth descending
|
||||
@@ -57,6 +61,13 @@ export const Page = async () => {
|
||||
})
|
||||
}
|
||||
<PageFooter />
|
||||
<ul>
|
||||
<li>session.expires = { session?.expires }</li>
|
||||
<li>session.user.id = { session?.user?.id }</li>
|
||||
<li>session.user.email = { session?.user?.email }</li>
|
||||
<li>session.user.name = { session?.user?.name }</li>
|
||||
<li>session.user.image = { session?.user?.image }</li>
|
||||
</ul>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
'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>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
/**
|
||||
* @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
67
auth.ts
@@ -1,67 +0,0 @@
|
||||
/**
|
||||
* @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.db';
|
||||
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;
|
||||
}
|
||||
})
|
||||
],
|
||||
});
|
||||
@@ -3,12 +3,11 @@
|
||||
* @description hooks-up `next-auth` into the page processing pipeline
|
||||
*/
|
||||
|
||||
import NextAuth from 'next-auth';
|
||||
import { authConfig } from './auth.config.db';
|
||||
import { auth } from '@/app/lib/auth.google'
|
||||
|
||||
export default NextAuth(authConfig).auth;
|
||||
export default auth; // middleware will call NextAuth's `auth` method, which will in turn call) see `auth.config.google.ts`
|
||||
|
||||
export const config = {
|
||||
// https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
|
||||
// midleware will NOT be called for paths: ['/api/auth/*', '/_next/static/*', '/_next/image*']
|
||||
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
|
||||
};
|
||||
Reference in New Issue
Block a user