generated from Arquisoft/wiq_0
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #78 from Arquisoft/user_management_rita
User management rita - It has some vulneravilities that will be fixed in the future
- Loading branch information
Showing
7 changed files
with
180 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,8 +11,14 @@ const port = 8002; | |
app.use(express.json()); | ||
|
||
// Connect to MongoDB | ||
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb'; | ||
mongoose.connect(mongoUri); | ||
// Connect to MongoDB - testing | ||
const mongoUri = 'mongodb+srv://prueba:[email protected]/?retryWrites=true&w=majority&appName=Cluster0'; | ||
|
||
|
||
// Connect to the database | ||
mongoose.connect(mongoUri).then( | ||
console.log('Succesfully connected to MongoDB') | ||
); | ||
|
||
// Function to validate required fields in the request body | ||
function validateRequiredFields(req, requiredFields) { | ||
|
@@ -26,20 +32,38 @@ function validateRequiredFields(req, requiredFields) { | |
// Route for user login | ||
app.post('/login', async (req, res) => { | ||
try { | ||
|
||
// Check if required fields are present in the request body | ||
validateRequiredFields(req, ['username', 'password']); | ||
|
||
const { username, password } = req.body; | ||
|
||
// Find the user by username in the database | ||
const user = await User.findOne({ username }); | ||
// access to the database | ||
const db = mongoose.connection.useDb("UsersDB"); | ||
|
||
// access to the collection of the database | ||
const userCollection = db.collection('User'); | ||
|
||
let user; | ||
|
||
await userCollection.findOne({ username: req.body.username }, function(err, result) { | ||
if (err) { | ||
console.error('Error finding user:', err); | ||
} else { | ||
user = result; | ||
// Cerrar la conexión después de terminar la consulta | ||
mongoose.connection.close(); | ||
} | ||
}); | ||
|
||
console.log(user); | ||
|
||
// 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 }, 'your-secret-key', { expiresIn: '1h' }); | ||
const token = jwt.sign({ username: user.username, userEmail: user.email, questions_answered: user.questions_answered, correctly_answered_questions: user.correctly_answered_questions }, 'your-secret-key', { expiresIn: '1h' }); | ||
// Respond with the token and user information | ||
res.json({ token: token, username: username, createdAt: user.createdAt }); | ||
res.json({ token: token }); | ||
} else { | ||
res.status(401).json({ error: 'Invalid credentials' }); | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
const axios = require('axios'); | ||
|
||
async function testLogin() { | ||
try { | ||
const response = await axios.post('http://localhost:8002/login', { | ||
username: 'tomas', | ||
password: '0000' | ||
}); | ||
|
||
console.log('Response:', response.data); | ||
} catch (error) { | ||
console.log('Full Error:', error); // Imprime todo el objeto de error | ||
|
||
} | ||
} | ||
|
||
testLogin(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
const axios = require('axios'); | ||
|
||
async function testAddUser() { | ||
try { | ||
const response = await axios.post('http://localhost:8001/addUser', { | ||
username: 'trogui', | ||
password: '0000', | ||
email: '[email protected]' | ||
}); | ||
|
||
console.log('Response:', response.data); | ||
} catch (error) { | ||
console.log('Full Error:', error); // Imprime todo el objeto de error | ||
|
||
} | ||
} | ||
|
||
testAddUser(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,17 +3,81 @@ const express = require('express'); | |
const mongoose = require('mongoose'); | ||
const bcrypt = require('bcrypt'); | ||
const bodyParser = require('body-parser'); | ||
const User = require('./user-model') | ||
const User = require('./user-model') // user model | ||
|
||
const app = express(); | ||
const port = 8001; | ||
|
||
// Middleware to parse JSON in request body | ||
// Middleware to parse JSON in request bodyUsersDB | ||
app.use(bodyParser.json()); | ||
|
||
|
||
// Connect to MongoDB | ||
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb'; | ||
mongoose.connect(mongoUri); | ||
// Connect to MongoDB - testing | ||
const mongoUri = 'mongodb+srv://prueba:[email protected]/?retryWrites=true&w=majority&appName=Cluster0'; | ||
|
||
|
||
// Connect to the database | ||
mongoose.connect(mongoUri).then( | ||
console.log('Succesfully connected to MongoDB') | ||
); | ||
|
||
// home | ||
app.get("/", async (req, res) => { | ||
res.send("userservice for wiq_en3a"); | ||
|
||
return res.status(200).send(); | ||
}); | ||
|
||
const router = express.Router(); | ||
|
||
// Get all users - not working | ||
app.get('/allUsers', async (req, res) => { | ||
try { | ||
// Obtener todos los usuarios usando el modelo User | ||
const allUsers = await User.find(); | ||
|
||
// Objeto JSON con la lista de usuarios | ||
const allUsersJSON = { | ||
users: allUsers | ||
}; | ||
|
||
res.json(allUsersJSON); | ||
} catch (error) { | ||
res.status(400).json({ error: error.message }); | ||
} | ||
}); | ||
|
||
|
||
|
||
|
||
|
||
// GET route to retrieve an specific user by username - working | ||
// 'http://localhost:8001/getOneUser?username=nombre_de_usuario' | ||
app.get('/getUser', async (req, res) => { | ||
try { | ||
|
||
// access to the database | ||
const db = mongoose.connection.useDb("UsersDB"); | ||
|
||
// access to the collection of the database | ||
const userCollection = db.collection('User'); | ||
|
||
userCollection.findOne({ username: req.body.username }, function(err, result) { | ||
if (err) { | ||
console.error('Error finding user:', err); | ||
} else { | ||
console.log('User:', result); | ||
// Cerrar la conexión después de terminar la consulta | ||
mongoose.connection.close(); | ||
} | ||
}); | ||
//const users = await User.find(); // Retrieve all users from the database | ||
//console.log("Users:", users); // Print users in the terminal | ||
//res.json(users); // Send the array of users as JSON response | ||
} catch (error) { | ||
res.status(500).json({ error: 'Internal Server Error' }); | ||
} | ||
}); | ||
|
||
|
||
|
||
|
@@ -26,21 +90,31 @@ function validateRequiredFields(req, requiredFields) { | |
} | ||
} | ||
|
||
|
||
app.post('/adduser', async (req, res) => { | ||
try { | ||
// Check if required fields are present in the request body | ||
validateRequiredFields(req, ['username', 'password']); | ||
validateRequiredFields(req, ['username', 'password', 'email']); | ||
|
||
// Encrypt the password before saving it | ||
const hashedPassword = await bcrypt.hash(req.body.password, 10); | ||
|
||
const newUser = new User({ | ||
username: req.body.username, | ||
password: hashedPassword, | ||
email: req.body.email, | ||
questions_answered: 0, | ||
correctly_answered_questions: 0 | ||
}); | ||
|
||
await newUser.save(); | ||
res.json(newUser); | ||
// access to the database | ||
const db = mongoose.connection.useDb("UsersDB"); | ||
|
||
// access to the collection of the database | ||
const userCollection = db.collection('User'); | ||
await userCollection.insertOne(newUser); | ||
|
||
res.json(newUser.username); | ||
} catch (error) { | ||
res.status(400).json({ error: error.message }); | ||
}}); | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters