Login and authentication completed

master
Hossein Rahmani 2024-05-05 13:00:04 +03:30
parent 380439411e
commit cb5eb6d45c
16 changed files with 305 additions and 46 deletions

2
.env
View File

@ -0,0 +1,2 @@
NEXT_PUBLIC_BASE_URL_APP = "https://shahrbinapi.shetabdahi.ir/"
SECRET_KEY = "gfonmdkfjbglnskmfsngldfgnkjndfglglkdgnhjkgflks;dlghljkgjkn;lasknfkjsdfsdjfnnjksngk"

7
app/dashboard/layout.tsx Normal file
View File

@ -0,0 +1,7 @@
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return <div className=" w-full min-h-screen bg-gray-300">{children}</div>;
}

5
app/dashboard/page.tsx Normal file
View File

@ -0,0 +1,5 @@
import React from "react";
export default function page() {
return <div>page</div>;
}

View File

@ -3,6 +3,7 @@ import { Inter } from "next/font/google";
import "./globals.css";
import Provider from "../lib/ReactQuery/Provider";
import { Toaster } from "@/components/ui/sonner";
import ProgressBarProviders from "@/components/ProgressBar";
const inter = Inter({ subsets: ["latin"] });
@ -20,9 +21,10 @@ export default function RootLayout({
<html dir="rtl" lang="fa">
<body className="font-[yekan]">
<Provider>
<div className=" bg-[#F6C507] bg-blend-lighten min-w-screen w-screen min-h-screen flex justify-center items-center pb-20">
<ProgressBarProviders>
{children}
</div>
</ProgressBarProviders>
</Provider>
<Toaster richColors />
</body>

View File

@ -2,29 +2,26 @@ import Image from "next/image";
import React from "react";
import LoginForm from "./LoginForm";
import Link from "next/link";
import { cn } from "@/lib/utils";
export default function Login() {
return (
<div className="flex flex-col gap-2 w-2/3 max-w-[760px]">
<div className=" bg-[#F6C507] bg-blend-lighten min-w-screen w-full min-h-screen flex justify-center items-center pb-20">
<div className="flex flex-col gap-2 mx-5 w-full lg:w-3/4 max-w-[500px] lg:max-w-[760px]">
<Image
alt="ostandari"
quality={100}
width={80}
height={80}
className=" self-end"
className=" self-end max-lg:order-2 max-lg:self-center"
src="/images/province-logo.png"
/>
<LoginLogo className=" lg:hidden w-44 self-center -mb-7 z-10" />
<div className=" bg-white w-full flex flex-col p-8 rounded-lg relative min-h-72">
<Image
alt="ostandari"
quality={100}
width={300}
height={300}
className=" max-h-[300px] absolute -left-5 -bottom-8 object-cover"
src="/images/login-logo.png"
/>
<div className=" w-full max-w-[400px] border rounded-lg h-full p-4">
<LoginLogo className=" max-h-[300px] absolute -left-5 -bottom-8 object-cover max-lg:hidden" />
<div className=" w-full max-w-full lg:max-w-[400px] border rounded-lg h-full p-4">
<p className=" font-bold">ورود به پنل کاربری</p>
<LoginForm />
<Link href="/ForgotPassword">
@ -33,5 +30,19 @@ export default function Login() {
</div>
</div>
</div>
</div>
);
}
const LoginLogo = ({ className }: { className: string }) => {
return (
<Image
alt="logo"
quality={100}
width={300}
height={300}
className={cn("object-cover", className)}
src="/images/login-logo.png"
/>
);
};

View File

@ -16,18 +16,20 @@ import {
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Eye, EyeOff, Lock, RefreshCcw, Shield, UserRound } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { getCaptcha } from "@/lib/api/Authenticate";
import { useMutation, useQuery } from "@tanstack/react-query";
import { LoginStaff, getCaptcha } from "@/lib/api/Authenticate";
import { Oval, ThreeDots } from "react-loader-spinner";
import Image from "next/image";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { login } from "@/lib/authActions";
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(2, {
message: "Username must be at least 2 characters.",
password: z.string().min(1, {
message: "لطفا رمز عبور خود را وارد نمایید.",
}),
captcha: z
.string({ required_error: "لطفا کد امنیتی را وارد نمایید." })
@ -36,7 +38,9 @@ const FormSchema = z.object({
export default function LoginForm() {
const [showPassword, setShowPassword] = useState(false);
const router = useRouter();
//Queries
const {
data: CaptchaData,
isLoading,
@ -47,6 +51,20 @@ export default function LoginForm() {
refetchOnWindowFocus: false,
});
const loginMutation = useMutation({
mutationKey: ["loginStaff"],
mutationFn: LoginStaff,
onSuccess: (res) => {
console.log(res.data.authToken);
login(JSON.stringify(res.data.authToken), "");
// router.push("/Dashboard");
},
onError: (err) => {
refetch();
},
});
//
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
@ -56,13 +74,23 @@ export default function LoginForm() {
function onSubmit(data: z.infer<typeof FormSchema>) {
console.log("🚀 ~ onSubmit ~ data:", data);
console.log(CaptchaData);
loginMutation.mutate({
username: data.username,
password: data.password,
captcha: {
key: CaptchaData?.headers["captcha-key"],
value: data.captcha,
},
});
}
console.log(CaptchaData);
const srcForImage = CaptchaData ? URL.createObjectURL(CaptchaData) : null;
const srcForImage = CaptchaData
? URL.createObjectURL(CaptchaData.data)
: null;
return (
<div className="">
<div className=" w-full">
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
@ -77,7 +105,7 @@ export default function LoginForm() {
<FormControl>
<div className="w-full flex h-10 relative border rounded-lg">
<div className=" w-12 h-10 rounded-s-lg flex justify-center items-center">
<UserRound size={23} strokeWidth={1.25} />
<UserRound size={22} strokeWidth={1.25} />
</div>
<Input
placeholder="نام کاربری خود را وارد نمایید."
@ -100,7 +128,7 @@ export default function LoginForm() {
<FormControl>
<div className="w-full flex items-center h-10 relative border rounded-lg">
<div className=" w-12 h-10 rounded-s-lg flex justify-center items-center">
<Lock size={23} strokeWidth={1.25} />
<Lock size={22} strokeWidth={1.25} />
</div>
<Input
placeholder="رمز عبور خود را وارد نمایید."
@ -141,7 +169,7 @@ export default function LoginForm() {
<FormControl>
<div className="w-full flex h-10 relative border rounded-lg">
<div className=" w-12 h-10 rounded-s-lg flex justify-center items-center">
<Shield size={23} strokeWidth={1.25} />
<Shield size={22} strokeWidth={1.25} />
</div>
<Input
placeholder="کد امنیتی"
@ -156,7 +184,7 @@ export default function LoginForm() {
/>
{isLoading ? (
<div className="flex justify-between text-center w-1/2">
<div className="flex justify-center text-center w-1/2">
<ThreeDots
visible={true}
height="50"
@ -173,7 +201,7 @@ export default function LoginForm() {
<Image
alt="icon"
src={srcForImage as string}
className="h-10 rounded-md shadow-md flex-1"
className="h-10 rounded-md flex-1"
width={150}
height={20}
quality={100}
@ -181,7 +209,7 @@ export default function LoginForm() {
<RefreshCcw
className="cursor-pointer "
onClick={() => refetch()}
size={23}
size={20}
color="#003778"
/>
</div>

View File

@ -0,0 +1,19 @@
"use client";
import { AppProgressBar as ProgressBar } from "next-nprogress-bar";
const ProgressBarProviders = ({ children }: { children: React.ReactNode }) => {
return (
<>
{children}
<ProgressBar
height="4px"
color="#29D"
options={{ showSpinner: false }}
shallowRouting
/>
</>
);
};
export default ProgressBarProviders;

View File

@ -6,12 +6,12 @@ import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
const { theme = "light" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
className="toaster group font-[yekan]"
toastOptions={{
classNames: {
toast:

View File

@ -0,0 +1,15 @@
import { SessionData } from "@/types";
import { SessionOptions } from "iron-session";
export const defaultSession: SessionData = {
isLoggedIn: false,
};
export const sessionOptions: SessionOptions = {
password: process.env.SECRET_KEY!,
cookieName: "Shahrbin-Admin-Token",
cookieOptions: {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
},
};

View File

@ -4,6 +4,17 @@ export async function getCaptcha() {
const response = await api.get("api/Authenticate/Captcha", {
responseType: "blob",
});
return response.data;
return response;
}
export async function LoginStaff(payload: {
username: string;
password: string;
captcha: {
key: string;
value: string;
};
}) {
const response = await api.post("api/Authenticate/LoginStaff", payload);
return response.data;
}

View File

@ -1,7 +1,9 @@
import axios from "axios";
import { toast } from "sonner";
import { env } from "next-runtime-env";
const api = axios.create({ baseURL: "https://shahrbinapi.shetabdahi.ir/" });
const NEXT_PUBLIC_BASE_URL_APP = env("NEXT_PUBLIC_BASE_URL_APP");
const api = axios.create({ baseURL: process.env.NEXT_PUBLIC_BASE_URL_APP });
api.interceptors.response.use(
function (response) {

47
lib/authActions.ts Normal file
View File

@ -0,0 +1,47 @@
"use server";
import { JwtPayload, jwtDecode } from "jwt-decode";
import { SessionData } from "@/types";
import { cookies } from "next/headers";
import { defaultSession, sessionOptions } from "@/constants";
import { getIronSession } from "iron-session";
import { redirect } from "next/navigation";
import { hasRole } from "./utils";
export const getSession = async () => {
"use server";
const session = await getIronSession<SessionData>(cookies(), sessionOptions);
if (!session.isLoggedIn) {
session.isLoggedIn = defaultSession.isLoggedIn;
}
return session;
};
export const login = async (res: string, history: any) => {
"use server";
const data: { jwtToken: string; refreshToken: string } = JSON.parse(res);
const session = await getSession();
const decodedToken = jwtDecode<any>(data.jwtToken);
const cookieStore = cookies();
const roles =
decodedToken[
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
];
console.log(roles);
cookieStore.set("Shahrbin-Admin-Roles", JSON.stringify(roles));
session.jwtToken = data.jwtToken;
session.refreshToken = data.refreshToken;
await session.save();
const to = hasRole(["Mayor", "Manager", "Admin"], roles)
? "/dashboard/infos"
: hasRole(["ComplaintInspector"], roles)
? "/dashboard/complaints"
: hasRole(["ComplaintAdmin"], roles)
? "/dashboard/complaints-categories"
: "/dashboard/newReports";
redirect(to);
};

View File

@ -1,6 +1,12 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
return twMerge(clsx(inputs));
}
export const hasRole = (userRoles: string[], acceptedRoles = []) => {
const contains = userRoles.some((r) => acceptedRoles.indexOf(r) !== -1);
if (contains) return true;
else return false;
};

94
package-lock.json generated
View File

@ -16,8 +16,13 @@
"axios": "^1.6.8",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"cookies-next": "^4.1.1",
"iron-session": "^8.0.1",
"jwt-decode": "^4.0.0",
"lucide-react": "^0.376.0",
"next": "14.2.3",
"next-nprogress-bar": "^2.3.11",
"next-runtime-env": "^3.2.1",
"next-themes": "^0.3.0",
"react": "^18",
"react-dom": "^18",
@ -600,6 +605,11 @@
"react": "^18.0.0"
}
},
"node_modules/@types/cookie": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",
"integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA=="
},
"node_modules/@types/json5": {
"version": "0.0.29",
"resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz",
@ -1330,6 +1340,29 @@
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
"dev": true
},
"node_modules/cookie": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz",
"integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookies-next": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/cookies-next/-/cookies-next-4.1.1.tgz",
"integrity": "sha512-20QaN0iQSz87Os0BhNg9M71eM++gylT3N5szTlhq2rK6QvXn1FYGPB4eAgU4qFTunbQKhD35zfQ95ZWgzUy3Cg==",
"dependencies": {
"@types/cookie": "^0.6.0",
"@types/node": "^16.10.2",
"cookie": "^0.6.0"
}
},
"node_modules/cookies-next/node_modules/@types/node": {
"version": "16.18.96",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.96.tgz",
"integrity": "sha512-84iSqGXoO+Ha16j8pRZ/L90vDMKX04QTYMTfYeE1WrjWaZXuchBehGUZEpNgx7JnmlrIHdnABmpjrQjhCnNldQ=="
},
"node_modules/cross-spawn": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
@ -2688,6 +2721,28 @@
"node": ">= 0.4"
}
},
"node_modules/iron-session": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/iron-session/-/iron-session-8.0.1.tgz",
"integrity": "sha512-ZQKazQRn/J5YaXY+CQ69V9lx9boh4swl+BgnNC1knxyZgBjhiXuGpY60URRntMPib9QdrsN9qAOTqdMFMbGYXg==",
"funding": [
"https://github.com/sponsors/vvo",
"https://github.com/sponsors/brc-dd"
],
"dependencies": {
"cookie": "0.6.0",
"iron-webcrypto": "1.0.0",
"uncrypto": "0.1.3"
}
},
"node_modules/iron-webcrypto": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/iron-webcrypto/-/iron-webcrypto-1.0.0.tgz",
"integrity": "sha512-anOK1Mktt8U1Xi7fCM3RELTuYbnFikQY5VtrDj7kPgpejV7d43tWKhzgioO0zpkazLEL/j/iayRqnJhrGfqUsg==",
"funding": {
"url": "https://github.com/sponsors/brc-dd"
}
},
"node_modules/is-array-buffer": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz",
@ -3160,6 +3215,14 @@
"node": ">=4.0"
}
},
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"engines": {
"node": ">=18"
}
},
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@ -3417,6 +3480,27 @@
}
}
},
"node_modules/next-nprogress-bar": {
"version": "2.3.11",
"resolved": "https://registry.npmjs.org/next-nprogress-bar/-/next-nprogress-bar-2.3.11.tgz",
"integrity": "sha512-OjSvsQwgSWa2qBMYO478QreGG9Jt82tr4wTQptmiyzNqqjzHCyKZNkhANnzPrjuFAoelIvmruJuakODofSnvTQ==",
"dependencies": {
"nprogress": "^0.2.0"
}
},
"node_modules/next-runtime-env": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/next-runtime-env/-/next-runtime-env-3.2.1.tgz",
"integrity": "sha512-vyuTpUMwnGUA9GjOGXNnuosqFQOa52IcKmu4mnTaQi4EqeFoCy3aYUxSF6mLaKkQ5yNC8yLa/gFjny74czpc9Q==",
"dependencies": {
"next": "^14",
"react": "^18"
},
"peerDependencies": {
"next": "^14",
"react": "^18"
}
},
"node_modules/next-themes": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.3.0.tgz",
@ -3461,6 +3545,11 @@
"node": ">=0.10.0"
}
},
"node_modules/nprogress": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/nprogress/-/nprogress-0.2.0.tgz",
"integrity": "sha512-I19aIingLgR1fmhftnbWWO3dXc0hSxqHQHQb3H8m+K3TnEn/iSeTZZOyvKXWqQESMwuUVnatlCnZdLBZZt2VSA=="
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@ -4942,6 +5031,11 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/uncrypto": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/uncrypto/-/uncrypto-0.1.3.tgz",
"integrity": "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q=="
},
"node_modules/undici-types": {
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",

View File

@ -17,8 +17,13 @@
"axios": "^1.6.8",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"cookies-next": "^4.1.1",
"iron-session": "^8.0.1",
"jwt-decode": "^4.0.0",
"lucide-react": "^0.376.0",
"next": "14.2.3",
"next-nprogress-bar": "^2.3.11",
"next-runtime-env": "^3.2.1",
"next-themes": "^0.3.0",
"react": "^18",
"react-dom": "^18",

5
types/index.ts Normal file
View File

@ -0,0 +1,5 @@
export interface SessionData {
jwtToken?: string;
refreshToken?: string;
isLoggedIn?: boolean;
}