Skip to content

Commit

Permalink
Merge branch 'Uo277382' of https://github.com/Arquisoft/wiq_es3a into…
Browse files Browse the repository at this point in the history
… Uo277382
  • Loading branch information
UO277382 committed Mar 18, 2024
2 parents 79ba807 + 98587b1 commit 6aa0550
Show file tree
Hide file tree
Showing 7 changed files with 149 additions and 18 deletions.
2 changes: 1 addition & 1 deletion webapp/package-lock.json

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

2 changes: 1 addition & 1 deletion webapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"react-responsive": "^9.0.2",
"react-router-dom": "^6.22.1",
"react-scripts": "5.0.1",
"react-toastify": "^8.0.2",
"react-toastify": "^8.2.0",
"web-vitals": "^3.5.1"
},
"scripts": {
Expand Down
22 changes: 7 additions & 15 deletions webapp/src/App.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,17 @@
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Navbar from "./components/Navbar";
import Home from "./components/Home";
import Inicio from './components/Inicio';
import Primera from './components/Primera';
import Game from './components/QuizGame';
import AuthProvider from './components/login/AuthProvider';
import Routes from './components/Routes';

function App() {

return (
<Router>
<Navbar />
<main className="main-content">
<Routes>
<Route index element={<Primera />} />
<Route path={process.env.RUTA_LOGIN || '/login'} element={<Inicio />} />
<Route path={process.env.RUTA_HOME || '/home'} element={<Home />} />
<Route path={process.env.RUTA_GAME || '/game'} element={<Game />} />
</Routes>
</main>
</Router>
<AuthProvider>
<Routes />
</AuthProvider>
</main>
);
}

Expand Down
16 changes: 16 additions & 0 deletions webapp/src/components/ProtectedRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Navigate, Outlet } from "react-router-dom";
import { useAuth } from "./login/AuthProvider";
import Navbar from "./Navbar";

export const ProtectedRoute = () => {
const { token } = useAuth();

// Check if the user is authenticated
if (!token) {
// If not authenticated, redirect to the login page
return <Navigate to="/login" />;
}

// If authenticated, render the child routes
return <div><Navbar></Navbar><Outlet /></div>;
};
64 changes: 64 additions & 0 deletions webapp/src/components/Routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { RouterProvider, createBrowserRouter } from "react-router-dom";
import { useAuth } from "./login/AuthProvider";
import { ProtectedRoute } from "./ProtectedRoute";
import Home from "./Home";
import Inicio from './Inicio';
import Primera from './Primera';
import Game from './QuizGame';
import Navbar from "./Navbar";

const Routes = () => {
const { token } = useAuth();

// Define public routes accessible to all users
const routesForPublic = [
{
path: "/",
element: <Primera />,
},
{
path: "/login",
element: <Inicio />,
},
];

// Define routes accessible only to authenticated users
const routesForAuthenticatedOnly = [
{
path: "/",
element: <ProtectedRoute />, // Wrap the component in ProtectedRoute
children: [
{
path: "/",
element: <Primera />,
},
{
path: "/game",
element: <Game />,
},
{
path: "/home",
element: <Home />,
},
],
},
];

// Define routes accessible only to non-authenticated users
const routesForNotAuthenticatedOnly = [

];

// Combine and conditionally include routes based on authentication status
const router = createBrowserRouter([
...routesForPublic,
...(!token ? routesForNotAuthenticatedOnly : []),
...routesForAuthenticatedOnly,
]);

// Provide the router configuration using RouterProvider
return <RouterProvider router={router}> </RouterProvider>
;
};

export default Routes;
44 changes: 44 additions & 0 deletions webapp/src/components/login/AuthProvider.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import axios from "axios";
import { createContext, useContext, useEffect, useMemo, useState } from "react";

const AuthContext = createContext();

const AuthProvider = ({ children }) => {
// State to hold the authentication token
const [token, setToken_] = useState(localStorage.getItem("token"));

// Function to set the authentication token
const setToken = (newToken) => {
setToken_(newToken);
};

useEffect(() => {
if (token) {
axios.defaults.headers.common["Authorization"] = "Bearer " + token;
localStorage.setItem('token',token);
} else {
delete axios.defaults.headers.common["Authorization"];
localStorage.removeItem('token')
}
}, [token]);

// Memoized value of the authentication context
const contextValue = useMemo(
() => ({
token,
setToken,
}),
[token]
);

// Provide the authentication context to the children components
return (
<AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
);
};

export const useAuth = () => {
return useContext(AuthContext);
};

export default AuthProvider;
17 changes: 16 additions & 1 deletion webapp/src/components/login/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import axios from 'axios';
import { Container, Typography, TextField, Button, Snackbar } from '@mui/material';
import './Login.css';
import logo from '../logo.png'
import { useAuth } from "./AuthProvider";


const Login = () => {
const [username, setUsername] = useState('');
Expand All @@ -15,11 +17,24 @@ const Login = () => {

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

const { setToken } = useAuth();


const loginUser = async () => {
try {
await axios.post(`${apiEndpoint}/login`, { username, password });

if(username.trim().length ===0 || password.trim().length===0)
{
setError("No se permite dejar espacios en blanco");
return;
}

let res= await axios.post(`${apiEndpoint}/login`, { username, password });


// Extract data from the response
setToken(res.data.token);
console.log(res);

setLoginSuccess(true);

Expand Down

0 comments on commit 6aa0550

Please sign in to comment.