Skip to content

Commit

Permalink
Refactor authentication controller and routes
Browse files Browse the repository at this point in the history
- Updated localLogin and googleCallback functions in the authentication controller to remove unnecessary parameters and improve code readability.
- Modified the response messages for successful login via local and Google authentication.
- Added a new getStatus function to retrieve the user's status, including username and profile, if logged in.
- Implemented a resetPassword function that returns a "Not implemented" message.

Modified auth.routes.js:
- Reordered the routes and added new routes for getStatus and resetPassword.

Modified app.js:
- Removed unused login and protected routes.
- Removed the trust proxy setting.

Modified corsOptions.js:
- Updated the origin to use the FRONTEND_DOMAIN environment variable.
- Enabled credentials for CORS.

Modified sessionConfig.js:
- Updated the secure option based on the NODE_ENV environment variable.
  • Loading branch information
OomsOoms committed Sep 27, 2024
1 parent 1405378 commit ac1e7b6
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 30 deletions.
27 changes: 21 additions & 6 deletions server/src/api/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const passport = require('../../config/passport'); // Instead of directly importing services, we import the passport configuration which uses the services

function localLogin(req, res) {
return passport.authenticate('local', (err, user, info) => {
return passport.authenticate('local', (err, user) => {
if (!user) {
return res.status(401).json({ message: 'Invalid credentials' });
//return res.redirect('/login');
Expand All @@ -10,8 +10,8 @@ function localLogin(req, res) {
req.login(user, (err) => {
req.session.ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
req.session.userAgent = req.headers['user-agent'];
res.status(201).json({ message: 'Logged in successfully' });
// res.redirect('/dashboard');
return res.status(201).json({ message: 'Logged in successfully via local login' });
//return res.redirect(`${process.env.FRONTEND_DOMAIN}/`);
});
})(req, res);
}
Expand All @@ -21,19 +21,22 @@ function googleLogin(req, res) {
}

function googleCallback(req, res) {
return passport.authenticate('google', (err, user, info) => {
return passport.authenticate('google', (err, user) => {
if (!user) {
return res.status(401).json({ message: 'Invalid credentials' });
}
req.logIn(user, (err) => {
req.session.ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
req.session.userAgent = req.headers['user-agent'];
return res.status(200).json({ message: 'Logged in successfully' });
return res.status(200).json({ message: 'Logged in successfully via google' });
//return res.redirect(`${process.env.FRONTEND_DOMAIN}/`);
});
})(req, res);
}

function resetPassword(req, res) {}
function resetPassword(req, res) {
res.status(501).json({ message: 'Not implemented' });
}

function logout(req, res) {
if (!req.user) {
Expand All @@ -45,10 +48,22 @@ function logout(req, res) {
});
}

function getStatus(req, res) {
if (req.user) {
return res.status(200).json({
username: req.user.username,
profile: req.user.profile,
});
} else {
return res.status(401).json({ message: 'Not logged in' });
}
}

module.exports = {
localLogin,
googleLogin,
googleCallback,
logout,
resetPassword,
getStatus,
};
6 changes: 4 additions & 2 deletions server/src/api/routes/auth.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ const { authController: ac } = require('../controllers');
router
.get('/google', ac.googleLogin)
.get('/google/callback', ac.googleCallback)
.get('/logout', ac.logout)
.post('/login', ac.localLogin);
.post('/logout', ac.logout)
.post('/login', ac.localLogin)
.get('/status', ac.getStatus)
.post('/reset-password', ac.resetPassword);

module.exports = router;
18 changes: 0 additions & 18 deletions server/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ if (process.env.NODE_ENV === 'production') {
}
// Enable CORS for all routes
app.use(corsMiddleware);
app.set('trust proxy', 1);

// built-in middleware for json
app.use(express.json());
Expand All @@ -41,23 +40,6 @@ app.use(express.static('public'));
// routes
require('./api/routes')(app);

app.get('/login', (req, res) => {
res.send(`
<html>
<body>
<h1>Login</h1>
<a href="/api/auth/google">Authenticate with Google</a>
</body>
</html>
`);
});

app.get('/protected', (req, res) => {
if (!req.isAuthenticated()) return res.status(401).json({ message: 'Unauthorized' });
res.send(`Hello ${req.user.username}`);
});
// req.login() will login a user on signup

// error handling middleware
app.all('*', (req, res) => {
res.status(404).json({ message: '404 Route does not exist' });
Expand Down
4 changes: 2 additions & 2 deletions server/src/config/corsOptions.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const cors = require('cors');

const corsOptions = {
origin: ['https://localhost:3000', 'https://localhost:5500', 'https://s84dlvcl-8000.uks1.devtunnels.ms/'],
optionSuccessStatus: 200,
origin: process.env.FRONTEND_DOMAIN,
credentials: true,
};

module.exports = cors(corsOptions);
4 changes: 2 additions & 2 deletions server/src/config/sessionConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ module.exports = session({
mongoUrl: process.env.DATABASE_URI,
collectionName: 'sessions',
ttl: 14 * 24 * 60 * 60,
autoRemove: 'native',
autoRemove: 'native', //
stringify: false, // Set stringify option to false to store cookies as objects
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7,
secure: false,
secure: process.env.NODE_ENV === 'production', // Set secure to true if in production
},
});

0 comments on commit ac1e7b6

Please sign in to comment.