Compare commits

..

2 Commits

Author SHA1 Message Date
Hossein Rahmani fc5c0a4f76 Merge branch 'Kahdooei' 2023-12-30 00:10:56 +03:30
Hossein Rahmani 3e99cf7732 Staff Authentication done + some Bugs fixed 2023-12-30 00:06:15 +03:30
14 changed files with 3336 additions and 209 deletions

View File

@ -1,15 +1,21 @@
import NavbarPanel from "@/components/NavbarPanel";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
// const cookieStore = cookies();
// const token = cookieStore.get("Sootzani-Token");
// if (!token.value) {
// return redirect("/");
// }
return (
<>
<NavbarPanel />
{children}
</>
)
);
}

View File

@ -1,9 +1,22 @@
"use client"
import React from "react";
import BoxDashboard from "./BoxDashboard";
import LineChart from "./LineChart";
import { HorizontalChart } from "./HorizontalChart";
import { getComplaintsList } from "@/utils/inspectorApi";
import { useQuery } from "@tanstack/react-query";
export default function ControllerDashboard() {
const {
data,
isLoading,
refetch,
} = useQuery({
queryKey: ["ComplaintsList"],
queryFn: () => getComplaintsList(),
refetchOnWindowFocus: false,
});
console.log(data);
return (
<div className="w-[95vw] lg:w-[82vw] xl:w-[70vw] 3xl:w-[65vw] mt-8 max-sm:mt-16 pt-9">
{/* Lg Show */}

View File

@ -24,21 +24,25 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import { loginStaff } from "@/utils/authenticateApi";
import { getCaptcha } from "@/utils/commonApi";
import { useRouter } from "next/navigation";
import { Oval, ThreeDots } from "react-loader-spinner";
import useData from "@/store/useData";
const FormSchema = z.object({
username: z.string().min(2, {
message: "Username must be at least 2 characters.",
username: z.string().min(1, {
message: "لطفا نام کاربری را وارد نمایید.",
}),
password: z.string().min(4, {
message: "Password must be at least 4 characters.",
}),
captcha: z.string().min(4, {
message: "Password must",
password: z
.string({ required_error: "لطفا رمز عبور را وارد نمایید." })
.min(1, {
message: "لطفا رمز عبور را وارد نمایید.",
}),
captcha: z
.string({ required_error: "لطفا کد امنیتی را وارد نمایید." })
.length(5, { message: "لطفا کد امنیتی را به طور کامل وارد نمایید." }),
});
export default function Login() {
const router = useRouter();
const saveData = useData((state) => state.saveData);
const {
data: CaptchaData,
@ -47,23 +51,15 @@ export default function Login() {
} = useQuery({
queryKey: ["Captcha"],
queryFn: () => getCaptcha(),
refetchOnWindowFocus: false,
});
console.log(CaptchaData);
const loginMutation = useMutation({
mutationFn: loginStaff,
onSuccess: (res) => {
console.log(res);
// localStorage.setItem("roles", res.roles[0]);
// setCookie("token", res.token);
// if (res.roles[0] == "Operator") {
// router.push("/MainPage/Prescriptions");
// } else {
// router.push("/MainPage");
// }
},
onSuccess: (res) => {},
onError: (err: any) => {
if (err.response.status == 428) {
console.log(useData);
router.push("/Verify");
}
},
@ -71,22 +67,9 @@ export default function Login() {
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
username: "",
password: "",
},
});
function onSubmit(data: z.infer<typeof FormSchema>) {
toast({
title: "You submitted the following values:",
description: (
<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4 pt-12">
<code className="text-white">{JSON.stringify(data, null, 2)}</code>
</pre>
),
});
console.log(CaptchaData?.headers["captcha-key"]);
const payload = {
username: data.username,
password: data.password,
@ -95,23 +78,23 @@ export default function Login() {
value: data.captcha,
},
};
console.log(payload);
loginMutation.mutate(payload);
saveData({
username: data.username,
password: data.password,
});
}
// if (data) {
// const base64ImageData = btoa(data);
// }
const srcForImage = CaptchaData
? URL.createObjectURL(CaptchaData.data)
: null;
// const base64ImageData = btoa(data.blob());
return (
<div
className="w-full mt-12 sm:w-2/3 md:w-2/4 xl:w-1/3 bg-white rounded-lg dark:border xl:p-0 dark:bg-gray-800 dark:border-gray-700 shadow-[0px_0px_15px_0px_#00000040]
h-full max-md:p-8 pt-12 mb-10"
>
<div className="space-y-3 md:space-y-4 flex flex-col md:py-12 md:px-20 h-full justify-center">
<div className="space-y-3 md:space-y-4 flex flex-col md:py-10 md:px-12 lg:px-16 h-full justify-center">
<Image alt="icon" src={LoginIcon} className="self-center w-1/3 " />
<p className="text-lg font-bold leading-tight tracking-tight text-blue dark:text-white">
@ -126,6 +109,7 @@ export default function Login() {
<FormField
control={form.control}
name="username"
rules={{ required: true }}
render={({ field }) => (
<FormItem>
<FormLabel className="text-[#7C838A] text-sm font-medium">
@ -149,13 +133,18 @@ export default function Login() {
<FormField
control={form.control}
name="password"
rules={{ required: true }}
render={({ field }) => (
<FormItem>
<FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
رمز عبور
</FormLabel>
<FormControl>
<Input placeholder="رمز عبور خود را وارد کنید" {...field} />
<Input
type="password"
placeholder="رمز عبور خود را وارد کنید"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
@ -165,8 +154,9 @@ export default function Login() {
<FormField
control={form.control}
name="captcha"
rules={{ required: true }}
render={({ field }) => (
<FormItem className=" flex-1 items-center h-10">
<FormItem className=" items-center h-10 flex-1">
{/* <FormLabel className="text-[#7C838A] text-sm font-medium mt-7">
رمز عبور
</FormLabel> */}
@ -177,23 +167,55 @@ export default function Login() {
</FormItem>
)}
/>
{!isLoading && (
{isLoading ? (
<div className=" w-36 flex justify-center text-center">
<ThreeDots
visible={true}
height="50"
width="50"
color="#003778"
radius="9"
ariaLabel="three-dots-loading"
wrapperStyle={{}}
wrapperClass=""
/>
</div>
) : (
<div className=" flex justify-center text-center">
<Image
alt="icon"
src={srcForImage as string}
className=" h-12 rounded-md shadow-md flex-1"
className=" h-12 rounded-md shadow-md w-36"
width={150}
height={20}
quality={100}
/>
</div>
)}
</div>
<div className="flex justify-end gap-2 w-full mt-14">
<Button
disabled={loginMutation.isPending}
type="submit"
className="bg-blue text-white w-1/2 md:w-1/3 p-2 rounded-xl"
className="bg-blue hover:bg-blue/90 transition text-white w-1/2 md:w-1/3 p-2 rounded-xl"
>
ورود
{loginMutation.isPending ? (
<div className="flex justify-center items-center gap-2">
<Oval
visible={true}
height="20"
width="20"
color="#fff"
ariaLabel="oval-loading"
wrapperStyle={{}}
wrapperClass=""
/>
{/* <p>در حال انجام ...</p> */}
</div>
) : (
"ورود"
)}
{/* ورود */}
</Button>
</div>
</form>

View File

@ -1,54 +1,75 @@
"use client";
import React from "react";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { AdminMenuItems, ControllerMenuItems } from "@/constants";
import { usePathname } from "next/navigation";
export default function NavbarPanel() {
const pathname = usePathname();
const [role, setRole] = useState<string | null>("");
useEffect(() => {
const userRole = localStorage.getItem("Sootzani_Role");
setRole(userRole);
}, []);
console.log(role);
const menus = {
Admin: AdminMenuItems,
Inspector: ControllerMenuItems,
};
const selectedMenu = menus[role as keyof typeof menus];
return (
<div className="fixed flex flex-col-reverse justify-between items-start gap-3
<div
className="fixed flex flex-col-reverse justify-between items-start gap-3
sm:flex-row sm:items-center sm:gap-0
w-full px-8 py-2 z-10 bg-blue max-md:px-4
">
"
>
<div className=" flex items-center gap-8 max-md:gap-4">
<p className="text-white inline-block bg-clip-text text-lg font-bold max-md:text-base max-md:font-medium">
پنل کاربری |
</p>
<div className="flex flex-row gap-7 max-md:gap-3">
{/* {ControllerMenuItems.map((item) => {
{role && (
<>
{selectedMenu.map(
(item: { id: number; name: string; href: string }) => {
return (
<Link key={item.id} href={item.href}>
<p className="text-white font-normal text-sm max-md:text-xs
<p
className="text-white font-normal text-sm max-md:text-xs
hover:bg-white/50 rounded-sm p-1
animate-out duration-300 ">{item.name}</p>
animate-out duration-300 "
>
{item.name}
</p>
</Link>
);
}
)}
</>
)}
{/* {AdminMenuItems.map((item) => {
return (
<Link key={item.id} href={item.href}>
<p
className="text-white font-normal text-sm max-md:text-xs
hover:bg-white/50 rounded-sm p-1
animate-out duration-300 "
>
{item.name}
</p>
</Link>
);
})} */}
{AdminMenuItems.map((item) => {
return (
<Link key={item.id} href={item.href}>
<p className="text-white font-normal text-sm max-md:text-xs
hover:bg-white/50 rounded-sm p-1
animate-out duration-300 ">{item.name}</p>
</Link>
);
})}
</div>
</div>
<h1 className="text-white inline-block bg-clip-text before:max-md:hidden text-sm font-bold max-md:text-xs max-md:font-medium">
نام و نام خانوادگی (بازرس)
</h1>
</div>
);
}

View File

@ -17,12 +17,14 @@ import {
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { IoMdClose } from "react-icons/io";
import { useMediaQuery } from "react-responsive";
export default function Search({ mode }: { mode: string }) {
// useEffect(() => {
// const isMobile = useMediaQuery({ query: "(max-width: 768px)" });
// }, []);
return (
<div>
{mode === "controller" || mode === "admin" || mode == "landing" ? (
{mode === "controller" || mode === "admin" ? (
<div className="relative flex bg-gray-300 rounded-xl items-center">
<Input
// type="search"
@ -49,6 +51,27 @@ export default function Search({ mode }: { mode: string }) {
</button>
</div>
) : (
<>
<div className=" max-md:hidden relative flex bg-gray-300 rounded-xl items-center">
<Input
// type="search"
id="default-search"
className={`mb-0 h-8 bg-[#D6D8DE66] border-none focus-visible:none rounded-lg
block w-full min-w-[13rem] lg:min-w-[16rem] text-xs text-black
text-opacity-60 dark:text-white
${mode === "controller" && "h-12 max-lg:min-w-[95vw]"}
${
mode === "admin" &&
"w-full min-w-full bg-white lg:min-w-full h-11"
}
`}
placeholder="جستجو..."
required
/>
<button className="absolute left-3">
<CiSearch />
</button>
</div>
<div className="md:hidden">
<AlertDialog>
<AlertDialogTrigger asChild>
@ -90,6 +113,7 @@ export default function Search({ mode }: { mode: string }) {
</AlertDialogContent>
</AlertDialog>
</div>
</>
)}
</div>
);

View File

@ -1,8 +1,54 @@
"use client";
import Image from "next/image";
import React from "react";
import React, { useEffect, useState } from "react";
import LoginIcon from "../public/img/login-icon.svg";
import OtpInput from "react-otp-input";
import { Button } from "./ui/button";
import { verifyStaff } from "@/utils/authenticateApi";
import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import useData from "@/store/useData";
import { JwtPayload, jwtDecode } from "jwt-decode";
import { setCookie } from "cookies-next";
import { Oval } from "react-loader-spinner";
export default function Verify() {
const [otp, setOtp] = useState("");
const space = "\xa0";
const router = useRouter();
const userData = useData((state) => state.data);
const verifyMutation = useMutation({
mutationFn: verifyStaff,
onSuccess: (res) => {
const decodedToken = jwtDecode<any>(res);
setCookie("Sootzani_Token", res);
const userRole =
decodedToken[
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
];
localStorage.setItem("Sootzani_Role", userRole);
if (userRole == "Inspector") {
router.push("/UserPanel/ControllerDashboard");
} else if (userRole == "Admin") {
router.push("/UserPanel/AdminDashboard");
} else {
router.push("/UserPanel/CitizenDashboard");
}
},
onError: (err: any) => {},
});
const handelVerify = () => {
console.log(otp);
const payload = { ...userData, verificationCode: otp };
verifyMutation.mutate(payload);
};
useEffect(() => {
useData.persist.rehydrate();
}, []);
return (
<div
className="w-full mt-12 sm:w-2/3 md:w-2/4 xl:w-1/3 bg-white rounded-lg dark:border xl:p-0 dark:bg-gray-800 dark:border-gray-700 shadow-[0px_0px_15px_0px_#00000040]
@ -10,11 +56,57 @@ export default function Verify() {
>
<div className="space-y-3 md:space-y-4 flex flex-col md:py-12 md:px-20 h-full justify-center">
<Image alt="icon" src={LoginIcon} className="self-center w-1/3 " />
<p className="text-lg font-bold leading-tight tracking-tight text-blue dark:text-white">
تایید کد
</p>
<div className="w-full " dir="ltr">
<OtpInput
value={otp}
onChange={setOtp}
numInputs={6}
renderSeparator={<span>{space}</span>}
renderInput={(props, idx) => (
<input
autoFocus={idx == 0}
inputmode="decimal"
pattern="[0-9]*"
{...props}
/>
)}
containerStyle=" flex justify-center"
inputStyle=" !w-10 rounded-md h-10 bg-[#F5F5F5] border border-blue/30 text-black"
/>
</div>
<label className="label text-center">
<span className="text-xs text-blue/70 label-text text-center">
کد دریافت شده توسط پیامک را وارد نمایید.
</span>
</label>
<div className="flex justify-end gap-2 w-full mt-14">
<Button
disabled={verifyMutation.isPending}
onClick={handelVerify}
type="submit"
className="bg-blue hover:bg-blue/90 text-white w-1/2 md:w-1/3 p-2 rounded-xl"
>
{verifyMutation.isPending ? (
<div className="flex justify-center items-center gap-2">
<Oval
visible={true}
height="20"
width="20"
color="#fff"
ariaLabel="oval-loading"
wrapperStyle={{}}
wrapperClass=""
/>
{/* <p>در حال انجام ...</p> */}
</div>
) : (
"تایید"
)}
</Button>
</div>
{/* <Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}

View File

@ -155,7 +155,7 @@ const FormMessage = React.forwardRef<
<p
ref={ref}
id={formMessageId}
className={cn("text-sm font-medium text-destructive", className)}
className={cn("text-xs font-medium text-destructive", className)}
{...props}
>
{body}

2894
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -28,10 +28,14 @@
"cookies-next": "^4.1.0",
"framer-motion": "^10.16.16",
"hamburger-react": "^2.5.0",
"i": "^0.3.7",
"jsencrypt": "^3.3.2",
"jwt-decode": "^4.0.0",
"leaflet": "^1.9.4",
"leaflet-geosearch": "^3.11.0",
"lucide-react": "^0.292.0",
"next": "14.0.3",
"npm": "^10.2.5",
"react": "^18.2.0",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18.2.0",
@ -40,11 +44,14 @@
"react-leaflet": "^4.2.1",
"react-loader-spinner": "^6.1.6",
"react-otp-input": "^3.1.1",
"react-responsive": "^9.0.2",
"react-spinners": "^0.13.8",
"react-use": "^17.4.2",
"swiper": "^11.0.5",
"tailwind-merge": "^2.1.0",
"tailwindcss-animate": "^1.0.7",
"zod": "^3.22.4"
"zod": "^3.22.4",
"zustand": "^4.4.7"
},
"devDependencies": {
"@faker-js/faker": "^8.3.1",

39
store/useData.ts Normal file
View File

@ -0,0 +1,39 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
type Store = {
data: any;
saveData: (data: any) => void;
};
// const useData = create<Store>()(persist((set: any) => ({
// data: "",
// saveData: (payload) => set((state: any) => ({ data: payload })),{
// name: 'auth',
// skipHydration: true,
// })
// }));
const useData = create<Store>()(
persist(
(set) => ({
data: "",
saveData: (payload) => {
set({ data:payload });
},
}),
{
name: 'auth',
skipHydration: true,
}
)
);
export default useData;
// function Counter() {
// const { count, inc } = useStore()
// return (
// <div>
// <span>{count}</span>
// <button onClick={inc}>one up</button>
// </div>
// )
// }

22
store/useToken.ts Normal file
View File

@ -0,0 +1,22 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
type Store = {
token: any;
saveToken: (data: any) => void;
};
const useToken = create<Store>()(
persist(
(set) => ({
token: "",
saveToken: (payload) => {
set({ token: payload });
},
}),
{
name: "auth",
skipHydration: true,
}
)
);
export default useToken;

View File

@ -0,0 +1,27 @@
import axios from "axios";
import { CookieValueTypes } from "cookies-next";
axios.defaults.baseURL = "https://sootzaniapi.shetabdahi.ir/";
export async function GenerateKeyPair() {
const data = await axios.get("api/Admin/GenerateKeyPair");
return data.data;
}
export async function GetKeys() {
const data = await axios.get("api/Admin/GetKeys");
return data.data;
}
export async function AddKey(payload: { title: string; publicKey: string }) {
const data = await axios.post("api/Admin/AddKey", payload);
return data.data;
}
export async function ChangeKey(payload: {
privateKey: string;
publicKeyId: string;
}) {
const data = await axios.post("api/Admin/ChangeKey", payload);
return data.data;
}

View File

@ -3,7 +3,7 @@ import { CookieValueTypes } from "cookies-next";
axios.defaults.baseURL = "https://sootzaniapi.shetabdahi.ir/";
export async function loginStaff(Data: {
export async function loginStaff(payload: {
username: string;
password: string;
captcha: {
@ -11,6 +11,62 @@ export async function loginStaff(Data: {
value: string;
};
}) {
const data = await axios.post("api/Authenticate/LoginStaff", Data);
const data = await axios.post("api/Authenticate/LoginStaff", payload);
return data.data;
}
export async function verifyStaff(payload: {
username: string;
password: string;
verificationCode: string;
}) {
const data = await axios.post("api/Authenticate/VerifyStaff", payload);
return data.data;
}
export async function logisterCitizen(payload: {
username: string;
password: string;
captcha: {
key: string;
value: string;
};
}) {
const data = await axios.post("api/Authenticate/LogisterCitizen", payload);
return data.data;
}
export async function verifyCitizen(payload: {
phoneNumber: string;
captcha: {
key: string;
value: string;
};
}) {
const data = await axios.post("api/Authenticate/VerifyCitizen", payload);
return data.data;
}
export async function changePassword(payload: {
oldPassword: string;
newPassword: string;
}) {
const data = await axios.put("api/Authenticate/ChangePassword", payload);
return data.data;
}
export async function getProfile() {
const data = await axios.get("api/Authenticate/Profile");
return data.data;
}
export async function editProfile(payload: {
firstName: string;
lastName: string;
nationalId: string;
phoneNumber2: string;
title: string;
}) {
const data = await axios.put("api/Authenticate/Profile", payload);
return data.data;
}

View File

@ -0,0 +1,32 @@
// "use client";
// import useToken from "@/store/useToken";
import axios from "axios";
import { CookieValueTypes, getCookie } from "cookies-next";
axios.defaults.baseURL = "https://sootzaniapi.shetabdahi.ir/";
axios.interceptors.request.use(function (config) {
const token = getCookie("Sootzani_Token");
config.headers.Authorization = token ? `Bearer ${token}` : "";
return config;
});
export async function getComplaintsList() {
const data = await axios.get(`api/Inspector/List`);
return data.data;
}
export async function getComplaint(payload: {
trackingNumber: string;
password: string;
}) {
const data = await axios.post(`api/Inspector/Get`, payload);
return data.data;
}
export async function OperateByInspector(payload: {
trackingNumber: string;
password: string;
}) {
const data = await axios.post(`api/Inspector/Operate`, payload);
return data.data;
}