Skip to content

Commit

Permalink
Merge pull request #100 from Arquisoft/tokenAuth
Browse files Browse the repository at this point in the history
Token auth
  • Loading branch information
marcosMachadoMenendez authored Apr 1, 2024
2 parents 5655256 + dc51a1b commit 725e9dd
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 7 deletions.
8 changes: 8 additions & 0 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ app.post('/adduser', async (req, res) => {
app.get('/generate-question', async (req, res) => {
try {
// Forward the generate question request to the question service
const bearerHeader = req.headers['authorization'];
if(! bearerHeader ){
return res.sendStatus(403);
}
const questionResponse = await axios.get(generatorServiceUrl+'/generate-question');
res.json(questionResponse.data);
} catch (error) {
Expand All @@ -73,6 +77,10 @@ app.get('/statistics', async (req, res) => {

app.get('/questions', async (req, res) => {
try {
const bearerHeader = req.headers['authorization'];
if(! bearerHeader ){
return res.sendStatus(403);
}
// Forward the get questions request to the question service
const questionResponse = await axios.get(questionServiceUrl+'/questions');
res.json(questionResponse.data);
Expand Down
7 changes: 6 additions & 1 deletion webapp/src/components/Navbar.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import React from "react";
import { NavLink } from "react-router-dom";
import { useAuth } from "./login/AuthProvider";
import "./Navbar.css";

const Navbar = () => {
const { nombreUsuario } = useAuth();

return (
<header className="header">
<nav className="nav container">
Expand All @@ -13,8 +16,10 @@ const Navbar = () => {
>
<ul className="nav-list">
<li className="nav-item">

<NavLink to={process.env.RUTA_USER ||"/statistics"}className="nav__link">
Usuario
Usuario {nombreUsuario}

</NavLink>
</li>

Expand Down
6 changes: 5 additions & 1 deletion webapp/src/components/Primera.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import CssBaseline from '@mui/material/CssBaseline';
import Container from '@mui/material/Container';
import Typography from '@mui/material/Typography';
import { NavLink } from "react-router-dom";
import "./Primera.css";

function Primera() {
Expand All @@ -13,7 +14,10 @@ function Primera() {
<CssBaseline />
<Typography component="h1" variant="h5" align="center" sx={{ marginTop: 20 }}>
Saber y Ganar: El Juego
</Typography>
</Typography>
<NavLink to={process.env.RUTA_LOGIN || '/login'} className="MuiTypography-root MuiTypography-h5 MuiTypography-alignCenter css-1sub1o7">
INICIAR SESIÓN
</NavLink>
</Container>
</div>
);
Expand Down
9 changes: 8 additions & 1 deletion webapp/src/components/QuizGame.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Button } from '@mui/material';
import './QuizGame.css';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useAuth } from "./login/AuthProvider";

const QuizGame = () => {
const numberOfQuestions = 9;
Expand Down Expand Up @@ -32,11 +33,17 @@ const QuizGame = () => {
const correctImage = 'https://img.freepik.com/foto-gratis/signo-icono-simbolo-marca-verificacion-verde-correcto-o-correcto-aprobar-o-concepto-confirmar-ilustracion-aislada-representacion-3d-fondo-verde_56104-1220.jpg?size=626&ext=jpg&ga=GA1.1.117944100.1710028800&semt=ais';
const wrongImage = 'https://img.freepik.com/foto-gratis/signo-cruzado-incorrecto-o-negativo-negativo-eleccion-icono-simbolo-icono-ilustracion-aislado-sobre-fondo-rojo-3d-rendering_56104-1219.jpg?t=st=1710078617~exp=1710082217~hmac=a9dc243dfad6f2c548c66d6748c5aae79b5039b1b5763e34bce3e787114bc329&w=1380';

const { token } = useAuth();

useEffect(() => {

const generateQuestion = async () => {
if (questionsNumber < 1){
try {
const response = await axios.get(`${apiEndpoint}/generate-question`);
const config = {
headers: { Authorization: 'Bearer '+ token}
};
const response = await axios.get(`${apiEndpoint}/generate-question`,config);
setCurrentQuestion(response.data);
setError(null);
} catch (error) {
Expand Down
21 changes: 18 additions & 3 deletions webapp/src/components/login/AuthProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,44 @@ const AuthContext = createContext();
const AuthProvider = ({ children }) => {
// State to hold the authentication token
const [token, setToken_] = useState(localStorage.getItem("token"));
const [nombreUsuario, setUsuario_] = useState(localStorage.getItem("usuario"));

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

const setUsuario = (newNombre) => {
setUsuario_(newNombre);
};

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

useEffect(() => {
if (nombreUsuario) {
localStorage.setItem('usuario',nombreUsuario);
} else {
localStorage.removeItem('usuario')
}
}, [nombreUsuario]);

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

// Provide the authentication context to the children components
Expand Down
3 changes: 2 additions & 1 deletion webapp/src/components/login/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const Login = () => {

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

const { setToken } = useAuth();
const { setToken, setUsuario } = useAuth();


const loginUser = async () => {
Expand All @@ -34,6 +34,7 @@ const Login = () => {

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

setLoginSuccess(true);
Expand Down

0 comments on commit 725e9dd

Please sign in to comment.