Step 8: Create example routes to demonstrate permission checks
Finally, let’s create some example routes to demonstrate how the permission checks work:
// routes/example.routes.js
const express = require('express');
const verifyToken = require('../middleware/auth');
const checkPermission = require('../middleware/permissions');
const router = express.Router();
router.get('/public', (req, res) => {
res.status(200).send({ message: "Public content." });
});
router.get('/protected', verifyToken, (req, res) => {
res.status(200).send({ message: "Protected content. You need to be logged in." });
});
router.get('/admin', verifyToken, checkPermission('access_admin'), (req, res) => {
res.status(200).send({ message: "Admin content. You need to have admin permissions." });
});
module.exports = router;
Now, let’s update our main app.js
file to include all the routes:
// app.js
const express = require('express');
const dotenv = require('dotenv');
const db = require('./models');
dotenv.config();
const app = express();
app.use(express.json());
// Routes
app.use('/api/auth', require('./routes/auth.routes'));
app.use('/api/admin', require('./routes/admin.routes'));
app.use('/api/example', require('./routes/example.routes'));
const PORT = process.env.PORT || 3000;
db.sequelize.sync().then(() => {
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
});
This completes the basic setup for a Django-like authentication and permission system in Express.js using MySQL and Sequelize ORM. Here’s a summary of what we’ve created:
- User, Group, and Permission models with their relationships
- User registration and login functionality
- JWT-based authentication middleware
- Permission checking middleware
- Routes for managing groups and permissions
- Example routes demonstrating different levels of access control
To use this system:
- Set up your MySQL database and update the
.env
file with your database credentials and JWT secret. - Run the application using
nodemon app.js
. - Use the
/api/auth/register
and/api/auth/login
endpoints to create users and obtain JWT tokens. - Use the admin routes to create groups and permissions, and assign them to users.
- Test the example routes to see how the permission checks work.
Remember to implement proper error handling, input validation, and security measures in a production environment. This example provides a foundation that you can build upon and customize according to your specific needs.