Skip to content

Commit

Permalink
Merge pull request #79 from Arquisoft/tokenAuth
Browse files Browse the repository at this point in the history
Token auth
  • Loading branch information
marcosMachadoMenendez authored Mar 18, 2024
2 parents 8720f3e + ab40e0b commit 0822e5c
Show file tree
Hide file tree
Showing 7 changed files with 142 additions and 19 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.

4 changes: 2 additions & 2 deletions webapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
"react-responsive": "^9.0.2",
"react-router-dom": "^6.22.1",
"react-scripts": "5.0.1",
"web-vitals": "^3.5.1",
"react-toastify": "^8.0.2"
"react-toastify": "^8.2.0",
"web-vitals": "^3.5.1"
},
"scripts": {
"start": "react-scripts start",
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 path={process.env.RUTA_INICIO || '/'} 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;
9 changes: 8 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,16 @@ 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 });
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 0822e5c

Please sign in to comment.