Skip to content

Commit

Permalink
Merge pull request #749 from ShivanshPlays/seller-login
Browse files Browse the repository at this point in the history
 login for seller feature
  • Loading branch information
mdazfar2 authored Oct 18, 2024
2 parents 2a2b967 + 382ce21 commit c892aae
Show file tree
Hide file tree
Showing 9 changed files with 124 additions and 68 deletions.
6 changes: 3 additions & 3 deletions app/(Seller)/auth/components/loginPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const LoginPage: React.FC<LoginPageProps> = ({
if (result?.error) setError("Invalid email or password");
else {
toast.success(`Welcome ${session.data?.user?.name}`);
window.location.href = "/"; // Redirect on success
window.location.href = "/dashboard"; // Redirect on success
}
setloading(false);
};
Expand Down Expand Up @@ -93,8 +93,8 @@ const LoginPage: React.FC<LoginPageProps> = ({
</div>
<Button
type="submit"
disabled
// disabled={loading}
// disabled
disabled={loading}
className="rounded-full bg-customTeal dark:bg-Green font-bold h-10 w-4/5 disabled"
>
{loading ? <Spinner /> : "Login"}
Expand Down
4 changes: 2 additions & 2 deletions app/(Seller)/auth/components/signupPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const SignupPage: React.FC<SignupPageProps> =({ switchCss, setSwitchCss,setError
}


const result = await axios.post('/api/auth/signup',{
const result = await axios.post('/api/auth/signup/seller',{
email,
password,
name:fullname,
Expand All @@ -55,7 +55,7 @@ const SignupPage: React.FC<SignupPageProps> =({ switchCss, setSwitchCss,setError
else {
toast.success(`Successful, you can login now.`)
// ${session.data?.user?.name}
window.location.href = "/login"; // Redirect on success
window.location.href = "/auth/seller"; // Redirect on success
}

// Reset form fields after submission
Expand Down
2 changes: 1 addition & 1 deletion app/(Seller)/auth/seller/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const Login = () => {
} z-10 h-full`}
>
<div className="text-5xl font-handlee font-bold ">
{switchCss ? "Welcome Back!" : "Welcome!"}
{switchCss ? "Welcome Back Seller!" : "Welcome Seller!"}
</div>
<div className="mt-5 text-lg w-52">
EzyShop makes it easy to browse, order, and receive products from
Expand Down
16 changes: 16 additions & 0 deletions app/(Seller)/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"use client"
import { useSession } from "next-auth/react";

const Dashboard = () => {

const session= useSession();

return (
<>
{session.data?.user.role}
{session.data?.user.name}
</>
);
}

export default Dashboard;
35 changes: 35 additions & 0 deletions app/api/auth/signup/seller/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcrypt';

const prisma = new PrismaClient();

export async function POST(request: Request) {
const { email, password , mobileNumber,name } = await request.json();

// Check if the user already exists
const existingUser = await prisma.user.findUnique({
where: { email },
});

if (existingUser) {
return NextResponse.json({ message: 'Seller already exists' }, { status: 400 });
}

// Hash the password
const passwordHash = await bcrypt.hash(password, 10);

// Create the user
const user = await prisma.seller.create({
data: {
email,
passwordHash,
mobileNumber,
name
},
});



return NextResponse.json({ message: 'Signup successful!',user });
}
16 changes: 9 additions & 7 deletions components/Navbar/sellerNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import UnderConstructionAlert from "../modals/underConstruction";
import { SellerMainNav } from "./seller-main-nav";

const SellerNavbar = () => {

const { theme } = useTheme() || { theme: "light" }; // Get the current theme and toggle function

return (
Expand All @@ -30,17 +29,20 @@ const SellerNavbar = () => {
/>
</Link>
<Link href="/" className="ml-4 flex lg:ml:0 gap-x-2">
<p className="font-extrabold text-5xl font-nunito bg-customTeal dark:bg-gradient-to-r from-Green to-Yellow inline-block text-transparent bg-clip-text">
Ezyshop
</p>
<div className="flex flex-col items-start">
<p className="font-extrabold text-5xl font-nunito bg-customTeal dark:bg-gradient-to-r from-Green to-Yellow inline-block text-transparent bg-clip-text">
Ezyshop
</p>
<p className="font-extrabold text-xl tracking-widest font-nunito bg-customTeal dark:bg-gradient-to-r from-Green to-Yellow inline-block text-transparent bg-clip-text">
seller
</p>
</div>
</Link>
</div>
{/* all the navigation links */}
<SellerMainNav theme={theme}/>

<SellerMainNav theme={theme} />

<UnderConstructionAlert theme={theme} />

</div>
</div>
);
Expand Down
90 changes: 37 additions & 53 deletions lib/auth.ts
Original file line number Diff line number Diff line change
@@ -1,76 +1,60 @@
import { PrismaClient } from "@prisma/client";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcrypt";
import { NextAuthOptions } from "next-auth";

import { DefaultUser, Session } from "next-auth";
import { JWT } from "next-auth/jwt";
const prisma = new PrismaClient();


export const NEXT_AUTH_CONFIG = {
export const NEXT_AUTH_CONFIG: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "email", type: "text", placeholder: "" },
password: { label: "password", type: "password", placeholder: "" },
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials:Record<"email" | "password", string> | undefined) {

async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
throw new Error("Invalid credentials");
}

const prisma = new PrismaClient();
// console.log(credentials);
const user = await prisma.user.findUnique({
where: {
email: credentials.email,
},
});
if (!user || !user.passwordHash) {
// return NextResponse.json({msg:"invalid email, not found in DB"},{status:403})
console.log("invalid email, not found in DB");
return null; // Return null for invalid login
const user = await prisma.user.findUnique({ where: { email: credentials.email } });
const seller = await prisma.seller.findUnique({ where: { email: credentials.email } });

const account = user || seller;
if (!account || !account.passwordHash) {
return null;
}
const isVerified = await bcrypt.compare(
credentials.password,
user.passwordHash
);

const isVerified = await bcrypt.compare(credentials.password, account.passwordHash);
if (!isVerified) {
console.log("Invalid password");
return null; // Return null if password doesn't match
return null;
}
return {
id: user.id, // Ensure id is included
name: user.name,
email: user.email,

return {
id: account.id,
name: account.name,
email: account.email,
role: user ? "user" : "seller",
};
},
}),
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
jwt: async ({ user, token }:{user:DefaultUser,token:JWT}) => {
if (user) {
token.uid = user.id;
}
return token;
},
session: ({ session, token }:{session:Session,token:JWT}) => {
// if (session.user) {

// session.user.id = token.uid
// }
if (session.user) {

return { ...session,
user: { ...session.user,
id: token.uid,
}
}
}
return session
}
},
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
jwt: async ({ token, user }) => {
if (user) {
token.uid = user.id;
token.role = user.role; // Store role in JWT token
}
return token;
},
session: async ({ session, token }) => {
if (session.user) {
session.user.id = token.uid;
session.user.role = token.role; // Pass role to session
}
return session;
},
},
};
3 changes: 3 additions & 0 deletions tailwind.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ const config: Config = {
nunito: ['Nunito', 'sans-serif'],
},
},
letterSpacing: {
widest: '1.25em',
}
},
plugins: [require("tailwindcss-animate")],
};
Expand Down
20 changes: 18 additions & 2 deletions types/next-auth.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,25 @@
import type { DefaultSession } from "next-auth";
// next-auth.d.ts
import NextAuth, { DefaultUser, Session } from "next-auth";
import { JWT } from "next-auth/jwt";

declare module "next-auth" {
interface Session {
user: DefaultSession["user"] & {
user: {
id: string;
name?: string;
email?: string;
role: "user" | "seller"; // Extend with the role property
};
}

interface User extends DefaultUser {
role: "user" | "seller"; // Add role to User object
}
}

declare module "next-auth/jwt" {
interface JWT {
uid: string;
role: "user" | "seller"; // Add role to JWT token
}
}

0 comments on commit c892aae

Please sign in to comment.