Skip to content

Commit

Permalink
cookies not working in vercel, switched to localstorage
Browse files Browse the repository at this point in the history
  • Loading branch information
ShaunDaniel committed Mar 30, 2024
1 parent f4d8cec commit 7cb7486
Show file tree
Hide file tree
Showing 10 changed files with 33 additions and 53 deletions.
2 changes: 0 additions & 2 deletions backend/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ const rateLimit = require("express-rate-limit");
const dotenv = require('dotenv').config();
const session = require('express-session');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const passport = require('passport');
const useGoogleStrategy = require('./config/passport.config.js');
const useLocalStrategy = require('./config/passport.config.js');
Expand All @@ -24,7 +23,6 @@ mongoose.connect(process.env.MONGODB_URL, { useNewUrlParser: true, useUnifiedTop
}).catch((error) => {console.log(error)});


app.use(cookieParser());
const allowedOrigins = ['http://localhost:3000',"https://mycity-omega.vercel.app"];

app.use(cors({
Expand Down
23 changes: 0 additions & 23 deletions backend/src/middlewares/jwtAuth.js

This file was deleted.

9 changes: 1 addition & 8 deletions backend/src/routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,7 @@ authRouter.get('/google/callback',passport.authenticate('google', { failureRedir
process.env.JWT_SECRET,
{ expiresIn: "1h" },
);
res.cookie('jwtToken', token, {
domain: process.env.FRONTEND_URL,
secure: true,
sameSite: 'none',
httpOnly: true,
path: '/'
});
res.redirect(process.env.FRONTEND_URL);
res.redirect(`${process.env.FRONTEND_URL}?token=${token}`);
}
);

Expand Down
10 changes: 5 additions & 5 deletions backend/src/routes/userRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ const passport = require("passport");
const isAuthenticated = require("../middlewares/isAuthenticated");
const jwt = require('jsonwebtoken');
const router = express.Router();
const jwtAuth = require("../middlewares/jwtAuth");

router.get("/user-details", jwtAuth, (req, res) => {
router.post("/user-details", (req, res) => {
console.log("Inside user-details");
if (req.user) {
console.log(req.user);
res.json(req.user);
console.log(req.body);
if(req.body.jwtToken){
const decoded = jwt.verify(req.body.jwtToken, process.env.JWT_SECRET || '');
res.json(decoded);
} else {
res.status(404).json({ message: "User not found" });
}
Expand Down
12 changes: 9 additions & 3 deletions frontend/src/App.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import "./App.css";
import { ChakraProvider } from "@chakra-ui/react";
import { useEffect, useState } from "react";
import { Routes, Route } from 'react-router-dom';
import { Routes, Route} from 'react-router-dom';
import Login from "./components/Login";
import Navbar from "./components/Nav";
import Register from "./pages/Register";
Expand All @@ -14,17 +14,23 @@ import UserContext from './components/UserContext';

function App() {


const [user, setUser] = useState(null);

useEffect(() => {
userService.user_details()
const jwtToken = localStorage.getItem("jwtToken");
if (jwtToken) {
userService.user_details(jwtToken)
.then((res) => {
setUser(res.data.user);
})
.catch(() => {
setUser(null);
});
}, []);

} else {
setUser(null);
} }, []);


return (
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ function Login() {
if (res.status !== 401 && res.status !== 500) {
navigate('/');
window.location.reload();
document.cookie = `jwtToken=${res.data.token}; path=/;`; // set JWT token to a cookie
localStorage.setItem('jwtToken', res.data.token); // set JWT token to local storage
setIsLoading(false);
setIsFormError(false);
} else{
Expand Down
5 changes: 2 additions & 3 deletions frontend/src/components/Logout.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ function Logout() {


const handleLogout = () => {
// Clear the JWT token from the cookie
document.cookie = 'jwtToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
// Navigate to the home page and reload
// Clear the JWT token from the local storage
localStorage.removeItem('jwtToken');
navigate('/');
window.location.reload();
};
Expand Down
6 changes: 2 additions & 4 deletions frontend/src/pages/FinishRegister.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function FinishRegister(props) {
const [registerUser, setRegisterUser] = useState({});
const location = useLocation();

const [userFromRegister, setUserFromRegister] = useState(location.state ? location.state.user : {});
const [userFromRegister, setUserFromRegister] = useState(location.state ? location.state.user : null);


useEffect(() => {
Expand All @@ -28,14 +28,12 @@ function FinishRegister(props) {
}).catch((err) => {
console.log(err);
})
if (!registerUser.firstName && !registerUser.lastName && !registerUser.email && !registerUser.password) {


if (userFromRegister) {
setRegisterUser(userFromRegister);
} else if (user) {
setRegisterUser(user);
}
}
}, [user]);


Expand Down
13 changes: 11 additions & 2 deletions frontend/src/pages/Homepage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import HomepageFeatureTab from '../components/HomepageFeatureTab'
import { useNavigate } from 'react-router-dom';
import { useEffect,useContext } from 'react';
import UserContext from '../components/UserContext';
import userService from '../services/userService';


function Homepage() {
Expand All @@ -12,12 +11,22 @@ function Homepage() {
const {user,setUser} = useContext(UserContext);

useEffect(() => {

const urlParams = new URLSearchParams(window.location.search);

if (urlParams.has('token')) {
const token = urlParams.get('token');
localStorage.setItem('jwtToken', token);
navigate('/')
}
else {
if (user && user.city === '-') {
navigate('/register/2');
} else {
return;
}
});
}
}, [user]);


const handleGetStarted = () => {
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/services/userService.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ function logout() {
return api.get(`${API_URL}/logout`,{withCredentials:true});
}

function user_details() {
return api.get(`${API_URL}/user-details`,{withCredentials:true});
function user_details(jwtToken) {
return api.post(`${API_URL}/user-details`, { jwtToken });
}


Expand Down

0 comments on commit 7cb7486

Please sign in to comment.