Access Control and Authorization
You'll learn how to use decorators to automatically enforce user permissions and restrict method access based on roles.
The Core Idea
Access control means ensuring only authorized users can execute certain methods or access specific functionality. Instead of manually checking permissions at the start of every sensitive method, you can use decorators to enforce these checks automatically — turning authorization into a declarative, reusable pattern.
Think of a decorator as a security guard at the entrance to a function. Before anyone enters, the guard checks their credentials. If they have the right role or permission, they proceed. Otherwise, they're turned away before the function even starts.
How It Works
A method decorator can inspect the context, check user roles or permissions (typically from an authentication system or current session), and either allow execution or throw an authorization error:
function requireRole(requiredRole) {
return function(method, context) {
return function(...args) {
const currentUser = this.getCurrentUser(); // Assumes object has this method
if (!currentUser || currentUser.role !== requiredRole) {
throw new Error(`Access denied: ${requiredRole} role required`);
}
return method.call(this, ...args);
};
};
}
class AdminPanel {
@requireRole('admin')
deleteUser(userId) {
// Only admins reach here
console.log(`Deleting user ${userId}`);
}
}
Here, @requireRole('admin') wraps the method so that every call is preceded by a permission check. No admin role? The decorator stops execution immediately.
You can create more sophisticated decorators that check multiple permissions, log access attempts, or integrate with external authorization services.
Key Takeaway:
Authorization decorators centralize and enforce access control logic, making sensitive methods self-documenting and removing repetitive permission checks from your business logic.