Skip to content

Commit a135263

Browse files
authored
Merge pull request #97 from roahoki/auth_admin2
rutas solo admin listas
2 parents ee506a2 + 722c2eb commit a135263

File tree

1 file changed

+27
-15
lines changed

1 file changed

+27
-15
lines changed

api/src/routes/admin.js

+27-15
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
const Router = require("koa-router");
22
const { AdminRequest, Request, User } = require("../models");
33
const router = new Router();
4-
const { User } = require('../models'); // Asegúrate de importar el modelo User
54

65
const getUserById = async (userId) => {
76
return await User.findOne({
87
where: { id: userId },
9-
attributes: ['id', 'isAdmin'], // Obtener solo los campos necesarios
8+
attributes: ['id', 'isAdmin'],
109
});
1110
};
1211

@@ -186,7 +185,13 @@ router.post('/bonds/:bondId/buy', async (ctx) => {
186185

187186
router.patch('/bonds/:bondId/discount', async (ctx) => {
188187
const { bondId } = ctx.params;
189-
const { discount } = ctx.request.body;
188+
const { userId, discount } = ctx.request.body;
189+
190+
if (!userId) {
191+
ctx.status = 400;
192+
ctx.body = { error: 'userId is required.' };
193+
return;
194+
}
190195

191196
if (![10, 20, 30].includes(discount)) {
192197
ctx.status = 400;
@@ -195,19 +200,26 @@ router.patch('/bonds/:bondId/discount', async (ctx) => {
195200
}
196201

197202
try {
198-
const bond = await AdminRequest.findByPk(bondId);
199-
200-
if (!bond) {
201-
ctx.status = 404;
202-
ctx.body = { error: 'Bond not found' };
203-
return;
204-
}
205-
206-
bond.discount = discount;
207-
await bond.save();
203+
const user = await User.findOne({ where: { id: userId } });
204+
if (!user || !user.isAdmin) {
205+
ctx.status = 403;
206+
ctx.body = { error: 'Access denied. Admins only.' };
207+
return;
208+
}
209+
210+
const bond = await AdminRequest.findByPk(bondId);
208211

209-
ctx.status = 200;
210-
ctx.body = { message: 'Discount applied successfully.', bond };
212+
if (!bond) {
213+
ctx.status = 404;
214+
ctx.body = { error: 'Bond not found' };
215+
return;
216+
}
217+
218+
bond.discount = discount;
219+
await bond.save();
220+
221+
ctx.status = 200;
222+
ctx.body = { message: 'Discount applied successfully.', bond };
211223
} catch (error) {
212224
console.error('Error applying discount:', error);
213225
ctx.status = 500;

0 commit comments

Comments
 (0)