From db5e2b9eb98af1ab003a82b6635f01a09cae1138 Mon Sep 17 00:00:00 2001 From: Ibidapo Ayomide Date: Tue, 12 Nov 2024 03:13:30 -0800 Subject: [PATCH] Login to vendor account added --- app/dashboard/components/Sidebar.tsx | 4 +- appwrite/user.actions.ts | 1 + appwrite/vendor.actions.ts | 15 ++- components/CustomInput.tsx | 2 +- components/forms/AccessDashboardForm.tsx | 132 ++++++++++++++++++----- components/forms/AccountInfoForm.tsx | 13 +-- components/forms/BecomeVendorForm.tsx | 3 +- middleware.ts | 23 ++-- 8 files changed, 124 insertions(+), 69 deletions(-) diff --git a/app/dashboard/components/Sidebar.tsx b/app/dashboard/components/Sidebar.tsx index ebac659..eedfa5a 100644 --- a/app/dashboard/components/Sidebar.tsx +++ b/app/dashboard/components/Sidebar.tsx @@ -12,7 +12,6 @@ import { } from "lucide-react" import Image from "next/image" import { Button } from "@/components/ui/button" -import { adminLogout } from "@/appwrite/user.actions" import { useRouter } from "next/navigation" const navLinks = [ @@ -60,8 +59,7 @@ export const SideBarLinks = () => { const router = useRouter() const handleLogoutAdmin = async () => { - await adminLogout() - router.push("/admin/access") + router.push("/logout") } return (
diff --git a/appwrite/user.actions.ts b/appwrite/user.actions.ts index f9e37ca..d5d5ea1 100644 --- a/appwrite/user.actions.ts +++ b/appwrite/user.actions.ts @@ -192,6 +192,7 @@ export const logout = async () => { try { await cookieStore.delete("session") await cookieStore.delete("userId") + await cookieStore.delete("adminPasskey") } catch (error) { console.log(error) } diff --git a/appwrite/vendor.actions.ts b/appwrite/vendor.actions.ts index 49b6b8e..f34c767 100644 --- a/appwrite/vendor.actions.ts +++ b/appwrite/vendor.actions.ts @@ -4,8 +4,6 @@ import { becomeVendorFormProps } from "@/types" import { cookies } from "next/headers" import { createSessionClient } from "./config" import { ID, Query } from "node-appwrite" -import { z } from "zod" -import { becomeVendorFormSchema } from "@/constants/validations" const { DATABASE_ID, VENDOR_ID } = process.env @@ -30,15 +28,15 @@ export const createVendorAccount = async (data: becomeVendorFormProps) => { await cookieStore.set("vendorId", result.$id) return result } catch (error) { - // @ts-ignore - if (error?.code === 409) { + // @ts-ignore + if (error?.code === 409) { // @ts-ignore - throw new Error(error.type) + throw new Error("User already exist in our database, please login to your dashboard") } } } -export const getVendor = async () => { +export const getVendor = async (email?: string) => { const cookieStore = await cookies() try { @@ -49,9 +47,10 @@ export const getVendor = async () => { const result = await databases.listDocuments( DATABASE_ID!, VENDOR_ID!, - [Query.equal("user", userId!)] + email ? [Query.equal("email", email!)] : [Query.equal("user", userId!)] ) - + + console.log(result) return result.documents } catch (error) { diff --git a/components/CustomInput.tsx b/components/CustomInput.tsx index 6472bb1..81a555f 100644 --- a/components/CustomInput.tsx +++ b/components/CustomInput.tsx @@ -109,7 +109,7 @@ const CustomInput = (props: CustomProps) => { control={control} name={name} render={({ field }) => ( - + {fieldType !== FormFieldTypes.CHECKBOX && label && ( {label} )} diff --git a/components/forms/AccessDashboardForm.tsx b/components/forms/AccessDashboardForm.tsx index f0f93c9..1bb62f9 100644 --- a/components/forms/AccessDashboardForm.tsx +++ b/components/forms/AccessDashboardForm.tsx @@ -1,6 +1,6 @@ "use client" import { zodResolver } from '@hookform/resolvers/zod' -import React from 'react' +import React, { useState } from 'react' import { useForm } from 'react-hook-form' import { z } from 'zod' import { Form } from '../ui/form' @@ -13,11 +13,18 @@ import { saveAdminPasskey } from '@/appwrite/user.actions' import { useRouter } from 'next/navigation' import Link from 'next/link' import { ArrowLeft } from 'lucide-react' +import { Button } from '../ui/button' +import { getVendor } from '@/appwrite/vendor.actions' const AccessDashboardSchema = z.object({ pin: z.string().min(6, { message: "Your dashboard access code must be 6 characters.", - }) + }), + + email: z.string().email({ + message: "Invalid email address" + }).optional(), + password: z.string().optional() }) const AccessDashboardForm = () => { @@ -25,48 +32,115 @@ const AccessDashboardForm = () => { const form = useForm>({ resolver: zodResolver(AccessDashboardSchema), defaultValues: { - pin: "" + pin: "", + email: "", + password: '' } }) + const [loginType, setLoginType] = useState("admin") + const [isLoading, setIsLoading] = useState(false) + const router = useRouter() - const onSubmit = (values: z.infer) => { + const onSubmit = async (values: z.infer) => { + console.log(loginType); + + + if (loginType === "admin") { + if (values.pin === process.env.NEXT_PUBLIC_ADMIN_PIN) { + const encryptedPin = encryptKey(values.pin) + saveAdminPasskey(encryptedPin) + router.push("/dashboard") + } else { + toast.error("Incorrect admin pin") + form.reset() + } + + return + } + + + if (loginType === "vendor") { + if (!values.email || !values.password) { + toast.warning("Email & password is required!") + console.log("Email not entered"); + + } else { + setIsLoading(true) + try { + const data = await getVendor(values.email) + console.log(data); - if (values.pin === process.env.NEXT_PUBLIC_ADMIN_PIN) { - const encryptedPin = encryptKey(values.pin) - saveAdminPasskey(encryptedPin) - router.push("/dashboard") - } else { - toast.error("Incorrect admin pin") - form.reset() + } catch (error) { + if (error instanceof Error) { + toast.error(error.message) + } + } finally { + setIsLoading(false) + } + } } + } return (
- ( - - - {Array.from({ length: 6 }, (_, i) => i).map((_, index) => ( - - ))} - - - )} - /> - - Access Dashboard + {loginType === "admin" && ( + <> + ( + + + {Array.from({ length: 6 }, (_, i) => i).map((_, index) => ( + + ))} + + + )} + /> + + Access Dashboard + + )} + + {loginType === "vendor" && ( + <> + + + + Access Dashboard + + )} - Go to home +
+ + +
) } diff --git a/components/forms/AccountInfoForm.tsx b/components/forms/AccountInfoForm.tsx index 887fd7a..baa5652 100644 --- a/components/forms/AccountInfoForm.tsx +++ b/components/forms/AccountInfoForm.tsx @@ -8,14 +8,11 @@ import { Form, FormControl } from '../ui/form' import CustomInput from '../CustomInput' import { FormFieldTypes } from '@/lib/utils' import SubmitButton from '../SubmitButton' -import { Button } from '../ui/button' -import { Edit2, LogOut } from 'lucide-react' import ProfileUploader from '@/app/dashboard/profile/components/ProfileUploader' -import { logout, updateUserInfo } from '@/appwrite/user.actions' +import { updateUserInfo } from '@/appwrite/user.actions' import { UserInfoParams } from '@/types' import { toast } from 'sonner' import { useRouter } from 'next/navigation' -import Link from 'next/link' const AccountInfoForm = ({ userInfo }: { userInfo?: UserInfoParams | undefined }) => { const form = useForm>({ @@ -31,9 +28,6 @@ const AccountInfoForm = ({ userInfo }: { userInfo?: UserInfoParams | undefined } const [isLoading, setIsLoading] = useState(false) - const router = useRouter() - - const onSubmit = async (values: z.infer) => { setIsLoading(true) try { @@ -66,10 +60,6 @@ const AccountInfoForm = ({ userInfo }: { userInfo?: UserInfoParams | undefined } } } - const handleLogout = async () => { - await logout() - router.push("/login") - } return ( @@ -125,7 +115,6 @@ const AccountInfoForm = ({ userInfo }: { userInfo?: UserInfoParams | undefined } />
- Logout
Save diff --git a/components/forms/BecomeVendorForm.tsx b/components/forms/BecomeVendorForm.tsx index 9c4a691..f90cbb6 100644 --- a/components/forms/BecomeVendorForm.tsx +++ b/components/forms/BecomeVendorForm.tsx @@ -45,7 +45,7 @@ const BecomeVendorForm = () => { ...values, password: encryptKey(values.password) } - const result = await createVendorAccount(values) + const result = await createVendorAccount(data) if(result?.$id){ router.push("/become-vendor/success") @@ -54,7 +54,6 @@ const BecomeVendorForm = () => { } catch (error) { if (error instanceof Error) { - console.log(error); toast.error(error.message) } } finally { diff --git a/middleware.ts b/middleware.ts index f220389..00d77d0 100644 --- a/middleware.ts +++ b/middleware.ts @@ -10,35 +10,30 @@ export async function middleware(request: NextRequest) { const isVendor = cookieStore.get("vendorId")?.value const isAdmin = decryptKey(cookieStore.get("adminPasskey")?.value!) === process.env.NEXT_PUBLIC_ADMIN_PIN - if (!user && request.url.includes("/")) { - return NextResponse.redirect(new URL("/login", request.url)) + if (!isVendor && !isAdmin && (request.url.includes("/dashboard"))) { + return NextResponse.redirect(new URL("/admin/access", request.url)) } - if (user && (request.url.includes("/login") || request.url.includes("/register"))) { - return NextResponse.redirect(new URL("/", request.url)) + if (!user) { + if (request.url.includes("/checkout") || request.url.includes("/dashboard") || request.url.includes("/accounts")) { + return NextResponse.redirect(new URL("/login", request.url)); + } } - if (!user && (request.url.includes("/accounts"))) { - return NextResponse.redirect(new URL("/login", request.url)) + if (user && (request.url.includes("/login") || request.url.includes("/register"))) { + return NextResponse.redirect(new URL("/", request.url)) } - if (!user && (request.url.includes("/dashboard"))) { - return NextResponse.redirect(new URL("/login", request.url)) - } if (isVendor && (request.url.includes("vendor"))) { return NextResponse.redirect(new URL("/accounts", request.url)) } - if (!user && (request.url.includes("/checkout"))) { - return NextResponse.redirect(new URL("/login", request.url)) - } - return NextResponse.next(); } export const config = { - matcher: ["/", "/cart", "/login", "/register", "/dashboard", "/accounts", "/checkout", "/become-vendor"] + matcher: ["/", "/cart", "/login", "/register", "/dashboard", "/accounts", "/checkout", "/become-vendor", "/dashboard/products/create", "/dashboard/products/manage"] } // const auth = {