Skip to content

Commit

Permalink
protected routes issue solved
Browse files Browse the repository at this point in the history
  • Loading branch information
sinanptm committed Aug 31, 2024
1 parent 789bda2 commit 1298481
Show file tree
Hide file tree
Showing 10 changed files with 88 additions and 68 deletions.
16 changes: 10 additions & 6 deletions client/app/(patient)/signin/otp-verification/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,22 @@ import OtpVerificationSection from "@/components/forms/patient/OtpForms";
import { useQuery } from "@tanstack/react-query";
import { getPatientProfile } from "@/services/api/patientProtectedApis";
import UniversalSkelton from "@/components/skeletons/Universal";
import { useAuth } from "@/lib/hooks/useAuth";

const OtpVerificationPage = () => {
const [otp, setOtp] = useState<string>("");
const { mutate: validateOtp, isPending } = useValidateOtpPatient();
const { toast } = useToast();
const navigate = useRouter();
const { isError, isFetching } = useQuery({
queryKey: ["patientToken"],
queryFn: getPatientProfile,
});
const [isLoading,setLoading]= useState(true)

const {patientToken} = useAuth()

if (isFetching) {
setTimeout(()=>{
setLoading(false)
});

if (isLoading) {
<UniversalSkelton />;
}

Expand Down Expand Up @@ -57,7 +61,7 @@ const OtpVerificationPage = () => {

const handleResend = async () => {};

if (isError) {
if (!patientToken) {
return (
<div className="flex h-screen max-h-screen">
<section className="remove-scrollbar container my-auto">
Expand Down
20 changes: 17 additions & 3 deletions client/components/layout/NavBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,31 @@ import {
} from "@/components/ui/dropdown-menu";
import Image from "next/image";
import { NavLinks } from "@/constants";
import { usePathname } from "next/navigation";
import { usePathname, useRouter } from "next/navigation";
import { useAuth } from "@/lib/hooks/useAuth";
import { useLogoutMutation } from "@/lib/hooks/usePatientAuth";
import { toast } from "../ui/use-toast";

export const NavBar = () => {
const path = usePathname();
const { patientToken } = useAuth();
const { patientToken,adminToken,doctorToken } = useAuth();
const {mutate:logout} = useLogoutMutation();
const route = useRouter();

if (path.includes("signup") || path.includes("admin") || path.includes("signin")) {
return null;
}
const handleLogout = () => {
console.log("patient logout successfull");
logout(null,{
onSuccess:({message})=>{
toast({
title:"Logout Successful",
description:"Sorry for our inconvenience"
});
localStorage.setItem('auth',JSON.stringify({patientToken:"",adminToken,doctorToken}));
route.push('/');
}
})
};

return (
Expand Down
36 changes: 14 additions & 22 deletions client/components/patient/auth/SignInPageSection.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
'use client';
"use client";
import SigninForm from "@/components/forms/patient/SigninForm";
import Image from "next/image";
import Link from "next/link";
import { Banners } from "@/constants";
import { useQuery } from "@tanstack/react-query";
import { getPatientProfile } from "@/services/api/patientProtectedApis";
import { ErrorResponse, IPatient } from "@/types";
import { AxiosError } from "axios";
import { notFound } from "next/navigation";
import UniversalSkeleton from "@/components/skeletons/Universal";
import { useAuth } from "@/lib/hooks/useAuth";
import { useState } from "react";

const FromSection = () => {
const { isLoading, isError } = useQuery<IPatient, AxiosError<ErrorResponse>>({
queryKey: ['patientProfile'],
queryFn: getPatientProfile
const SignFromSection = () => {
const { patientToken } = useAuth();
let [isLoading, setLoading] = useState(true);

setTimeout(() => {
setLoading(false);
});

if (isLoading) {
return <UniversalSkeleton />;
}

if (isError) {
if (!patientToken) {
return (
<div className="flex h-screen max-h-screen">
<section className="remove-scrollbar container my-auto">
Expand All @@ -34,27 +34,19 @@ const FromSection = () => {
/>
<SigninForm />
<div className="text-14-regular py-12 flex justify-between">
<p className="justify-items-end text-dark-600 xl:text-left">
© 2024 AVM Ayurveda&apos;s
</p>
<p className="justify-items-end text-dark-600 xl:text-left">© 2024 AVM Ayurveda&apos;s</p>
<Link href={"/signup"} className="text-green-500 text-xs">
Staff-Login
</Link>
</div>
</div>
</section>
<Image
src={Banners.signin}
height={1000}
width={1000}
alt="patient"
className="side-img max-w-[50%]"
/>
<Image src={Banners.signin} height={1000} width={1000} alt="patient" className="side-img max-w-[50%]" />
</div>
);
}

notFound();
notFound();
};

export default FromSection;
export default SignFromSection;
20 changes: 11 additions & 9 deletions client/components/patient/auth/SignUnPageSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,24 @@
import Image from "next/image";
import SignupForm from "@/components/forms/patient/SignupForm";
import { Banners } from "@/constants";
import { useQuery } from "@tanstack/react-query";
import { getPatientProfile } from "@/services/api/patientProtectedApis";
import UniversalSkelton from "@/components/skeletons/Universal";
import UniversalSkeleton from "@/components/skeletons/Universal";
import { notFound } from "next/navigation";
import { useState } from "react";
import { useAuth } from "@/lib/hooks/useAuth";

const SignUnFormSection = () => {
const { isLoading, isError } = useQuery({
queryKey: ["patientProfile"],
queryFn: getPatientProfile,
});
const {patientToken} = useAuth();
let [isLoading,setLoading ] = useState(true)

setTimeout(()=>{
setLoading(false)
})

if (isLoading) {
return <UniversalSkelton />;
return <UniversalSkeleton />;
}

if (isError) {
if (!patientToken) {
return (
<div className="flex h-screen max-h-screen">
<section className="remove-scrollbar container">
Expand Down
12 changes: 11 additions & 1 deletion client/lib/hooks/usePatientAuth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { ErrorResponse, IPatient } from "@/types";
import { useMutation } from "@tanstack/react-query";
import { signInPatient, signUpPatient, validateOtpPatient } from "@/services/api/patientAuth";
import { signInPatient, signUpPatient, validateOtpPatient } from "@/services/api/patientAuthApis";
import { AxiosError } from "axios";
import { logoutPatient } from "@/services/api/patientProtectedApis";

export const useSignUpPatient = () => {
return useMutation<{ message: string }, AxiosError<ErrorResponse>, IPatient>({
Expand Down Expand Up @@ -33,3 +34,12 @@ export const useValidateOtpPatient = () => {
},
});
};

export const useLogoutMutation = ()=>{
return useMutation<{message:string},AxiosError<ErrorResponse>,null>({
mutationFn:logoutPatient,
onError:(error)=>{
console.log('Error in Logout',error);
}
})
}
2 changes: 1 addition & 1 deletion client/services/api/patientProtectedApis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,6 @@ export const getPatientProfile = async () => {
};

export const logoutPatient = async ()=>{
const response = await axiosInstance.post("/logout");
const response = await axiosInstance.post("/auth/logout");
return response.data;
}
12 changes: 6 additions & 6 deletions server/src/presentation/controllers/PatientController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export default class PatientController {

const { refreshToken, accessToken } = await this.loginPatientUseCase.validateOtp(otp, email);

res.cookie("patient_token", refreshToken, {
res.cookie("patientToken", refreshToken, {
httpOnly: true,
secure: true,
sameSite: "strict" as const,
Expand All @@ -83,9 +83,9 @@ export default class PatientController {
async refreshAccessToken(req: Request, res: Response, next: NextFunction) {
try {
const cookies = req.cookies;
if (!cookies?.patient_token) return res.status(403).json({ message: "Unauthenticated" });
if (!cookies?.patientToken) return res.status(403).json({ message: "Unauthenticated" });

const newAccessToken = await this.loginPatientUseCase.refreshAccessToken(cookies.patient_token);
const newAccessToken = await this.loginPatientUseCase.refreshAccessToken(cookies.patientToken);

return res.status(200).json(newAccessToken);
} catch (error: any) {
Expand All @@ -96,13 +96,13 @@ export default class PatientController {
logout(req: Request, res: Response, next: NextFunction) {
try {
const cookies = req.cookies;
if (!cookies?.patient_token) return res.sendStatus(204);
res.clearCookie("patient_token", {
if (!cookies?.patientToken) return res.sendStatus(204);
res.clearCookie("patientToken", {
httpOnly: true,
sameSite: "strict" as const,
secure: true,
});
res.json({ message: "cookie cleared" });
res.status(204).json({ message: "cookie cleared" });
} catch (error) {
next(error);
}
Expand Down
8 changes: 4 additions & 4 deletions server/src/presentation/routers/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import express from "express";
import patientAuthRoutes from "./patient/PatientAuthRoutes";
import AuthRoutes from "./patient/PatientAuthRoutes";
import ProtectedRoutes from "./patient/PatientProtectedRoutes";
import { errorHandler } from "../middlewares/errorHandler";
import patientRoutes from "./patient/patientRoutes";

const app = express();
app.use("/patient/auth", patientAuthRoutes);
app.use("/patient", patientRoutes);
app.use("/patient/auth", AuthRoutes);
app.use("/patient", ProtectedRoutes);
app.use(errorHandler);

export default app;
14 changes: 14 additions & 0 deletions server/src/presentation/routers/patient/PatientProtectedRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import express from "express";
import PatientAuthMiddleware from "../../middlewares/PatientAuthMiddleware";
import TokenService from "../../../infrastructure/services/TokenService";

const patientRoutes = express();

const tokenService = new TokenService();
const authenticatePatient = new PatientAuthMiddleware(tokenService);

patientRoutes.get("/profile", authenticatePatient.exec, (req, res, next) => {
res.status(200).json({ name: "sinan", age: 19, phone: 12312312312 });
});

export default patientRoutes;
16 changes: 0 additions & 16 deletions server/src/presentation/routers/patient/patientRoutes.ts

This file was deleted.

1 comment on commit 1298481

@vercel
Copy link

@vercel vercel bot commented on 1298481 Aug 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.