Skip to content

Commit

Permalink
Login to vendor account added
Browse files Browse the repository at this point in the history
  • Loading branch information
Ibidapo-Ayo committed Nov 12, 2024
1 parent 0a39f29 commit db5e2b9
Show file tree
Hide file tree
Showing 8 changed files with 124 additions and 69 deletions.
4 changes: 1 addition & 3 deletions app/dashboard/components/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -60,8 +59,7 @@ export const SideBarLinks = () => {
const router = useRouter()

const handleLogoutAdmin = async () => {
await adminLogout()
router.push("/admin/access")
router.push("/logout")
}
return (
<div className="flex flex-col justify-between h-full">
Expand Down
1 change: 1 addition & 0 deletions appwrite/user.actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
15 changes: 7 additions & 8 deletions appwrite/vendor.actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 {
Expand All @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion components/CustomInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ const CustomInput = (props: CustomProps) => {
control={control}
name={name}
render={({ field }) => (
<FormItem className='flex-1'>
<FormItem className='flex-1 w-full'>
{fieldType !== FormFieldTypes.CHECKBOX && label && (
<FormLabel className='text-black text-xs tracking-tight font-semibold'>{label}</FormLabel>
)}
Expand Down
132 changes: 103 additions & 29 deletions components/forms/AccessDashboardForm.tsx
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -13,60 +13,134 @@ 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 = () => {

const form = useForm<z.infer<typeof AccessDashboardSchema>>({
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<typeof AccessDashboardSchema>) => {
const onSubmit = async (values: z.infer<typeof AccessDashboardSchema>) => {
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 (
<div>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className='w-full space-y-6 flex flex-col justify-center items-center'>
<CustomInput
control={form.control}
name='pin'
fieldType={FormFieldTypes.SKELETON}
label='Enter your access code'
renderSkeleton={(field) => (
<InputOTP maxLength={6} {...field}>
<InputOTPGroup>
{Array.from({ length: 6 }, (_, i) => i).map((_, index) => (
<InputOTPSlot key={index} className='h-20 w-20 text-2xl' index={index} />
))}
</InputOTPGroup>
</InputOTP>
)}
/>

<SubmitButton>Access Dashboard</SubmitButton>
{loginType === "admin" && (
<>
<CustomInput
control={form.control}
name='pin'
fieldType={FormFieldTypes.SKELETON}
label='Enter your access code'
renderSkeleton={(field) => (
<InputOTP maxLength={6} {...field}>
<InputOTPGroup>
{Array.from({ length: 6 }, (_, i) => i).map((_, index) => (
<InputOTPSlot key={index} className='h-20 w-20 text-2xl' index={index} />
))}
</InputOTPGroup>
</InputOTP>
)}
/>

<SubmitButton>Access Dashboard</SubmitButton>
</>
)}

{loginType === "vendor" && (
<>
<CustomInput
control={form.control}
name='email'
fieldType={FormFieldTypes.INPUT}
label='Enter your vendor email address'
/>
<CustomInput
control={form.control}
name='password'
fieldType={FormFieldTypes.INPUT}
label='Enter your password'
type='password'
/>

<SubmitButton isLoading={isLoading}>Access Dashboard</SubmitButton>
</>
)}
</form>

</Form>
<Link href={"/"} className='text-secondary-green-60 text-xs tracking-tight pt-10 flex items-center space-x-3'><ArrowLeft className='w-4' /> Go to home</Link>
<div className='flex items-center justify-between pt-10'>
<Link href={"/"} className='text-secondary-green-60 text-xs tracking-tight flex items-center space-x-3'><Button variant={"ghost"} className='bg-transparent hover:bg-transparent'><ArrowLeft className='w-4' /> Go to home</Button></Link>
<Button variant={"ghost"} className='hover:bg-transparent bg-transparent' onClick={() => {
if (loginType === "admin") {
setLoginType("vendor")
} else {
setLoginType("admin")
}
}}>{loginType === "admin" ? "Login as a vendor" : "Login as an admin"}</Button>
</div>
</div>
)
}
Expand Down
13 changes: 1 addition & 12 deletions components/forms/AccountInfoForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<z.infer<typeof accountInfoFormSchema>>({
Expand All @@ -31,9 +28,6 @@ const AccountInfoForm = ({ userInfo }: { userInfo?: UserInfoParams | undefined }

const [isLoading, setIsLoading] = useState(false)

const router = useRouter()


const onSubmit = async (values: z.infer<typeof accountInfoFormSchema>) => {
setIsLoading(true)
try {
Expand Down Expand Up @@ -66,10 +60,6 @@ const AccountInfoForm = ({ userInfo }: { userInfo?: UserInfoParams | undefined }
}
}

const handleLogout = async () => {
await logout()
router.push("/login")
}


return (
Expand Down Expand Up @@ -125,7 +115,6 @@ const AccountInfoForm = ({ userInfo }: { userInfo?: UserInfoParams | undefined }
/>

<div className='flex justify-between items-center'>
<Link className='text-red-500 hover:bg-transparent hover:text-red-500 text-sm space-x-2 flex items-center' href={"/logout"}><LogOut className='w-4' /> <span>Logout</span></Link>
<div className='w-full flex flex-col items-end justify-end'>
<div className='w-auto'>
<SubmitButton isLoading={isLoading}>Save</SubmitButton>
Expand Down
3 changes: 1 addition & 2 deletions components/forms/BecomeVendorForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -54,7 +54,6 @@ const BecomeVendorForm = () => {

} catch (error) {
if (error instanceof Error) {
console.log(error);
toast.error(error.message)
}
} finally {
Expand Down
23 changes: 9 additions & 14 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down

0 comments on commit db5e2b9

Please sign in to comment.