Skip to content
This repository was archived by the owner on May 17, 2024. It is now read-only.

Commit def17b7

Browse files
Logout finally working, include credentials bug
1 parent 1e7be8e commit def17b7

File tree

4 files changed

+57
-43
lines changed

4 files changed

+57
-43
lines changed

dev/the-last-stand/src/client/components/LogoutButton.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ const LogoutButton = () => {
99
const formData = new FormData();
1010

1111
fetch(`${HOST_URL}:${HOST_PORT}/auth/logout`, {
12-
method: 'POST',
12+
method: 'DELETE',
1313
body: formData,
14+
credentials: 'include',
1415
})
1516
.then((res) => res.json())
1617
.then((res) => {

dev/the-last-stand/src/server/api/controllers/auth.ts

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ export const initializeGoogleOAuthStrategy = () => {
1717
clientSecret: GOOGLE_CLIENT_SECRET!,
1818
callbackURL: `${HOST_URL}:${HOST_PORT}/auth/google/callback`,
1919
passReqToCallback: true,
20-
prompt: 'consent',
2120
},
2221
async (req, accessToken, refreshToken, profile, done) => {
2322
try {
@@ -129,17 +128,17 @@ export const isAdmin = async (req: any, res: any, next: any) => {
129128
// }
130129
// };
131130

132-
// Logout user v3
133-
export const logoutUser = (req: any, res: any) => {
134-
try {
135-
res.clearCookie('connect.sid');
136-
res.cookie('connect.sid', '', { expires: new Date(0) });
137-
console.log('cookie should be cleared');
138-
return res.status(200).json({ message: 'Logged out' });
139-
} catch (err: any) {
140-
return res.status(500).json({ message: err });
141-
}
142-
};
131+
// // Logout user v3 DOING SHIT FUCKALL
132+
// export const logoutUser = (req: any, res: any) => {
133+
// try {
134+
// res.clearCookie('connect.sid');
135+
// res.cookie('connect.sid', '', { expires: new Date(0) });
136+
// console.log('cookie should be cleared');
137+
// return res.status(200).json({ message: 'Logged out' });
138+
// } catch (err: any) {
139+
// return res.status(500).json({ message: err });
140+
// }
141+
// };
143142

144143
// // Logout user v4
145144
// export const logoutUser = (req: any, res: any) => {
@@ -169,3 +168,13 @@ export const logoutUser = (req: any, res: any) => {
169168
// });
170169
// });
171170
// };
171+
172+
// Logout user v6
173+
export const logoutUser = (req: any, res: any) => {
174+
req.logout((err: any) => {
175+
if (err) {
176+
return res.status(500).json({ message: err });
177+
}
178+
return res.status(200).json({ message: 'Logged out' });
179+
});
180+
};

dev/the-last-stand/src/server/api/routes/auth.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,6 @@ authRouter.get(
1919

2020
authRouter.get('/check', checkAuth);
2121

22-
authRouter.post('/logout', logoutUser);
22+
authRouter.delete('/logout', logoutUser);
2323

2424
export default authRouter;

dev/the-last-stand/src/server/main.ts

Lines changed: 33 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import express from 'express';
66
import mongoose from 'mongoose';
77
import cors from 'cors';
88
import session from 'express-session';
9+
import { Session, SessionData } from 'express-session';
910
import MongoStore from 'connect-mongo';
1011
import passport from 'passport';
1112

@@ -26,6 +27,12 @@ import authRouter from './api/routes/auth';
2627
import usersRouter from './api/routes/users';
2728
import heroesRouter from './api/routes/heroes';
2829

30+
mongoose.set('strictQuery', false);
31+
dotenv.config();
32+
33+
const { APP_MODE, MONGO_URI, SESSION_SECRET, HOST_PORT } = process.env as Record<string, string>;
34+
35+
// Console eye candy
2936
console.log(' ___ _');
3037
console.log(' / __\\___ | |_ _ ___ ___ _ _ ___');
3138
console.log(' / / / _ \\| | | | / __|/ _ \\ | | / __|');
@@ -38,11 +45,6 @@ console.log('--------------------------------------------------');
3845
console.log('Starter file created by Andrzej Wisniowski. Find my other projects at https://github.com/cryptoblivious');
3946
console.log('--------------------------------------------------');
4047

41-
mongoose.set('strictQuery', false);
42-
dotenv.config();
43-
44-
const { APP_MODE, MONGO_URI, SESSION_SECRET, CLIENT_URL, CLIENT_PORT, HOST_PORT } = process.env as Record<string, string>;
45-
4648
// Options
4749

4850
// Load SSL certificates and private keys if in production mode
@@ -71,7 +73,8 @@ console.log('✅ Options set.');
7173
const mongoStore = new MongoStore({
7274
mongoUrl: MONGO_URI,
7375
collectionName: 'sessions',
74-
ttl: 60 * 15, // 15 minutes
76+
ttl: 60 * 15, // 15 minutes,
77+
touchAfter: 60 * 5, // 5 minutes
7578
});
7679
console.log('✅ Session store created.');
7780

@@ -96,18 +99,6 @@ if (APP_MODE === 'prod') {
9699
console.log('✅ Redirect to https enabled.');
97100
}
98101

99-
passport.serializeUser((user, done) => {
100-
done(null, user.id);
101-
});
102-
103-
passport.deserializeUser((id, done) => {
104-
User.findById(id, (err: any, user: boolean | Express.User | null | undefined) => {
105-
done(err, user);
106-
});
107-
});
108-
109-
initializeGoogleOAuthStrategy();
110-
111102
app.use((req: any, res: { header: (arg0: string, arg1: string) => void }, next: () => void) => {
112103
res.header('Access-Control-Allow-Credentials', 'true');
113104
next();
@@ -124,24 +115,37 @@ app.use(
124115
secure: APP_MODE === 'prod' ? true : false,
125116
sameSite: 'strict',
126117
},
118+
rolling: true,
127119
})
128120
);
129121

130-
// Add this code after the session middleware to log the session ID
131-
app.use((req, res, next) => {
132-
console.log('express-session ID:', req.sessionID); // Log the session ID generated by express-session
133-
mongoStore.get(req.sessionID, (err) => {
134-
if (err) {
135-
console.error('Failed to get session from MongoStore:', err);
136-
} else {
137-
console.log('mongo-connect ID:', req.session.id); // Log the session ID generated by mongo-connect
138-
}
139-
next();
122+
passport.serializeUser((user, done) => {
123+
done(null, user.id);
124+
});
125+
126+
passport.deserializeUser((id, done) => {
127+
User.findById(id, (err: any, user: boolean | Express.User | null | undefined) => {
128+
done(err, user);
140129
});
141130
});
142131

132+
initializeGoogleOAuthStrategy();
133+
134+
// Add middleware to update the session timestamp in order to keep the serverside session alive
135+
app.use(function (req, res, next) {
136+
interface ISession extends Session, SessionData {
137+
lastAccess: Date;
138+
}
139+
const reqSession: ISession = req.session as ISession;
140+
// Update the session timestamp
141+
reqSession.lastAccess = new Date();
142+
143+
// Call the next middleware function in the chain
144+
next();
145+
}); // REF : ChatGPT
146+
143147
app.use(passport.session());
144-
app.use(passport.authenticate('session'));
148+
//app.use(passport.authenticate('session'));
145149
console.log('✅ Middleware defined.');
146150

147151
// Hello World route

0 commit comments

Comments
 (0)