Skip to content

Commit

Permalink
Hotfix: Added extra security layers in the registration form
Browse files Browse the repository at this point in the history
  • Loading branch information
AbelMH1 committed May 2, 2024
1 parent fffbb23 commit 5ef3226
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 6 deletions.
15 changes: 13 additions & 2 deletions users/userservice/user-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,27 @@ function validateRequiredFields(req, requiredFields) {
}
}

function validateFieldLength(fieldName, value, minLength, maxLength) {
if (value.toString().length < minLength) {
throw new Error(`The field '${fieldName}' must have at least ${minLength} characters`);
} if (value.toString().length > maxLength) {
throw new Error(`The field '${fieldName}' can't have more than ${maxLength} characters`);
}
}

app.post('/adduser', async (req, res) => {
try {
// Check if required fields are present in the request body
validateRequiredFields(req, ['username', 'password']);

const {username, password} = req.body;
validateFieldLength('username', username, 1, 20);
validateFieldLength('password', password, 8, 128);

// Encrypt the password before saving it
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const username = req.body.username.toString();

const user = await User.findOne({ username });
const user = await User.findOne({ username: username.toString() });

// Check if the doesn't exists
if (user) {
Expand Down
30 changes: 30 additions & 0 deletions users/userservice/user-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,36 @@ describe('User Service', () => {
expect(response.status).toBe(200);
expect(response.body).toHaveProperty('username', 'testuser');
});

it('should return an error given a wrong new user on POST /adduser', async () => {
const wrongUser1 = {
username: 'IHaveMoreThan20Characters',
password: 'testpassword',
};
const wrongUser2 = {
username: 'testuser',
password: `IHaveMoreThan128Characters${'0'.repeat(128)}`,
};
const wrongUser3 = {
username: 'testuser',
password: 'lt8Char',
};
const response1 = await request(app).post('/adduser').send(wrongUser1);
expect(response1.status).toBe(400);
expect(response1.body).toHaveProperty('error');
expect(response1.body.error).toEqual(`The field 'username' can't have more than 20 characters`);

const response2 = await request(app).post('/adduser').send(wrongUser2);
expect(response2.status).toBe(400);
expect(response2.body).toHaveProperty('error');
expect(response2.body.error).toEqual(`The field 'password' can't have more than 128 characters`);

const response3 = await request(app).post('/adduser').send(wrongUser3);
expect(response3.status).toBe(400);
expect(response3.body).toHaveProperty('error');
expect(response3.body.error).toEqual(`The field 'password' must have at least 8 characters`);
});

it('should return a list of users on GET /users', async () => {
// Realizar la solicitud GET a /users
const response = await request(app).get('/users');
Expand Down
12 changes: 8 additions & 4 deletions webapp/src/components/AddUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@ const AddUser = () => {
const addUser = async () => {
if (username.trim() === '' || password.trim() === '' || confirmPassword.trim() === '') {
setError('Todos los campos deben de estar rellenos.');
} else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test(password)) {
} else if (username.length > 20) {
setError('El nombre debe contener menos de 21 caracteres.');
} else if (password.length > 128) {
setError('La contraseña debe contener menos de 129 caracteres.');
}else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test(password)) {
setError('Las contraseñas deben contener al menos una letra mayúscula, una letra minúscula y un número, y tener más de 8 caracteres.');
} else if(password !== confirmPassword){
} else if (password !== confirmPassword) {
setError('Las contraseñas no coinciden.');
} else {
try {
Expand All @@ -42,7 +46,7 @@ const AddUser = () => {

return (
<Container className='addUser' component="main" maxWidth="xs" sx={{ marginTop: 4 }}>

<Typography component="h1" variant="h5">
Registro
</Typography>
Expand Down Expand Up @@ -76,7 +80,7 @@ const AddUser = () => {
onChange={(e) => setConfirmPassword(e.target.value)}
/>

<Button text="Registrarse" onClick={addUser} name = "Add user"/>
<Button text="Registrarse" onClick={addUser} name="Add user" />

<Snackbar open={openSnackbar} autoHideDuration={6000} onClose={handleCloseSnackbar} message="Usuario añadido correctamente" />
{error && (
Expand Down

0 comments on commit 5ef3226

Please sign in to comment.