Skip to content

Commit

Permalink
Sesión se mantiene entre diferentes ventanas
Browse files Browse the repository at this point in the history
  • Loading branch information
UO277938 committed Mar 21, 2024
1 parent 1d1bc3b commit e28208a
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 29 deletions.
1 change: 0 additions & 1 deletion userservice/authservice/auth-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ app.post('/login', async (req, res) => {
validateRequiredFields(req, ['username', 'password']);

const { username, password } = req.body;
console.log("LLEGA")
// Find the user by username in the database
const user = await User.findOne({ username });
// Check if the user exists and verify the password
Expand Down
1 change: 1 addition & 0 deletions webapp/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 22 additions & 13 deletions webapp/src/App.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import AddUser from './components/AddUser';
import Layout from './components/Pages/Layout';
Expand All @@ -11,6 +11,13 @@ import NotFound from './components/Pages/NotFound';
function App() {
const [isLogged, setIsLogged] = useState(false);

useEffect(() => {
const storedIsLogged = localStorage.getItem('isLogged');
if (storedIsLogged) {
setIsLogged(JSON.parse(storedIsLogged));
}
}, []);

//Si intenta acceder a una ruta privada (en este caso Estadistica) se le redirigira al login
function PrivateRoute({ element, ...props }) {
return isLogged ? element : <Navigate to="/login" />;
Expand All @@ -20,19 +27,21 @@ function PrivateRoute({ element, ...props }) {
<>
<Layout/>
<Router>
<Routes>
<Route path="/" element={<Home isLogged={isLogged}/>}></Route>
<Route path="/game" element={<Juego isLogged={isLogged}/>} />
<Route path="/login" element={<Login isLogged={isLogged}/>} />
<Route path="*" element={<NotFound />} />
<Route path="/register" element={<AddUser isLogged={isLogged}/>}/>

<Route
path="/stats"
element={<PrivateRoute element={<Estadisticas />} />}
/>
<Routes>
<Route path="/" element={<Home isLogged={isLogged}/>}></Route>
<Route path="/game"
element={<PrivateRoute element={<Juego isLogged={isLogged} />} />}
/>
<Route path="/login" element={<Login isLogged={isLogged} setIsLogged={setIsLogged} />} />
<Route path="*" element={<NotFound />} />
<Route path="/register" element={<AddUser isLogged={isLogged}/>}/>

<Route
path="/stats"
element={<PrivateRoute element={<Estadisticas />} />}
/>

</Routes>
</Routes>
</Router>
</>
);
Expand Down
4 changes: 3 additions & 1 deletion webapp/src/components/AddUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import { Container, Typography, TextField, Button, Snackbar } from '@mui/materia

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

const AddUser = () => {
const AddUser = ({isLogged}) => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [openSnackbar, setOpenSnackbar] = useState(false);

console.log("ADDUSER: " + isLogged)

const addUser = async () => {
try {
await axios.post(`${apiEndpoint}/adduser`, { username, password });
Expand Down
16 changes: 7 additions & 9 deletions webapp/src/components/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,24 @@ import React, { useState } from 'react';
import axios from 'axios';
import { Container, Typography, TextField, Button, Snackbar } from '@mui/material';

const Login = (isLogged) => {
const Login = ({isLogged, setIsLogged}) => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loginSuccess, setLoginSuccess] = useState(false);
const [createdAt, setCreatedAt] = useState('');
const [openSnackbar, setOpenSnackbar] = useState(false);

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

console.log("LOGIN: " + isLogged)
const loginUser = async () => {
try {
const response = await axios.post(`${apiEndpoint}/login`, { username, password });

// Extract data from the response
const { createdAt: userCreatedAt } = response.data;
const datos = response.data;

setCreatedAt(userCreatedAt);
setLoginSuccess(true);

setCreatedAt(datos.createdAt);
setIsLogged(true);
localStorage.setItem('isLogged', JSON.stringify(true));
setOpenSnackbar(true);
} catch (error) {
setError(error.response.data.error);
Expand All @@ -35,7 +33,7 @@ const Login = (isLogged) => {

return (
<Container component="main" maxWidth="xs" sx={{ marginTop: 4 }}>
{loginSuccess ? (
{isLogged ? (
<div>
<Typography component="h1" variant="h5" sx={{ textAlign: 'center' }}>
Hello {username}!
Expand Down
21 changes: 17 additions & 4 deletions webapp/src/components/Pages/Home.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import { Container, Button } from '@mui/material';
import { useNavigate } from 'react-router-dom';

// Definimos el componente Home
const Home = (isLogged) => {
const Home = ({isLogged, setIsLogged}) => {
// Utilizamos el hook useNavigate para la navegación
const navigate = useNavigate();
console.log("HOME: " + isLogged)

// Definimos la función que se ejecutará al hacer clic en el botón "Jugar"
const clickJugar = () => {
Expand All @@ -21,19 +22,31 @@ const Home = (isLogged) => {
navigate("/stats");
}

// Definimos la función que se ejecutará al hacer clic en el botón "Estadísticas"
const clickIniciar = () => {
// Navegamos a la ruta "/login"
navigate("/login");
}

// Definimos la función que se ejecutará al hacer clic en el botón "Estadísticas"
const clickRegistro = () => {
// Navegamos a la ruta "/register"
navigate("/register");
}

// Renderizamos el componente
return (
<>
{isLogged ? (
{!isLogged ? (
<Container component="main" maxWidth="xs" sx={{ marginTop: 4, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
{/* Mostramos el título del juego */}
<h1 className="titulo">WIQ 5A</h1>
{/* Creamos un contenedor para los botones */}
<div className="button-container">
{/* Creamos el botón "Jugar" y le asignamos la función clickJugar al evento onClick */}
<Button variant="contained" color="primary" className="button" id="btJugar" onClick={clickJugar}>INICIA SESIÓN</Button>
<Button variant="contained" color="primary" className="button" id="btJugar" onClick={clickIniciar}>INICIA SESIÓN</Button>
{/* Creamos el botón "Estadísticas" y le asignamos la función clickEstadisticas al evento onClick */}
<Button variant="contained" color="secondary" className="button" id="btEstadisticas" onClick={clickEstadisticas}>REGÍSTRATE</Button>
<Button variant="contained" color="secondary" className="button" id="btEstadisticas" onClick={clickRegistro}>REGÍSTRATE</Button>
</div>
</Container>) : (
<Container component="main" maxWidth="xs" sx={{ marginTop: 4, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
Expand Down
2 changes: 1 addition & 1 deletion webapp/src/components/Pages/Layout.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Outlet, Link } from "react-router-dom";
import {Container, Nav, Navbar, NavDropdown} from 'react-bootstrap';

const Layout = () => {
const Layout = (isLogged) => {
return (
<>
<Navbar collapseOnSelect expand="lg" className="bg-body-tertiary">
Expand Down

0 comments on commit e28208a

Please sign in to comment.