Reputation: 45
I am trying to keep a currently user logged in on refresh via server-side authentication. I am using the UseEffect() function to do this in which I verify on refresh. My issue is that whenever I refresh, my server reads a user session on and off. Meaning that one refresh will read no session, while the other refresh will read a user session, and so on. I want my app.js to always read code to always read 'auth:true' assuming user is logged in.
Server-side:
index.js
app.use(express.json()); //Parsing Json
app.use(cors({ //Parsing origin of the front-end
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
credentials: true //Allows cookies to be enabled
}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
session({
key: "userID",
secret: "subscribe", //Normally this has to be long and complex for security
resave: false,
saveUninitialized: false,
cookie: { //How long will the cookie live for?
expires: 60 * 60 * 1000, //Expires after one hour
}
}));
app.post('/isUserAuth', (req, res) => { //Where we Authenticate session
const token = req.body.token;
jwt.verify(token, "jwtSecret", (err, decoded) => {
if (err) {
res.send({auth: false, user: "No valid token!"});
}
else if (!req.session.user) {
res.send({auth: false, user: "empty user"});
console.log(req.session.user)
}
else { //Else if user is verified, we send confirmed authentication and user data
res.send({auth: true, user: req.session.user});
console.log(req.session.user)
}
})
});
Client-side:
app.js
const userAuthToken = localStorage.getItem('token');
useEffect(() => { //Stay logged in, if user is logged in, after refresh
Axios.post("http://localhost:3001/isUserAuth", { //End-point for creation request
token: userAuthToken
}).then(response => {
if (!response.data.auth) { //checking for auth status
setAuthStatus(false); //User isnt logged in!
console.log("NOT LOGGED IN!");
console.log(response.data.user);
} else {
setAuthStatus(true); //User is logged into session!
console.log("LOGGED IN!");
console.log(response.data.user);
}
})
}
,[]);
Upvotes: 2
Views: 1103
Reputation: 189
The issue here is that you do not send credentiels from client via the Axios request. Since your server app has credentiels: true, you should do the same thing in the client.
My suggestion is to add {withCredentials: true} to your Hook in the client.
useEffect(() => {
const token = localStorage.getItem('token');
Axios.post("http://localhost:3001/isUserAuth", {
token: token,
},{withCredentials: true} /*<<Insert this*/).then(response => {
if (!response.data.auth) {
setAuthStatus(false);
console.log("NOT LOGGED IN!");
console.log(response.data.user);
} else {
setAuthStatus(true);
console.log("LOGGED IN!");
console.log(response.data.user);
}
})
}
,[]);
Upvotes: 1
Reputation: 2655
This is due to your userToken being undefined on reload. See this related question on pemanently getting token from local storage.
Upvotes: 0