Skip to content

Commit

Permalink
implement sign contract, create document and tests b00tc4mp#85
Browse files Browse the repository at this point in the history
  • Loading branch information
MatiasSargo committed Aug 29, 2024
1 parent fa4338a commit f4647a5
Show file tree
Hide file tree
Showing 35 changed files with 686 additions and 368 deletions.
28 changes: 28 additions & 0 deletions staff/matias-sargo/project/api/handlers/createDocumentHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { logic } from '../../cor/index.js';
import fs from 'fs';

export default (req, res, next) => {
const { propertyId, type, url } = req.body;
const file = req.file; // Aquí se encuentra el archivo subido por `multer`

if (!file) {
return res.status(400).json({ error: 'BadRequest', message: 'File is required' });
}

try {
logic.createDocument(propertyId, file.path, type, url)
.then(() => {
fs.unlinkSync(file.path); // Elimina el archivo temporal después de guardarlo
res.status(201).send();
})
.catch(error => {
fs.unlinkSync(file.path); // Asegúrate de eliminar el archivo temporal si ocurre un error
next(error);
});
} catch (error) {
if (fs.existsSync(file.path)) {
fs.unlinkSync(file.path); // Elimina el archivo si ocurre un error en la escritura
}
next(error);
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export default (req, res, next) => {

try {
logic.getAllProps(userId)
.then(properties => res.json(properties)) // Cambia 'events' por 'properties' para mayor claridad
.then(properties => res.json(properties))
.catch(error => next(error));
} catch (error) {
next(error);
Expand Down
27 changes: 15 additions & 12 deletions staff/matias-sargo/project/api/handlers/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import registerUserHandler from '../handlers/registerUserHandler.js'
import authenticateUserHandler from '../handlers/authenticateUserHandler.js'
import createPropHandler from '../handlers/createPropHandler.js'
import getAllPropsHandler from '../handlers/getAllPropsHandler.js'
import createContractHandler from './createContractHandler.js'
import registerUserHandler from "../handlers/registerUserHandler.js";
import authenticateUserHandler from "../handlers/authenticateUserHandler.js";
import createPropHandler from "../handlers/createPropHandler.js";
import getAllPropsHandler from "../handlers/getAllPropsHandler.js";
import createContractHandler from "./createContractHandler.js";
import signContractHandler from "./signContractHandler.js";
import createDocumentHandler from "./createDocumentHandler.js";

export {
registerUserHandler,
authenticateUserHandler,
createPropHandler,
getAllPropsHandler,
createContractHandler

}
registerUserHandler,
authenticateUserHandler,
createPropHandler,
getAllPropsHandler,
createContractHandler,
signContractHandler,
createDocumentHandler
};
14 changes: 14 additions & 0 deletions staff/matias-sargo/project/api/handlers/signContractHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { logic } from '../../cor/index.js';

export default (req, res, next) => {
const { userId } = req; // Obtenido del middleware
const { contractId } = req.params;

try {
logic.signContract(userId, contractId)
.then(() => res.status(200).send())
.catch(error => next(error));
} catch (error) {
next(error);
}
};
80 changes: 47 additions & 33 deletions staff/matias-sargo/project/api/index.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,51 @@
import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import "dotenv/config";
import express from "express";
import cors from "cors";
import multer from "multer";

import { mongoose } from '../cor/index.js';

import { jsonBodyParser, jwtVerifier, errorHandler } from './middlewares/index.js';
import { mongoose } from "../cor/index.js";

import {
registerUserHandler,
authenticateUserHandler,
createPropHandler,
getAllPropsHandler,
createContractHandler
} from './handlers/index.js';

mongoose.connect(process.env.MONGODB_URI)
.then(() => {
console.info(`API connected to ${process.env.MONGODB_URI}`);

const api = express();

api.use(cors());

api.post('/users', jsonBodyParser, registerUserHandler);
api.post('/users/auth', jsonBodyParser, authenticateUserHandler);
jsonBodyParser,
jwtVerifier,
errorHandler,
} from "./middlewares/index.js";

api.post('/properties', jsonBodyParser, jwtVerifier, createPropHandler);
api.get('/properties', jwtVerifier, getAllPropsHandler)

api.post('/contracts', jsonBodyParser, jwtVerifier, createContractHandler);

api.use(errorHandler);

api.listen(process.env.PORT, () => console.info(`API listening on PORT ${process.env.PORT}`));
})
.catch(error => console.error(error));
import {
registerUserHandler,
authenticateUserHandler,
createPropHandler,
getAllPropsHandler,
createContractHandler,
signContractHandler,
createDocumentHandler
} from "./handlers/index.js";

mongoose
.connect(process.env.MONGODB_URI)
.then(() => {
console.info(`API connected to ${process.env.MONGODB_URI}`);

const api = express();
const upload = multer({ dest: 'uploads/' });

api.use(cors());

api.post("/users", jsonBodyParser, registerUserHandler);
api.post("/users/auth", jsonBodyParser, authenticateUserHandler);

api.post("/properties", jsonBodyParser, jwtVerifier, createPropHandler);
api.get("/properties", jwtVerifier, getAllPropsHandler);

api.post("/contracts", jsonBodyParser, jwtVerifier, createContractHandler);
api.post("/contracts/:contractId/sign", jsonBodyParser, jwtVerifier, signContractHandler);

api.post('/documents', upload.single('content'), createDocumentHandler);

api.use(errorHandler);

api.listen(process.env.PORT, () =>
console.info(`API listening on PORT ${process.env.PORT}`)
);
})
.catch((error) => console.error(error));
4 changes: 3 additions & 1 deletion staff/matias-sargo/project/api/middlewares/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import cors from './cors.js'
import jsonBodyParser from './jsonBodyParser.js'
import jwtVerifier from './jwtVerifier.js'
import errorHandler from './errorHandler.js'
import multer from 'multer'

export {
cors,
jsonBodyParser,
jwtVerifier,
errorHandler
errorHandler,
multer
}
66 changes: 48 additions & 18 deletions staff/matias-sargo/project/api/middlewares/jwtVerifier.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// import jwt from 'jsonwebtoken'
import jwt from 'jsonwebtoken'

// import { errors } from '../../com/index.js'
import { errors } from '../../com/index.js'

// const { SessionError } = errors
const { SessionError } = errors

// export default (req, res, next) => {
// const { authorization } = req.headers
Expand All @@ -23,35 +23,65 @@
// next()
// })
// }

import jwt from 'jsonwebtoken';
import { errors } from '../../com/index.js';

const { SessionError } = errors;

export default (req, res, next) => {
const { authorization } = req.headers;

// Verifica que el header authorization esté presente y tenga el formato correcto
if (!authorization || !authorization.startsWith('Bearer ')) {
return res.status(401).json({ error: SessionError.name, message: 'No authorization token provided or token is malformed.' });
if (!authorization) {
return res.status(401).json({ error: 'Unauthorized', message: 'No authorization header provided' });
}

// Extraer el token del header
console.log('Authorization Header:', authorization);

const token = authorization.slice(7);

// Verificar el token usando la clave secreta
console.log('Token:', token);

jwt.verify(token, process.env.JWT_SECRET, (error, payload) => {
if (error) {
// Si el token es inválido o ha expirado, devuelve un error
console.error('JWT Verification Error:', error.message);
return res.status(498).json({ error: SessionError.name, message: error.message });
}

// Extraer el `userId` del payload y agregarlo al objeto `req`
const { sub: userId } = payload;

console.log('JWT Payload:', payload);
console.log('UserId from JWT:', userId);

req.userId = userId;

// Continuar con la siguiente función de middleware o ruta
next();
});
};
}


// import jwt from 'jsonwebtoken';
// import { errors } from '../../com/index.js';

// const { SessionError } = errors;

// export default (req, res, next) => {
// const { authorization } = req.headers;

// // Verifica que el header authorization esté presente y tenga el formato correcto
// if (!authorization || !authorization.startsWith('Bearer ')) {
// return res.status(401).json({ error: SessionError.name, message: 'No authorization token provided or token is malformed.' });
// }

// // Extraer el token del header
// const token = authorization.slice(7);

// // Verificar el token usando la clave secreta
// jwt.verify(token, process.env.JWT_SECRET, (error, payload) => {
// if (error) {
// // Si el token es inválido o ha expirado, devuelve un error
// return res.status(498).json({ error: SessionError.name, message: error.message });
// }

// // Extraer el `userId` del payload y agregarlo al objeto `req`
// const { sub: userId } = payload;
// req.userId = userId;

// // Continuar con la siguiente función de middleware o ruta
// next();
// });
// };
4 changes: 4 additions & 0 deletions staff/matias-sargo/project/api/middlewares/multer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import multer from 'multer';

// Configura multer para almacenar archivos en una carpeta temporal
const upload = multer({ dest: 'uploads/' });
Loading

0 comments on commit f4647a5

Please sign in to comment.