From cea3c820bc6b9813843b53b8f379c25b0923e6bd Mon Sep 17 00:00:00 2001 From: JavidSumra Date: Sat, 3 Feb 2024 12:58:39 +0530 Subject: [PATCH] Fixing Issue of Cookies --- app.js | 5 ++-- client/src/components/Admin/Users/Users.jsx | 2 -- client/src/components/Auth/Login.jsx | 4 +-- client/src/components/Auth/Register.jsx | 2 +- middlewares/Auth.js | 3 +-- middlewares/adminAuth.js | 5 ++-- package.json | 1 + utils/sendToken.js | 30 +++++++++++---------- 8 files changed, 25 insertions(+), 27 deletions(-) diff --git a/app.js b/app.js index 4f25a8e..f362e54 100644 --- a/app.js +++ b/app.js @@ -13,18 +13,17 @@ const app = express(); app.use( cors({ - origin: ["http://localhost:3000"], + origin: "http://localhost:3000", credentials: true, }) ); app.use(express.json()); - +app.use(cookieParser()); app.use( express.urlencoded({ extended: true, }) ); -app.use(cookieParser("This_Is_My_Super_Secret")); // app.use((req, res, next) => { // res.setHeader("Access-Control-Allow-Credentials", true); diff --git a/client/src/components/Admin/Users/Users.jsx b/client/src/components/Admin/Users/Users.jsx index 255df6c..90701a4 100644 --- a/client/src/components/Admin/Users/Users.jsx +++ b/client/src/components/Admin/Users/Users.jsx @@ -20,12 +20,10 @@ const Users = () => { const navigate = useNavigate(); const fetchUserData = async () => { - const token = localStorage.getItem('authToken'); const res = await fetch(`${API_ENDPOINT}/getAllUsers`, { method: 'GET', headers: { 'Content-Type': 'application/json', - Authorization: `Bearer ${token}`, }, credentials: 'include', }); diff --git a/client/src/components/Auth/Login.jsx b/client/src/components/Auth/Login.jsx index 47f1ee9..f648711 100644 --- a/client/src/components/Auth/Login.jsx +++ b/client/src/components/Auth/Login.jsx @@ -29,15 +29,13 @@ const Login = () => { headers: { 'Content-Type': 'application/json', }, + credentials: 'include', body: JSON.stringify({ email, password }), }); const data = await res.json(); - console.log(data); - if (data?.success) { - localStorage.setItem('authToken', data?.token); localStorage.setItem('isAuth', true, 3600000); localStorage.setItem( 'userData', diff --git a/client/src/components/Auth/Register.jsx b/client/src/components/Auth/Register.jsx index 0d240ce..71ccbdc 100644 --- a/client/src/components/Auth/Register.jsx +++ b/client/src/components/Auth/Register.jsx @@ -52,13 +52,13 @@ const Register = () => { headers: { 'Content-Type': 'application/json', }, + credentials: 'include', body: JSON.stringify({ email, name, password }), }); const data = await res.json(); if (data?.success) { - localStorage.setItem('authToken', data?.token); localStorage.setItem('isAuth', true, 3600000); localStorage.setItem( 'userData', diff --git a/middlewares/Auth.js b/middlewares/Auth.js index 3b9f339..f9c0d89 100644 --- a/middlewares/Auth.js +++ b/middlewares/Auth.js @@ -4,8 +4,7 @@ import ErrorHandler from "../utils/ErrorHandler.js"; import { User } from "../models/User.js"; export const isAuthenticated = catchAsyncError(async (req, res, next) => { - const token = - req.header("Authorization")?.replace("Bearer ", "") || req.cookies?.token; + const token = req.cookies?.authToken; if (!token) return next(new ErrorHandler("Not Logged in", 401)); const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = await User.findById(decoded._id); diff --git a/middlewares/adminAuth.js b/middlewares/adminAuth.js index 616cdd5..402b85a 100644 --- a/middlewares/adminAuth.js +++ b/middlewares/adminAuth.js @@ -4,8 +4,9 @@ import ErrorHandler from "../utils/ErrorHandler.js"; import { User } from "../models/User.js"; export const isAdminAuthenticated = catchAsyncError(async (req, res, next) => { - const token = - req.header("Authorization")?.replace("Bearer ", "") || req.cookies?.token; + const token = req.cookies?.authToken; + + console.log(req.cookies); if (!token) return next(new ErrorHandler("Not Logged in", 401)); const decoded = jwt.verify(token, process.env.JWT_SECRET); diff --git a/package.json b/package.json index 27c03e4..68e41e5 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,7 @@ "description": "", "type": "module", "main": "server.js", + "proxy":"http://localhost:4000", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon server.js" diff --git a/utils/sendToken.js b/utils/sendToken.js index 67a3629..9afc993 100644 --- a/utils/sendToken.js +++ b/utils/sendToken.js @@ -1,16 +1,18 @@ export const sendToken = (res, user, message, statusCode = 200) => { - const token = user.getJWTToken(); - const options = { - expires: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000), // 15 days token valid - httpOnly: true, - secure: true, - sameSite: true, - }; - - res.status(statusCode).cookie("token", token, options).json({ - success: true, - message, - user, - token, - }); + try { + const token = user.getJWTToken(); + const options = { + expires: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000), // 15 days token valid + httpOnly: true, + secure: true, + // sameSite: true, + }; + res.status(statusCode).cookie("authToken", token, options).json({ + success: true, + message, + user, + }); + } catch (error) { + console.log(error); + } };