Skip to content

Commit

Permalink
Added email field on login and register and be able to login with use…
Browse files Browse the repository at this point in the history
…rname or email
  • Loading branch information
Mister-Mario committed Apr 15, 2024
1 parent 22dba52 commit bb17d39
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 26 deletions.
13 changes: 5 additions & 8 deletions users/authservice/auth-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,30 +28,27 @@ app.post('/login', async (req, res) => {
try {
// Check if required fields are present in the request body
try{
validateRequiredFields(req, ['email', 'username', 'password']);
validateRequiredFields(req, ['username', 'password']);
}
catch(error){
res.status(400).json({ error : error.message });
return
}

const email = req.body.email.toString();
const email = req.body.username.toString();
const username = req.body.username.toString();
const password = req.body.password.toString();

let user;
if(username) //Can log in with both
// Find the user by username in the database
user = await User.findOne({ username })
else
let user = await User.findOne({ username })
if(!user) //There is no user by that username we may have received an email
user = await User.findOne({ email })

// Check if the user exists and verify the password
if (user && await bcrypt.compare(password, user.password)) {
// Generate a JWT token
const token = jwt.sign({ userId: user._id }, (process.env.JWT_KEY??'my-key'), { expiresIn: '1h' });
// Respond with the token and user information
res.json({ token: token, username: username, email: email});
res.json({ token: token, username: user.username, email: user.email});
} else {
res.status(400).json({ error: 'Invalid credentials' });
}
Expand Down
18 changes: 12 additions & 6 deletions users/authservice/auth-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,15 @@ let mongoServer;
let app;

//test user
const user = {
email: '[email protected]',
let user = {
username: 'testuser',
password: 'testpassword',
};

async function addUser(user){
const hashedPassword = await bcrypt.hash(user.password, 10);
const newUser = new User({
email: user.email,
email: "user@gmail.com",
username: user.username,
password: hashedPassword,
createdAt: new Date()
Expand Down Expand Up @@ -46,14 +45,21 @@ describe('Auth Service', () => {
expect(response.body).toHaveProperty('username', 'testuser');
});

it('Should show missing field user /login', async () => {
it('Should perform a login operation with email /login', async () => {
user.username = "[email protected]";
const response = await request(app).post('/login').send(user);
expect(response.status).toBe(200);
expect(response.body).toHaveProperty('username', 'testuser');
});

it('Should show missing field username /login', async () => {
const response = await request(app).post('/login').send();
expect(response.status).toBe(400);
expect(response.body).toHaveProperty('error', 'Missing required field: email');
expect(response.body).toHaveProperty('error', 'Missing required field: username');
});

it('Should show invalid credentials /login', async () => {
const user2 = {email:"[email protected]" ,username:"Hello", password:"world"}
const user2 = {username:"Hello", password:"world"}
const response = await request(app).post('/login').send(user2);
expect(response.status).toBe(400);
expect(response.body).toHaveProperty('error', 'Invalid credentials');
Expand Down
14 changes: 13 additions & 1 deletion webapp/src/components/loginAndRegistration/AddUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const AddUser = () => {
const navigate = useNavigate();
const apiUrl = (process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000') + "/adduser";
const { t } = useTranslation("global");
const [email, setEmail] = useState('');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [repeatPassword, setRepeatPassword] = useState('');
Expand All @@ -21,7 +22,7 @@ const AddUser = () => {
try {
//TODO: Add more validations
if(password === repeatPassword){ //User put the same password
const response = await axios.post(apiUrl, { username, password });
const response = await axios.post(apiUrl, { email, username, password });
console.log("Registered user: " + response.data.username);
navigate('/login');
}
Expand All @@ -40,6 +41,17 @@ const AddUser = () => {
<div className="card2">
<form className="form" onSubmit={handleSubmit}>
<h1>{t("addUser.title")}</h1>
<div className="input-box">
<p>{t("addUser.email_placeholder")}:</p>
<input
name = "email"
type="text"
placeholder={t("addUser.email_placeholder")}
required
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="input-box">
<p>{t("addUser.username_placeholder")}:</p>
<input
Expand Down
7 changes: 0 additions & 7 deletions webapp/src/components/loginAndRegistration/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,6 @@ const Login = () => {
onChange={(e) => setPassword(e.target.value)}
/>
</div>
{//TODO: Study this option and see if it is viable
}
<div className="remember-forgot">
<label>
<input type="checkbox" /> {t("login.remember_me")}
</label>
</div>

<button type="submit">{t("login.login_button")}</button>
<LinkRegister />
Expand Down
5 changes: 3 additions & 2 deletions webapp/src/translations/en/global.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
},
"login": {
"title": "Login",
"username_placeholder": "Username",
"username_placeholder": "Username or Email",
"password_placeholder": "Password",
"remember_me": "Remember me",
"forgot_password": "Forgot password?",
Expand All @@ -51,7 +51,8 @@
"password_placeholder": "Password",
"repeat_password_placeholder": "Repeat password",
"register_button": "Register",
"login_link": "Do you have an account? Login here."
"login_link": "Do you have an account? Login here.",
"email_placeholder" : "Email"
},
"gameMenu":{
"history_button":"View Historical Data",
Expand Down
5 changes: 3 additions & 2 deletions webapp/src/translations/es/global.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
},
"login": {
"title": "Inicio de sesión",
"username_placeholder": "Nombre de usuario",
"username_placeholder": "Nombre de usuario o Correo Electrónico",
"password_placeholder": "Contraseña",
"remember_me": "Recordarme",
"forgot_password": "¿Olvidaste tu contraseña?",
Expand All @@ -55,7 +55,8 @@
"password_placeholder": "Contraseña",
"repeat_password_placeholder": "Repetir contraseña",
"register_button": "Registrarse",
"login_link": "¿Ya tienes una cuenta? Inicia sesión aquí."
"login_link": "¿Ya tienes una cuenta? Inicia sesión aquí.",
"email_placeholder" : "Correo electrónico"
},
"gameMenu":{
"history_button":"Ver Historial",
Expand Down

0 comments on commit bb17d39

Please sign in to comment.