Skip to content

Commit

Permalink
logout
Browse files Browse the repository at this point in the history
  • Loading branch information
angelalvaigle committed Dec 8, 2024
1 parent 5cfc211 commit 54298bb
Show file tree
Hide file tree
Showing 8 changed files with 89 additions and 18 deletions.
12 changes: 12 additions & 0 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,18 @@ app.post('/login', async (req, res) => {
}
});

app.get('/logout', async (req, res) => {
try {
// Forward the login request to the authentication service
const authResponse = await axios.get(authServiceUrl + '/logout', req.body);
res.json(authResponse.data);
} catch (error) {
res
.status(error.response.status)
.json({ error: error.response.data.error });
}
});

app.post('/adduser', async (req, res) => {
try {
// Forward the add user request to the user service
Expand Down
7 changes: 1 addition & 6 deletions middleware/auth-middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,10 @@ import {
import { verifyJWT } from '../utils/tokenUtils.js';

export const authenticateUser = (req, res, next) => {
// const { token } = req.cookies;
console.log('auth middleware');
console.log(req.headers);
try {
const authHeader = req.headers.authorization;

console.log(req.headers.authorization);

const token = authHeader.split(' ')[1];

const { userId, role } = verifyJWT(token);
req.user = { userId, role };
next();
Expand Down
10 changes: 8 additions & 2 deletions users/authservice/auth-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ function validateRequiredFields(req, requiredFields) {
}

export const loginController = async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); // Origen permitido
res.setHeader('Access-Control-Allow-Credentials', 'true'); // Permite credenciales
try {
// Check if required fields are present in the request body
validateRequiredFields(req, ['username', 'password']);
Expand All @@ -38,3 +36,11 @@ export const loginController = async (req, res) => {
res.status(500).json({ error: 'Internal Server Error' });
}
};

export const logoutController = async (req, res) => {
try {
res.status(StatusCodes.OK).json({ msg: 'user logged out' });
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
}
};
4 changes: 2 additions & 2 deletions users/authservice/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// auth-router.js
import express from 'express';
import { loginController } from './auth-controller.js';
import { loginController, logoutController } from './auth-controller.js';

const authRouter = express.Router();

// Define la ruta para el login y asocia el controlador
authRouter.post('/login', loginController);

authRouter.get('/logout', logoutController);
export default authRouter;
19 changes: 19 additions & 0 deletions users/userservice/user-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,22 @@ export const getUsersController = async (req, res) => {
res.status(500).json({ error: error.message });
}
};

export const getCurrentUserController = async (req, res) => {
try {
const user = await User.findOne({ _id: req.user.userId }); // Fetch current user
const userWithoutPassword = user.toJSON;
res.json(userWithoutPassword);
} catch (error) {
res.status(500).json({ error: error.message });
}
};

export const updateUserController = async (req, res) => {
try {
const users = await User.find(); // Fetch all users, only return username field for security
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
};
48 changes: 46 additions & 2 deletions webapp/src/pages/DashboardLayout.jsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
import { Outlet } from 'react-router-dom';
import { Outlet, useNavigate } from 'react-router-dom';
import Wrapper from '../assets/wrappers/Dashboard';
import { SmallSidebar, BigSidebar, Navbar } from '../components';
import { createContext, useContext, useState } from 'react';
import { checkDefaultTheme } from '../App';
import axios from 'axios';
import { Snackbar } from '@mui/material';

const apiEndpoint =
process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

const DashboardContext = createContext();

const DashboardLayout = () => {
// temp
const user = { name: 'user' };
const [error, setError] = useState('');
const [openSnackbar, setOpenSnackbar] = useState(false);
const [showSidebar, setShowSidebar] = useState(false);
const [isDarkTheme, setIsDarkTheme] = useState(checkDefaultTheme());

const navigate = useNavigate();

const toggleDarkTheme = () => {
const newDarkTheme = !isDarkTheme;
setIsDarkTheme(newDarkTheme);
Expand All @@ -24,7 +33,28 @@ const DashboardLayout = () => {
};

const logoutUser = async () => {
console.log('logout user');
try {
const token = localStorage.getItem('token');
await axios.get(`${apiEndpoint}/logout`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
console.log('token');
localStorage.removeItem('token');
console.log('token');
setOpenSnackbar(true);
// Añadir un retardo antes de navegar
setTimeout(() => {
navigate('/login');
}, 1000); // 1000 ms = 1 segundos
} catch (error) {
setError(error.response.data.error);
}
};

const handleCloseSnackbar = () => {
setOpenSnackbar(false);
};

return (
Expand All @@ -49,6 +79,20 @@ const DashboardLayout = () => {
</div>
</div>
</main>
<Snackbar
open={openSnackbar}
autoHideDuration={6000}
onClose={handleCloseSnackbar}
message="Logout successful"
/>
{error && (
<Snackbar
open={!!error}
autoHideDuration={6000}
onClose={() => setError('')}
message={`Error: ${error}`}
/>
)}
</Wrapper>
</DashboardContext.Provider>
);
Expand Down
2 changes: 1 addition & 1 deletion webapp/src/pages/Landing.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const Landing = () => {
Register
</Link>
<Link to="/login" className="btn">
Login / Demo User
Login
</Link>
</div>
<img src={main} alt="wiq 7" className="img main-img" />
Expand Down
5 changes: 0 additions & 5 deletions webapp/src/pages/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ const Login = () => {
process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

const login = async () => {
console.log('login frontend');

try {
const response = await axios.post(
`${apiEndpoint}/login`,
Expand Down Expand Up @@ -65,9 +63,6 @@ const Login = () => {
<button type="button" className="btn btn-block" onClick={login}>
submit
</button>
<button type="button" className="btn btn-block">
explore the app
</button>
<p>
Not a member yet?
<Link to="/register" className="member-btn">
Expand Down

0 comments on commit 54298bb

Please sign in to comment.