Skip to content

Commit

Permalink
Merge pull request #121 from Arquisoft/LaraFMz
Browse files Browse the repository at this point in the history
Lara f mz
  • Loading branch information
UO277938 authored Apr 26, 2024
2 parents 8668d3b + 045cd59 commit c439ab6
Show file tree
Hide file tree
Showing 8 changed files with 196 additions and 30 deletions.
34 changes: 16 additions & 18 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,16 @@ app.post('/login', async (req, res) => {
}
});


function validateCredentials(username, password) {
// Verifica si la contraseña es erronea
if (password.length < 8) {
return false;
}

return true;
}

app.post('/adduser', async (req, res) => {

const isValidUser = validateCredentials(req.body.username, req.body.password);
try {
const { username, password, valido, mensajeError } = req.body;

if (!isValidUser) {
// Si las credenciales son inválidas, devuelve un error 401
res.status(401).json({ error: 'Credenciales incorrectas. La contraseña debe contener al menos 8 caracteres' });
return; // Termina la ejecución de la función para evitar ejecutar el código restante
}
if (!valido) {
// Si las credenciales son inválidas, devuelve un error 401
res.status(401).json({ error: mensajeError });
return; // Termina la ejecución de la función para evitar ejecutar el código restante
}

try {
// Forward the add user request to the user service
const userResponse = await axios.post(userServiceUrl+'/adduser', req.body);
res.json(userResponse.data);
Expand Down Expand Up @@ -110,6 +99,15 @@ app.get('/getUserData', async (req, res) => {
}
});

app.get('/getUsernames', async (req, res) => {
try{
const getUserDataResponse = await axios.get(userServiceUrl+ `/getUsernames`)
res.json(getUserDataResponse.data);
}catch(error){
res.status(error.response.status).json({error: error.response.data.error});
}
});

// Read the OpenAPI YAML file synchronously
let openapiPath='./openapi.yaml';
if (fs.existsSync(openapiPath)) {
Expand Down
11 changes: 0 additions & 11 deletions gatewayservice/gateway-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,6 @@ describe('Gateway Service', () => {
expect(response.status).toBe(500);
expect(response.body).toEqual({ error: errorMessage });
});

// Test /adduser endpoint
it('deberia añadir usuario correctamente', async () => {
const response = await request(app)
.post('/adduser')
.send({ username: 'newuser', password: 'newpassword' });

// Verificamos que la respuesta tenga un código de estado 200 y un ID de usuario
expect(response.statusCode).toBe(200);
expect(response.body.userId).toBe('mockedUserId');
});

// Probamos con una pregunta errónea
it('debería devolver error con esa pregunta', async () => {
Expand Down
99 changes: 99 additions & 0 deletions questionservice/questionservice/package-lock.json

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

5 changes: 5 additions & 0 deletions questionservice/questionservice/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"dependencies": {
"questionservice": "file:.."
}
}
35 changes: 35 additions & 0 deletions userservice/authservice/userservice/authservice/package-lock.json

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

5 changes: 5 additions & 0 deletions userservice/authservice/userservice/authservice/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"dependencies": {
"authservice": "file:../.."
}
}
13 changes: 13 additions & 0 deletions userservice/userservice/user-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,19 @@ app.get('/getUserData', async (req, res) => {
}
});

app.get('/getUsernames', async (req, res) => {
try {
const users = await User.find();
if (!users || users.length===0) {
return res.status(200).json({ success: true, message: 'No hay usuarios en la base de datos' });
}
const usernames = users.map(user => user.username);
return res.status(200).json({ usernames });
} catch (error) {
return res.status(500).json({ success: false, message: 'Error al obtener los datos de usuario' });
}
});

const server = app.listen(port, () => {
console.log(`User Service listening at http://localhost:${port}`);
});
Expand Down
24 changes: 23 additions & 1 deletion webapp/src/components/AddUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,38 @@ const AddUser = () => {
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [openSnackbar, setOpenSnackbar] = useState(false);
const [mensajeError, setMensajeError] =useState('');

const addUser = async () => {
try {
await axios.post(`${apiEndpoint}/adduser`, { username, password });
var valido = await validateCredentials(username, password);
await axios.post(`${apiEndpoint}/adduser`, { username, password, valido, mensajeError });
setOpenSnackbar(true);
} catch (error) {
setError(error.response.data.error);
}
};



async function validateCredentials(username, password){
try {
const response = await axios.get(`${apiEndpoint}/getUsernames`);
const usernames = response.data.usernames;
if (usernames.includes(username)){
setMensajeError('Credenciales incorrectas. El nombre de usuario esta en uso')
return false;
}
if (password.length < 8) {
setMensajeError('Credenciales incorrectas. La contraseña debe contener al menos 8 caracteres')
return false;
}
return true;
} catch (error) {
setError('Error al cargar la información');
}
};

const handleCloseSnackbar = () => {
setOpenSnackbar(false);
};
Expand Down

0 comments on commit c439ab6

Please sign in to comment.