Skip to content

Commit

Permalink
login microservice updated
Browse files Browse the repository at this point in the history
  • Loading branch information
angelalvaigle committed Oct 27, 2024
1 parent c5621b0 commit c9f5242
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 40 deletions.
1 change: 0 additions & 1 deletion gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,4 @@ const server = app.listen(port, () => {
console.log(`Gateway Service listening at http://localhost:${port}`);
});


module.exports = server
27 changes: 27 additions & 0 deletions users/authservice/auth-controller.js
Original file line number Diff line number Diff line change
@@ -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' });
}
};
25 changes: 21 additions & 4 deletions users/authservice/auth-model.js
Original file line number Diff line number Diff line change
@@ -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
module.exports = User;
10 changes: 10 additions & 0 deletions users/authservice/auth-router.js
Original file line number Diff line number Diff line change
@@ -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;
46 changes: 11 additions & 35 deletions users/authservice/auth-service.js
Original file line number Diff line number Diff line change
@@ -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());
Expand All @@ -16,46 +14,24 @@ 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, () => {
console.log(`Auth Service listening at http://localhost:${port}`);
});

server.on('close', () => {
// Close the Mongoose connection
mongoose.connection.close();
});
// Close the Mongoose connection
mongoose.connection.close();
});

module.exports = server
module.exports = server;

0 comments on commit c9f5242

Please sign in to comment.