Introducci贸n a Node.js y Express
Node.js y Express
Entorno de trabajo
Variables de entorno
Rutas din谩micas
Body parser
Postman
CRUD
驴Que es una API Restful?
Solicitudes GET
Solicitudes POST
CRUD
Soluci贸n del reto de validaci贸n
Solicitudes DELETE
MIddlewares
Middlewares - logger
Middlewares - ErrorHandler
DB
Instalar Postgresql
Instalar Prisma y PostgreSQL Client
Prisma Models
JWT
Autenticaci贸n utilizando JSON Web Tokens (JWT)
Auth - Register
Auth - Login
Expres.js
Arquitectura
Arquitectura parte 2
Creaci贸n y Migraci贸n de Modelos con Prisma para Citas M茅dicas
Admin controllers / services
Admin controllers / services parte 2
Reservations
Reservations parte 2
Appointments
Deploy
PostgreSQL
Deploy
You don't have access to this class
Keep learning! Join and start boosting your career
Permission and role management is a fundamental component of modern web application development. In this content, we will explore how to implement an administration system for an appointment booking application, where only users with an administrator role can create blocks of time available for appointments. This structure not only improves the security of our application, but also establishes an organized and efficient workflow.
Before diving into the code, it is important to understand the business logic behind our application. Only an administrator can add blocks of time in which users can register their appointments. This restriction requires implementing a role-based access control structure.
To achieve this, we need to create:
The first step is to set up routes that will only be accessible to administrators. We start by modifying our main routes file:
// routes/index.jsrouter.use('/admin', adminRoutes);
const adminRouter = require('./admin');
Next, we create a file specifically for admin routes:
// routes/admin.jsconst router = require('express').Router();const adminController = require('../controllers/adminController');
// Route to create time blocksrouter.post('/timeblocks', adminController.createTimeBlock);
// Route to list all reservationsrouter.get('/reservations', adminController.listReservations);
module.exports = router;
These routes define two main functionalities for administrators:
The controller is responsible for receiving HTTP requests, validating user permissions and coordinating with the corresponding services:
// controllers/adminController.jsconst createTimeBlockService = require('../services/adminService').createTimeBlockService;const listReservationsService = require('../services/adminService').listReservationsService;
const createTimeBlock = async (req, res) => { // Check if user has admin role if (req.user.role !== 'admin') { return res.status(403).json({ error: 'Access Denied' }); }
// Get data from request body const { startTime, endTime } = req.body;
try { // Call service to create time block const newTimeBlock = await createTimeBlockService(startTime, endTime); res.status(201).json(newTimeBlock); } catch (error) { res.status(500).json({ error: 'Error creating time block' }); } } };
const listReservations = async (req, res) => { // Check if user has admin role if (req.user.role !== 'admin') { return res.status(403).json({ error: 'Access Denied' }); } }
try { // Get all reservations const reservations = await listReservationsService(); res.json(reservations); } catch (error) { res.status(500).json({ error: 'Error getting reservations' }); } } };
module.exports = { createTimeBlock, listReservations};
A crucial aspect of our implementation is permission validation. Notice how in each controller function we check if the user has the administrator role:
if (req.user.role !== 'admin') { return res.status(403).json({ error: 'Access Denied' });}
This simple check ensures that only users with the appropriate role can access these functionalities. If a user without permissions tries to access, they will receive a 403 (Forbidden) error.
To create a time block, we need two essential pieces of information:
This data is extracted from the body of the request:
const { startTime, endTime } = req.body;
Then, these values are passed to the corresponding service, which will take care of the business logic and the interaction with the database.
Although the full implementation of the services is not shown in the code provided, it is important to understand that these will be responsible for:
This separation of responsibilities follows the single responsibility principle and makes our code more maintainable and testable.
The structure that we are implementing follows a common pattern in application development:
This separation offers multiple benefits:
Implementing this structure may seem like more work initially, but in the long run it greatly facilitates the maintenance and evolution of the application.
Proper management of roles and permissions is essential to ensure the security and proper functioning of any application with different types of users. Have you implemented similar systems in your projects? Share your experience in the comments and tell us what strategies you have used to manage authorization in your applications.
Contributions 0
Questions 0
Want to see more contributions, questions and answers from the community?