Skip to content
This repository has been archived by the owner on May 10, 2024. It is now read-only.

Commit

Permalink
Merge pull request #62 from Arquisoft/FixUserTests#61
Browse files Browse the repository at this point in the history
Fix user tests#61
  • Loading branch information
RubenFern authored Feb 10, 2024
2 parents ceba1f5 + d721ce0 commit fb63c43
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 53 deletions.
20 changes: 16 additions & 4 deletions auth_service/auth/authEndpoints.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ function validateRequiredFields(req, requiredFields) {
const login = async (req, res) => {
try {
if(!validateRequiredFields(req,['username','password'])){
res.status(401).send();
res
.status(401)
.json({error:"Usuario o contraseña incorrectos"})
.send();
return;
}

Expand All @@ -34,12 +37,18 @@ const login = async (req, res) => {
})

if(u == undefined){
res.status(401).send();
res
.status(401)
.json({error:"Usuario o contraseña incorrectos"})
.send();
return;
}

if(!bcrypt.compareSync(password, u.password)) {
res.status(401).send();
res
.status(401)
.json({error:"Usuario o contraseña incorrectos"})
.send();
return;
}

Expand All @@ -57,7 +66,10 @@ const login = async (req, res) => {
const register = async (req, res) => {
try{
if(!validateRequiredFields(req,['username','password'])){
res.status(401).send();
res
.status(401)
.json({error:"Usuario o contraseña incorrectos"})
.send();
return;
}

Expand Down
21 changes: 21 additions & 0 deletions docs/src/10_quality_requirements.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,18 @@ In any case the tree should include links to the scenarios of the following sect
****

[options="header",cols="1,2,2,1"]
|===
|Quality Category|Quality|Description|Scenario
| _Usability_ | _Easy to use_ | _Ease of use by the user when playing games or moving around the application._ | _SC1_
| __ | _Easy to learn_ | _Game modes should be intuitive._ | __
| _Maintainability_ | _Robustness_ | _The application must be able to respond to user requests first._ | _SC2_
| __ | _Persistence_ | _There will be no partial loss of user information and data._ | __
| _Performance efficiency_ | _Response time_ | _La aplicación no deberá superar los 3 segundos de tiempo de espera_ | _SC3_
| _Security_ | _Integrity_ | _User data must be kept confidential and secure at all times._ | __
| _Cultural and Regional_ | _Multi-language_ | _The application texts must be displayed in English._ | _SC4_
|===

=== Quality Scenarios

[role="arc42help"]
Expand All @@ -71,3 +83,12 @@ more precisely down to a level of scenarios that can be discussed and evaluated.
.Form
Tabular or free form text.
****

[options="header",cols="1,4"]
|===
|Id|Scenario
| _SC1_ | _A new user registers in the application and can start playing without the need to view a user guide._
| _SC2_ | _A user performs an action in the application that results in an internal error, but the user can still use the application normally._
| _SC3_ | _Un usuario jugando irá visualizando las diferentes preguntas con un tiempo de espera bajo o inexistente._
| _SC4_ | _Un usuario de habla inglesa podrá usar y jugar con la aplicación sin suponerle ningún problema._
|===
19 changes: 9 additions & 10 deletions webapp/src/components/login/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,37 +28,36 @@ const Login = () =>
{
e.preventDefault();

if ( username.trim() !== '' && password.trim() !== '' )
if ( username !== '' && password !== '' )
{
setError('');
setValidUsername(true);
setValidPassword(true);

let res = await login(username, password);
const res = await login(username, password);

if(!res)
setError("Usuario o contraseña incorrectos");
else
setError("");
if (res !== '')
setError(res);

return;
}

if ( username.trim() === '' )
if ( username === '' )
setValidUsername(false);

if ( password.trim() === '' )
if ( password === '' )
setValidPassword(false);
}

const checkUsername = (e) =>
{
setUsername(e.target.value);
setUsername(e.target.value.trim());
setValidUsername(true);
}

const checkPassword = (e) =>
{
setPassword(e.target.value);
setPassword(e.target.value.trim());
setValidPassword(true);
}

Expand Down
49 changes: 43 additions & 6 deletions webapp/src/components/register/AddUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,54 @@ import { register } from "../../services/user.service";
const AddUser = () =>
{
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [validUsername, setValidUsername] = useState(true);
const [validPassword, setValidPassword] = useState(true);
const [validConfirmPassword, setValidConfirmPassword] = useState(true);
const [error, setError] = useState('');

const doRegister = async (e) => {
e.preventDefault();
e.preventDefault();

let error = await register(username,password)
setError(error);
if ( username !== '' && password !== '' && password === confirmPassword )
{
setError('');
setValidUsername(true);
setValidPassword(true);

const error = await register(username,password)

if (error !== '')
setError(error);
}

if ( username === '' )
setValidUsername(false);

if ( password === '' )
setValidPassword(false);

if ( password !== confirmPassword )
setValidConfirmPassword(false);
}

const checkUsername = (e) =>
{
setUsername(e.target.value);
setUsername(e.target.value.trim());
setValidUsername(true);
}

const checkPassword = (e) =>
{
setPassword(e.target.value);
setPassword(e.target.value.trim());
setValidPassword(true);
}

const checkConfirmPassword = (e) =>
{
setConfirmPassword(e.target.value.trim());
setValidConfirmPassword(true);
}

return (
Expand Down Expand Up @@ -79,6 +109,8 @@ const AddUser = () =>
name="username"
autoComplete="username"
onChange={ checkUsername }
error={!validUsername}
helperText={validUsername ? '' : 'Debes introducir tu nombre de usuario'}
autoFocus
/>
<TextField
Expand All @@ -91,6 +123,8 @@ const AddUser = () =>
id="password"
autoComplete="current-password"
onChange={ checkPassword }
error={!validPassword}
helperText={validPassword ? '' : 'Debes introducir una contraseña'}
/>
<TextField
margin="normal"
Expand All @@ -101,6 +135,9 @@ const AddUser = () =>
type="password"
id="confirmPassword"
autoComplete="current-password"
onChange={ checkConfirmPassword }
error={!validConfirmPassword}
helperText={validConfirmPassword ? '' : 'Las contraseñas no coinciden'}
/>

<Typography variant="body2" color="error" sx={{ mt: 1 }}>
Expand Down
35 changes: 25 additions & 10 deletions webapp/src/components/register/AddUser.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,47 @@ describe('AddUser Component', () => {
expect(screen.getByText('Registro')).toBeInTheDocument();
});

test('submits the form with valid input', async () => {
/* TODO fix these tests
test('submit the form with valid inputs', async () => {
render(<MemoryRouter><AddUser /></MemoryRouter>);

fireEvent.change(screen.getByLabelText(/Nombre de usuario/i), { target: { value: 'validUsername' } });
fireEvent.change(screen.getByLabelText(/Contraseña/i), { target: { value: 'validPassword' } });

fireEvent.change(screen.getAllByLabelText(/Contraseña/i)[0], { target: { value: 'validPassword' } });
fireEvent.change(screen.getByLabelText(/Repetir contraseña/i), { target: { value: 'validPassword' } });

fireEvent.submit(screen.getByRole('button', { name: 'Registrarme' }));

// Wait for the asynchronous code inside doRegister to complete
await waitFor(() => {
expect(screen.queryByText('')).not.toBeInTheDocument(); // No error message should be present
});*/
expect(screen.queryByText('Debes introducir tu nombre de usuario')).toBeNull();
expect(screen.queryByText('Debes introducir una contraseña')).toBeNull();
});
});

test('displays error message with invalid input', async () => {
/* TODO fix these tests
test('attempt to register with empty fields', async () => {
render(<MemoryRouter><AddUser /></MemoryRouter>);

fireEvent.submit(screen.getByRole('button', { name: 'Registrarme' }));

await waitFor(() => {
expect(screen.getByText('')).toBeInTheDocument(); // An error message should be present
});*/
expect(screen.getByText('Debes introducir tu nombre de usuario')).toBeInTheDocument();
expect(screen.getByText('Debes introducir una contraseña')).toBeInTheDocument();
});
});

// Add more tests as needed
test('submit the form with different passwords', async () => {
render(<MemoryRouter><AddUser /></MemoryRouter>);

fireEvent.change(screen.getByLabelText(/Nombre de usuario/i), { target: { value: 'validUsername' } });

fireEvent.change(screen.getAllByLabelText(/Contraseña/i)[0], { target: { value: 'validPassword' } });
fireEvent.change(screen.getByLabelText(/Repetir contraseña/i), { target: { value: 'invalidPassword' } });

fireEvent.submit(screen.getByRole('button', { name: 'Registrarme' }));

// Wait for the asynchronous code inside doRegister to complete
await waitFor(() => {
expect(screen.getByText('Las contraseñas no coinciden')).toBeInTheDocument();
});
});
});
13 changes: 10 additions & 3 deletions webapp/src/routers/AppRouter.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createBrowserRouter } from "react-router-dom";
import { Navigate, createBrowserRouter } from "react-router-dom";

import Login from "../components/login/Login";
import AddUser from "../components/register/AddUser";
Expand All @@ -7,8 +7,11 @@ import Error404 from "../components/error/Error404";
const router = createBrowserRouter([
{
path: "/",
element: <h1 className="text-white text-5xl text-center">Pantalla del juego</h1>,
errorElement: <Error404 />
element: <Navigate to="/home" replace />
},
{
path: "/home",
element: <h1 className="text-white text-5xl text-center">Pantalla del juego</h1>
},
{
path: "/login",
Expand All @@ -17,6 +20,10 @@ const router = createBrowserRouter([
{
path: "/register",
element: <AddUser />
},
{
path: "*",
element: <Error404 />
}
]);

Expand Down
35 changes: 15 additions & 20 deletions webapp/src/services/user.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,38 +7,33 @@ let token;
const login = async (username, password) =>
{
try {
const response = await axios.post(`${apiEndpoint}:8001/api/auth/login`, { username, password });
const response = await axios.post(`${apiEndpoint}:8001/api/auth/login`, { username, password });

if(response.status == 401)
return false;
token = response.data.token;

token = response.data.token;
return "";

return true;

} catch (error) {
return false;
}
} catch (error) {
return error.response.data.error;
}
}

const register = async (username, password) =>
{
try {
const response = await axios.post(`${apiEndpoint}:8001/api/auth/register`, { username, password });

if(response.status == 201)
return "";
try {
const response = await axios.post(`${apiEndpoint}:8001/api/auth/register`, { username, password });

let err = response.data.error;
if ( response.status === 200 )
return response.data.error;

return err;
return "";

} catch (error) {
return "";
}
} catch (error) {
return error.response.data.error;
}
}

const isLoggedIn = async (username, password) => token != undefined;
const isLoggedIn = async (username, password) => token !== undefined;
const getToken = async () => token;

export {login, register, isLoggedIn, getToken};

0 comments on commit fb63c43

Please sign in to comment.