https://github.com/Naastyya/fitness-online2
I give a link to an open repository because the case is really problematic. To summarize, this is an application on react and express dedicated to physical exercises.
I will describe the problem in more detail:
I use sessions in my application for authentication, logging in and providing miscellaneous information. These are my settings regarding cors and session:
app.use(cors({ credentials: true, origin: [“http://localhost:5173”, “http://127.0.0.1:5173”] }));
app.use(express.json());
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
app.use('/images', express.static(path.join(__dirname, 'images')));
app.use(session({
secret: 'fweuonqijwehqfojimejnuwhe98fhcquijpqoejcpeuhquhwec',
resave: false,
saveUninitialized: true,
}));
I have an endpoint (backend/controllers/auth.js) that authorizes a user through one of the components (Login/login.jsx):
const loginUser = (e) => {
e.preventDefault();
const Axios = axios.create({
baseURL: "http://localhost:4444/",
withCredentials: true,
});
if (!loginEmail || !loginPassword) {
setLoginStatus('Please fill in all fields');
setStatusHolder('showMessage');
return;
}
Axios.post('http://localhost:4444/auth/login', {
email: loginEmail,
password: loginPassword
}).then(response => {
if (response.status === 200) {
navigateTo('/profilepage');
}
})
.catch(error => {
console.error('There was an error!', error);
});
}
router.post('/auth/login', async (req, res) => {
try {
const user = await User.findOne({email: req.body.email});
if (!user) {
return res.status(400).json({message: 'Користувача з таким email не знайдено'});
}
const isMatch = await bcrypt.compare(req.body.password, user.passwordHash);
if (!isMatch) {
return res.status(400).json({message: 'Неправильний пароль, спробуйте знову'});
}
req.session.user = user;
res.json(user);
} catch (err) {
console.log(err)
res.json(err);
}
});
As you can see after a successful login the user should get a session and be redirected to another component behind the navigateTo(‘/profilepage’) router.
And here a friend of mine has a problem: the component (Profilepage/profilepage.jsx) to which we are redirected immediately after login to the system has the following code to make a request and check if the user is authorized:
const Axios = axios.create({
baseURL: "http://localhost:4444/",
withCredentials: true,
});
useEffect(() => {
Axios.get('http://localhost:4444/checkAuth')
.then(response => {
if (response.status === 200) {
setMyVariable(true);
}
setIsLoading(false);
})
.catch(error => {
console.error('Помилка при запиті:', error);
setIsLoading(false);
});
}, []);
router.get('/checkAuth', async (req, res) => {
if (!req.session.user) {
return res.status(401).send('Неавторизований доступ: Ви повинні увійти до системи!');
}
res.send('Досвід успішно оновлено');
});
I seem to have everything working fine and I upload a user profile but my friend gets a 401 error sometimes I also observed that she has no sessions in the cookie store as if she didn’t have them saved after authentication.
Very urgently need help maybe someone knows the solution to this mystery?