adding clerk authentication

This commit is contained in:
2025-01-22 23:11:25 -05:00
parent 1a59ac8373
commit 9931980114
8 changed files with 370 additions and 52 deletions

View File

@@ -1,7 +1,7 @@
'use server';
import { eq, not , asc} from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { db } from "@db/index";
import { db } from "@src/db";
import { users } from "@schemas/schema";
export const getData = async () => {
@@ -14,7 +14,7 @@ export const getAllUsersOrdrByLastname = async () => {
};
export const getUserByEmail = async (email:string) => {
return getData();
return await db.select().from(users).where(eq(users.email, email));
};
export const getUserByUUID = async (uuid:string) => {
@@ -22,10 +22,23 @@ export const getUserByUUID = async (uuid:string) => {
return data[0];
};
export const addUser = async ( first_name: string, last_name: string, username: string, email: string, password_hash : string) => {
/*export const addUser = async ( first_name: string, last_name: string, username: string, email: string, password_hash : string) => {
await db.insert(users).values({
first_name : first_name, last_name: last_name, username: email, email: email, password_hash : password_hash
});
first_name : first_name, last_name: last_name, username: email, email: email, password_hash : password_hash
});
};*/
export const addUser = async (first_name: string, last_name: string, username: string, email: string, password_hash: string) => {
const [addedUser] = await db.insert(users).values({
name: `${first_name} ${last_name}`,
first_name: first_name,
last_name: last_name,
username: email,
email: email,
password_hash: password_hash,
full_name: `${first_name} ${last_name}`,
}).returning(); // Returns the inserted user (adjust "*" to specific columns if necessary)
return addedUser;
};
export const deleteUser = async (id: string) => {

View File

@@ -4,7 +4,14 @@ import PopNav from "@components/PopNav/page";
import { Roboto } from 'next/font/google'
import constants from "@src/lib/constants";
import Footer from "@components/footer";
import '../styles/globals.css'
import {
ClerkProvider,
SignInButton,
SignedIn,
SignedOut,
UserButton
} from '@clerk/nextjs';
export const metadata = {
title: constants.APP_NAME,
description: constants.DESCRIPTION,
@@ -21,14 +28,25 @@ export default function RootLayout(props: { children: React.ReactNode }) {
const { children } = props;
return (
<html suppressHydrationWarning className={roboto.className}>
<body className="bg-slate-200 ">
<Navbar />
<PopNav />
{children}
<Footer />
</body>
</html>
<ClerkProvider>
<html lang="en" suppressHydrationWarning className={roboto.className}>
<body className="bg-slate-200 ">
<header>
<SignedOut>
<SignInButton />
</SignedOut>
<SignedIn>
<UserButton />
</SignedIn>
</header>
<Navbar />
<PopNav />
<main>
{children}
</main>
<Footer />
</body>
</html>
</ClerkProvider>
)
}

View File

@@ -27,20 +27,22 @@ export default function RegistrationForm() {
return;
}
const existingUser : any = null;
if((await getUserByEmail(formData.email)).length > 0){
let existingUser : any = null;
existingUser = await getUserByEmail(formData.email);
console.log(existingUser);
if(existingUser.length > 0){
setError("Duplicate E-Mail Address");
return
}
try {
const hashedPassword = await bcrypt.hash(formData.password, 10);
addUser(
formData.first_name,
formData.last_name,
formData.username,
formData.email,
hashedPassword
await addUser(
formData.first_name,
formData.last_name,
formData.username,
formData.email,
hashedPassword
);
router.push("/signin"); // Redirect to login after successful registration
} catch (err) {

View File

@@ -16,9 +16,8 @@ export const products = pgTable("products", {
export const users = pgTable("users", {
id: text("id")
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
id: uuid("id").primaryKey().defaultRandom(),
name: varchar("name").notNull(),
username: varchar({ length: 50 }).notNull(),
email: varchar({ length: 255 }).notNull(),
emailVerifiedOn: timestamp("email_verified_on", { mode: "date" }),
@@ -27,6 +26,7 @@ export const users = pgTable("users", {
last_name: varchar("last_name", { length: 50 }),
full_name: varchar("full_name", { length: 50 }),
profilePicture: varchar("profile_picture", { length: 255 }),
image: text("image"),
dateOfBirth: date("date_of_birth"),
phoneNumber: varchar("phone_number", { length: 20 }),
createdAt: timestamp("created_at", { mode: 'string' }).default(sql`CURRENT_TIMESTAMP`),
@@ -92,10 +92,11 @@ export const brands = pgTable("brands", {
});
export const sessions = pgTable("sessions", {
sessionToken: text().primaryKey().notNull(),
userId: text().notNull(),
expires: timestamp({ mode: 'string' }).notNull(),
});
id: uuid("id").primaryKey().defaultRandom(),
sessionToken: varchar("session_token").notNull(),
userId: uuid("user_id").notNull(),
expires: timestamp("expires").notNull(),
});
export const manufacturer = pgTable("manufacturer", {
id: integer().primaryKey().generatedAlwaysAsIdentity({ name: "manufacturer_id_seq", startWith: 1, increment: 1, minValue: 1, maxValue: 2147483647, cache: 1 }),
@@ -399,13 +400,9 @@ export const balResellers = pgTable("bal_resellers", {
});
export const verificationTokens = pgTable("verificationTokens", {
identifier: text().notNull(),
token: text().notNull(),
expires: timestamp({ mode: 'string' }).notNull(),
}, (table) => {
return {
verificationTokenIdentifierTokenPk: primaryKey({ columns: [table.identifier, table.token], name: "verificationToken_identifier_token_pk"}),
}
identifier: varchar("identifier").notNull(),
token: varchar("token").notNull(),
expires: timestamp("expires").notNull(),
});
export const authenticator = pgTable("authenticator", {
@@ -425,25 +422,23 @@ export const authenticator = pgTable("authenticator", {
});
export const accounts = pgTable("accounts", {
uuid: uuid().defaultRandom(),
userId: text("user_id").notNull(),
type: text().notNull(),
id: uuid("id").primaryKey().defaultRandom(),
uuid: uuid("uuid").defaultRandom(),
userId: uuid("user_id").notNull(),
type: varchar("type").notNull(),
provider: text().notNull(),
providerAccountId: text("provider_account_id").notNull(),
providerAccountId: varchar("provider_account_id").notNull(),
refreshToken: text("refresh_token"),
accessToken: text("access_token"),
expiresAt: integer("expires_at"),
tokenType: text("token_type"),
scope: text(),
tokenType: varchar("token_type"),
idToken: text("id_token"),
sessionState: text("session_state"),
}, (table) => {
return {
accountProviderProviderAccountIdPk: primaryKey({ columns: [table.provider, table.providerAccountId], name: "account_provider_providerAccountId_pk"}),
}
});
sessionState: varchar("session_state"),
scope: text(),
}
);
export const vw_accounts = pgView("vw_accounts", {
/* export const vw_accounts = pgView("vw_accounts", {
uuid: uuid().defaultRandom(),
userId: text("user_id").notNull(),
type: text().notNull(),
@@ -459,4 +454,4 @@ export const vw_accounts = pgView("vw_accounts", {
first_name: text("first_name"),
last_name: text("last_name"),
},).existing();
},).existing(); */

12
src/middleware.ts Normal file
View File

@@ -0,0 +1,12 @@
import { clerkMiddleware } from "@clerk/nextjs/server";
export default clerkMiddleware();
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
// Always run for API routes
'/(api|trpc)(.*)',
],
};