generated from Arquisoft/wiq_0
-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
User management rita #78
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
876952d
Merge pull request #20 from Arquisoft/documentation_ángel
UO289930 077cbce
connecting to mongoDB
uo284185 0481f9b
Adding new fields to use-model and add a user to database
viraterletska 93cb991
Merge pull request #69 from Arquisoft/user_management_vira
ritacatuxo 8ad2fe6
getOneUser working
uo284185 0562d86
fix /addUser with email and questions_answered not required
ritacatuxo f3ca421
/getUser (specific) working and /allUsers not working
ritacatuxo 588329b
/login working and retrieving a token with all the info
ritacatuxo 6812bd1
/adduser working
ritacatuxo 3830ab9
user-model fixed
ritacatuxo 556877d
auth service tests commented
ritacatuxo fba6ec1
tests comentados y un test siempre true
ritacatuxo 81d4a10
tests commented and one of them always true
ritacatuxo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ | |
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 @@ | |
// 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 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'; | ||
Check failure Code scanning / SonarCloud MongoDB database passwords should not be disclosed High
Make sure this MongoDB database password gets changed and removed from the code. See more on SonarCloud
|
||
|
||
|
||
// 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 @@ | |
} | ||
} | ||
|
||
|
||
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / SonarCloud
MongoDB database passwords should not be disclosed High