Server logs:
Signing in
Signin successful 224152 0
Authenticating session…
No session established
I sign in, session exists in api/signin, i check session in Home.jsx and session is undefined calling api/auth
server.jsx:
const express = require('express');
const session = require('express-session');
const Sequelize = require('sequelize');
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const cors = require('cors');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
require('dotenv').config();
const app = express();
// CORS setup
const corsOptions = {
origin: 'http://localhost:3000',
methods: 'GET,PUT,POST,DELETE',
optionsSuccessStatus: 200,
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
};
app.use(cors(corsOptions));
// Body parser setup
app.use(bodyParser.json());
// Sequelize setup
const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASSWORD, {
host: process.env.DB_HOST,
dialect: 'mysql',
logging: false
});
// Employee model
const Employee = sequelize.define('Employee', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
field: 'id'
},
name: {
type: Sequelize.STRING,
field: 'name'
},
address: {
type: Sequelize.STRING,
field: 'address'
},
phoneNumber: {
type: Sequelize.STRING,
field: 'phonenumber'
},
email: {
type: Sequelize.STRING,
field: 'email'
},
dateStarted: {
type: Sequelize.DATEONLY,
field: 'datestarted'
},
password: {
type: Sequelize.STRING,
field: 'password'
},
access: {
type: Sequelize.INTEGER,
field: 'access'
}
}, {
tableName: 'employees',
timestamps: false
});
// Hook to hash password before saving
Employee.beforeCreate(async (employee) => {
if (employee.password) {
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(employee.password, saltRounds);
employee.password = hashedPassword;
}
});
// Session store setup
const store = new SequelizeStore({
db: sequelize
});
// Sync Sequelize and Session Store
sequelize.sync()
.then(() => store.sync())
.then(() => {
console.log('Sequelize and Session Store synced');
// Session setup
const sess = {
secret: process.env.SESSION_SECRET,
cookie: {
maxAge: 24 * 60 * 60 * 1000, // 1 day
secure: false, // Set to true if using HTTPS
httpOnly: true
},
resave: false,
saveUninitialized: true,
store: store
};
app.use(session(sess));
// Signin Route
app.post('/api/signin', async (req, res) => {
console.log("Signing in");
const { id, password } = req.body;
if (!id || !password) {
return res.status(400).json({ message: 'Employee number and password are required' });
}
try {
const employee = await Employee.findOne({
where: { id: id }
});
if (!employee) {
return res.status(401).json({ message: 'Invalid employee number or password' });
}
const match = await bcrypt.compare(password, employee.password);
if (!match) {
return res.status(401).json({ message: 'Invalid employee number or password' });
}
// Successfully signed in
const user = {
id: employee.id,
name: employee.name,
access: employee.access
};
// Save session variables
req.session.logged_in = true;
req.session.user = user;
// Log and respond with success message
console.log("Signin successful", user.id, user.access);
res.json({ message: 'Signin successful', user });
} catch (error) {
console.error('Error querying database:', error);
res.status(500).json({ message: 'An error occurred while signing in' });
}
});
// Authentication Check Route
app.get('/api/auth', (req, res) => {
console.log("Authenticating session...");
if (req.session.logged_in && req.session.user) {
console.log("Session established for " + req.session.user.id);
res.json({ isAuthenticated: true, access: req.session.user.access });
} else {
console.log("No session established");
res.json({ isAuthenticated: false });
}
});
// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
})
.catch(err => {
console.error('Error syncing Sequelize or Session Store:', err);
});
Home.jsx:
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
export default function Content() {
const [access, setAccess] = useState(100);
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
fetch('http://localhost:5000/api/auth', {
credentials: 'include'
})
.then(response => response.json())
.then(data => {
console.log("Signed in: "+data.isAuthenticated)
if (data.isAuthenticated) {
setAccess(data.access);
setIsAuthenticated(data.isAuthenticated);
}
})
.catch(error => console.error('Error checking authentication status:', error));
}, []);
return (
<div className="container mt-5">
<h1>Home</h1>
{isAuthenticated ? (
<div>
<p>Welcome! You are authenticated.</p>
<Link to="/add-entry">Add Time Entry</Link>
<Link to="/export-time">Export Time</Link>
<Link to="/edit-entry">Edit Entry</Link>
</div>
) : (
<div>
<p>Sign in to manage time entries</p>
<Link to="/signin">Sign In</Link>
</div>
)}
</div>
);
}
Signin.jsx:
import React, { useState } from 'react';
export default function Signin() {
const [id, setId] = useState('');
const [password, setPassword] = useState('');
const handleSignIn = async (e) => {
e.preventDefault();
console.log(`Signing in with Employee Number: ${id} and Password: ${password}`);
try {
const response = await fetch('http://localhost:5000/api/signin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id, password }),
});
if (response.ok) {
console.log('Sign in successful');
window.location.href = '/'
} else {
console.error('Sign in failed');
}
} catch (error) {
console.error('Error occurred during sign in:', error);
}
// Reset form fields
setId('');
setPassword('');
};
return (
<div>
<h1>Sign In</h1>
<form onSubmit={handleSignIn}>
<div>
<label>Employee Number:</label>
<input type="text" value={id} onChange={(e) => setId(e.target.value)} />
</div>
<div>
<label>Password:</label>
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
<button type="submit">Sign In</button>
</form>
</div>
);
}
My session is not saving properly. I set credentials to include in the fetch. I followed tutorial blogs on sessions online properly as far as I can tell. I do not even have any error logs for my server or client, I just see my session is good after api/signin and then undefined for api/auth in Home.jsx to determine what content to display the user.
It seems alot of these issues stem from secure not being set in cors and in the route call, but I fixed that and still have the issue.
Sorry if i included too much code, I just didnt want to miss anything I believe the issue lies in server.js just wanted to include the react incase I had an issue in the route call
HauntingRex9763 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.