Skip to content

Commit

Permalink
Fixing Issue of Cookies
Browse files Browse the repository at this point in the history
  • Loading branch information
JavidSumra committed Feb 3, 2024
1 parent 3970bf8 commit cea3c82
Show file tree
Hide file tree
Showing 8 changed files with 25 additions and 27 deletions.
5 changes: 2 additions & 3 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 0 additions & 2 deletions client/src/components/Admin/Users/Users.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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',
});
Expand Down
4 changes: 1 addition & 3 deletions client/src/components/Auth/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/Auth/Register.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
3 changes: 1 addition & 2 deletions middlewares/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
5 changes: 3 additions & 2 deletions middlewares/adminAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
30 changes: 16 additions & 14 deletions utils/sendToken.js
Original file line number Diff line number Diff line change
@@ -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);
}
};

0 comments on commit cea3c82

Please sign in to comment.