Skip to content

Commit

Permalink
user-service updated
Browse files Browse the repository at this point in the history
  • Loading branch information
angelalvaigle committed Oct 28, 2024
1 parent 42f31d8 commit 68ddf85
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 62 deletions.
42 changes: 30 additions & 12 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ const axios = require('axios');
const cors = require('cors');
const promBundle = require('express-prom-bundle');
//libraries required for OpenAPI-Swagger
const swaggerUi = require('swagger-ui-express');
const fs = require("fs")
const YAML = require('yaml')

const swaggerUi = require('swagger-ui-express');
const fs = require('fs');
const YAML = require('yaml');

const app = express();
const port = 8000;
Expand All @@ -18,7 +17,7 @@ app.use(cors());
app.use(express.json());

//Prometheus configuration
const metricsMiddleware = promBundle({includeMethod: true});
const metricsMiddleware = promBundle({ includeMethod: true });
app.use(metricsMiddleware);

// Health check endpoint
Expand All @@ -29,25 +28,44 @@ app.get('/health', (_req, res) => {
app.post('/login', async (req, res) => {
try {
// Forward the login request to the authentication service
const authResponse = await axios.post(authServiceUrl+'/login', req.body);
const authResponse = await axios.post(authServiceUrl + '/login', req.body);
res.json(authResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
res
.status(error.response.status)
.json({ error: error.response.data.error });
}
});

app.post('/adduser', async (req, res) => {
try {
// Forward the add user request to the user service
const userResponse = await axios.post(userServiceUrl+'/adduser', req.body);
const userResponse = await axios.post(
userServiceUrl + '/adduser',
req.body
);
res.json(userResponse.data);
} catch (error) {
res
.status(error.response.status)
.json({ error: error.response.data.error });
}
});

app.get('/users', async (req, res) => {
try {
// Forward the get users request to the user service
const userResponse = await axios.get(userServiceUrl + '/users', req.body);
res.json(userResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
res
.status(error.response.status)
.json({ error: error.response.data.error });
}
});

// Read the OpenAPI YAML file synchronously
openapiPath='./openapi.yaml'
openapiPath = './openapi.yaml';
if (fs.existsSync(openapiPath)) {
const file = fs.readFileSync(openapiPath, 'utf8');

Expand All @@ -59,12 +77,12 @@ if (fs.existsSync(openapiPath)) {
// It takes the parsed Swagger document as input
app.use('/api-doc', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
} else {
console.log("Not configuring OpenAPI. Configuration file not present.")
console.log('Not configuring OpenAPI. Configuration file not present.');
}

// Start the gateway service
const server = app.listen(port, () => {
console.log(`Gateway Service listening at http://localhost:${port}`);
});

module.exports = server
module.exports = server;
6 changes: 6 additions & 0 deletions users/authservice/auth-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ const userSchema = new mongoose.Schema({
},
});

userSchema.methods.toJSON = function () {
let obj = this.toObject();
delete obj.password;
return obj;
};

const User = mongoose.model('User', userSchema);

module.exports = User;
2 changes: 1 addition & 1 deletion users/authservice/auth-router.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// authRouter.js
const express = require('express');
const { loginController } = require('./auth-controller.js'); // Asegúrate de que esta ruta sea correcta
const { loginController } = require('./auth-controller.js');

const authRouter = express.Router();

Expand Down
44 changes: 44 additions & 0 deletions users/userservice/user-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const bcrypt = require('bcrypt');
const User = require('./user-model');

// 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}`);
}
}
}

exports.addUserController = async (req, res) => {
try {
// Check if required fields are present in the request body
validateRequiredFields(req, ['username', 'password']);

// Encrypt the password before saving it
const hashedPassword = await bcrypt.hash(req.body.password, 10);

const newUser = new User({
name: req.body.name,
lastName: req.body.lastName,
email: req.body.email,
username: req.body.username,
password: hashedPassword,
role: req.body.role,
});

await newUser.save();
res.json(newUser);
} catch (error) {
res.status(400).json({ error: error.message });
}
};

exports.getUsersController = async (req, res) => {
try {
const users = await User.find(); // Fetch all users, only return username field for security
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
};
6 changes: 6 additions & 0 deletions users/userservice/user-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ const userSchema = new mongoose.Schema({
},
});

userSchema.methods.toJSON = function () {
let obj = this.toObject();
delete obj.password;
return obj;
};

const User = mongoose.model('User', userSchema);

module.exports = User;
14 changes: 14 additions & 0 deletions users/userservice/user-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// userRouter.js
const express = require('express');
const {
addUserController,
getUsersController,
} = require('./user-controller.js');

const userRouter = express.Router();

// Define la ruta para el login y asocia el controlador
userRouter.post('/adduser', addUserController);
userRouter.get('/users', getUsersController);

module.exports = userRouter;
50 changes: 3 additions & 47 deletions users/userservice/user-service.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
// user-service.js
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const bodyParser = require('body-parser');
const User = require('./user-model');
const { get } = require('http');
const { emit } = require('process');
const userRouter = require('./user-router.js');

const app = express();
const port = 8001;
Expand All @@ -17,49 +14,8 @@ app.use(bodyParser.json());
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb';
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}`);
}
}
}

// add a new user
app.post('/adduser', async (req, res) => {
try {
// Check if required fields are present in the request body
validateRequiredFields(req, ['username', 'password']);

// Encrypt the password before saving it
const hashedPassword = await bcrypt.hash(req.body.password, 10);

const newUser = new User({
name: req.body.name,
lastName: req.body.lastName,
email: req.body.email,
username: req.body.username,
password: hashedPassword,
role: req.body.role,
});

await newUser.save();
res.json(newUser);
} catch (error) {
res.status(400).json({ error: error.message });
}
});

// get users
app.get('/users', async (req, res) => {
try {
const users = await User.find(); // Fetch all users, only return username field for security
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// userRouter
app.use('/', userRouter);

const server = app.listen(port, () => {
console.log(`User Service listening at http://localhost:${port}`);
Expand Down
2 changes: 0 additions & 2 deletions webapp/src/pages/AddUser.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ const AddUser = () => {
const navigate = useNavigate();

const addUser = async () => {
console.log({ username });
console.log({ password });
try {
await axios.post(`${apiEndpoint}/adduser`, {
name,
Expand Down

0 comments on commit 68ddf85

Please sign in to comment.