ExpressJs

⌘K
  1. Home
  2. Docs
  3. ExpressJs
  4. Authentication and Permis...
  5. 07. example routes

07. example routes

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:

  1. User, Group, and Permission models with their relationships
  2. User registration and login functionality
  3. JWT-based authentication middleware
  4. Permission checking middleware
  5. Routes for managing groups and permissions
  6. Example routes demonstrating different levels of access control

To use this system:

  1. Set up your MySQL database and update the .env file with your database credentials and JWT secret.
  2. Run the application using nodemon app.js.
  3. Use the /api/auth/register and /api/auth/login endpoints to create users and obtain JWT tokens.
  4. Use the admin routes to create groups and permissions, and assign them to users.
  5. 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.

How can we help?