From c9f5242b29f08480cefa801438c9f6c7c323c395 Mon Sep 17 00:00:00 2001 From: angelalvaigle Date: Sun, 27 Oct 2024 21:05:53 +0100 Subject: [PATCH] login microservice updated --- gatewayservice/gateway-service.js | 1 - users/authservice/auth-controller.js | 27 ++++++++++++++++ users/authservice/auth-model.js | 25 ++++++++++++--- users/authservice/auth-router.js | 10 ++++++ users/authservice/auth-service.js | 46 +++++++--------------------- 5 files changed, 69 insertions(+), 40 deletions(-) create mode 100644 users/authservice/auth-controller.js create mode 100644 users/authservice/auth-router.js diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index 444b71d..79ccc28 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -67,5 +67,4 @@ const server = app.listen(port, () => { console.log(`Gateway Service listening at http://localhost:${port}`); }); - module.exports = server diff --git a/users/authservice/auth-controller.js b/users/authservice/auth-controller.js new file mode 100644 index 0000000..9451542 --- /dev/null +++ b/users/authservice/auth-controller.js @@ -0,0 +1,27 @@ +const bcrypt = require('bcrypt'); +const jwt = require('jsonwebtoken'); +const User = require('./auth-model.js'); + +exports.loginController = async (req, res) => { + try { + const { username, password } = req.body; + + // Buscar el usuario por nombre en la base de datos + const user = await User.findOne({ username }); + + // Verificar que el usuario exista y la contraseña sea correcta + if (user && (await bcrypt.compare(password, user.password))) { + // Generar un token JWT + const token = jwt.sign({ userId: user._id }, 'your-secret-key', { + expiresIn: '1h', + }); + + // Responder con el token y la información del usuario + res.json({ username, createdAt: user.createdAt }); + } else { + res.status(401).json({ error: 'Invalid credentials' }); + } + } catch (error) { + res.status(500).json({ error: 'Internal Server Error' }); + } +}; diff --git a/users/authservice/auth-model.js b/users/authservice/auth-model.js index 7763b51..7540e29 100644 --- a/users/authservice/auth-model.js +++ b/users/authservice/auth-model.js @@ -1,11 +1,28 @@ const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ - username: String, - password: String, - createdAt: Date, + name: String, + lastName: String, + email: String, + username: { + type: String, + required: true, + }, + password: { + type: String, + required: true, + }, + role: { + type: String, + enum: ['admin', 'user'], + default: 'user', + }, + createdAt: { + type: Date, + default: Date.now, + }, }); const User = mongoose.model('User', userSchema); -module.exports = User \ No newline at end of file +module.exports = User; diff --git a/users/authservice/auth-router.js b/users/authservice/auth-router.js new file mode 100644 index 0000000..4a60c72 --- /dev/null +++ b/users/authservice/auth-router.js @@ -0,0 +1,10 @@ +// authRouter.js +const express = require('express'); +const { loginController } = require('./auth-controller.js'); // Asegúrate de que esta ruta sea correcta + +const authRouter = express.Router(); + +// Define la ruta para el login y asocia el controlador +authRouter.post('/login', loginController); + +module.exports = authRouter; diff --git a/users/authservice/auth-service.js b/users/authservice/auth-service.js index 9764f08..c36511c 100644 --- a/users/authservice/auth-service.js +++ b/users/authservice/auth-service.js @@ -1,11 +1,9 @@ const express = require('express'); const mongoose = require('mongoose'); -const bcrypt = require('bcrypt'); -const jwt = require('jsonwebtoken'); -const User = require('./auth-model') +const authRouter = require('./auth-router.js'); const app = express(); -const port = 8002; +const port = 8002; // Middleware to parse JSON in request body app.use(express.json()); @@ -16,37 +14,15 @@ mongoose.connect(mongoUri); // Function to validate required fields in the request body function validateRequiredFields(req, requiredFields) { - for (const field of requiredFields) { - if (!(field in req.body)) { - throw new Error(`Missing required field: ${field}`); - } + for (const field of requiredFields) { + if (!(field in req.body)) { + throw new Error(`Missing required field: ${field}`); } + } } // 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 }); - - // 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' }); - // Respond with the token and user information - res.json({ token: token, username: username, createdAt: user.createdAt }); - } else { - res.status(401).json({ error: 'Invalid credentials' }); - } - } catch (error) { - res.status(500).json({ error: 'Internal Server Error' }); - } -}); +app.use('/', authRouter); // Start the server const server = app.listen(port, () => { @@ -54,8 +30,8 @@ const server = app.listen(port, () => { }); server.on('close', () => { - // Close the Mongoose connection - mongoose.connection.close(); - }); + // Close the Mongoose connection + mongoose.connection.close(); +}); -module.exports = server +module.exports = server;