From 54298bb3a1597dd0b39810026e3571c2652debf1 Mon Sep 17 00:00:00 2001 From: angelalvaigle Date: Sun, 8 Dec 2024 15:26:12 +0100 Subject: [PATCH] logout --- gatewayservice/gateway-service.js | 12 +++++++ middleware/auth-middleware.js | 7 +--- users/authservice/auth-controller.js | 10 ++++-- users/authservice/auth-router.js | 4 +-- users/userservice/user-controller.js | 19 +++++++++++ webapp/src/pages/DashboardLayout.jsx | 48 ++++++++++++++++++++++++++-- webapp/src/pages/Landing.jsx | 2 +- webapp/src/pages/Login.jsx | 5 --- 8 files changed, 89 insertions(+), 18 deletions(-) diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index bc95175..1d107dc 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -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 diff --git a/middleware/auth-middleware.js b/middleware/auth-middleware.js index d0e6888..e82b9d4 100644 --- a/middleware/auth-middleware.js +++ b/middleware/auth-middleware.js @@ -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(); diff --git a/users/authservice/auth-controller.js b/users/authservice/auth-controller.js index c4d863f..a58b3fb 100644 --- a/users/authservice/auth-controller.js +++ b/users/authservice/auth-controller.js @@ -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']); @@ -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' }); + } +}; diff --git a/users/authservice/auth-router.js b/users/authservice/auth-router.js index d8eda74..93ae530 100644 --- a/users/authservice/auth-router.js +++ b/users/authservice/auth-router.js @@ -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; diff --git a/users/userservice/user-controller.js b/users/userservice/user-controller.js index 77ac38f..7c3e441 100644 --- a/users/userservice/user-controller.js +++ b/users/userservice/user-controller.js @@ -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 }); + } +}; diff --git a/webapp/src/pages/DashboardLayout.jsx b/webapp/src/pages/DashboardLayout.jsx index b8dd39e..c368c95 100644 --- a/webapp/src/pages/DashboardLayout.jsx +++ b/webapp/src/pages/DashboardLayout.jsx @@ -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); @@ -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 ( @@ -49,6 +79,20 @@ const DashboardLayout = () => { + + {error && ( + setError('')} + message={`Error: ${error}`} + /> + )} ); diff --git a/webapp/src/pages/Landing.jsx b/webapp/src/pages/Landing.jsx index 0e88f36..9e5b813 100644 --- a/webapp/src/pages/Landing.jsx +++ b/webapp/src/pages/Landing.jsx @@ -24,7 +24,7 @@ const Landing = () => { Register - Login / Demo User + Login wiq 7 diff --git a/webapp/src/pages/Login.jsx b/webapp/src/pages/Login.jsx index e2b4fd1..9b445bc 100644 --- a/webapp/src/pages/Login.jsx +++ b/webapp/src/pages/Login.jsx @@ -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`, @@ -65,9 +63,6 @@ const Login = () => { -

Not a member yet?