authorization-z
v1.0.2
Published
`Authorization-Z` is a comprehensive Express middleware package for validating JWT Authorization-Z tokens, attaching permissions to requests, verifying permissions, and granting access accordingly. This package provides a robust solution for implementing
Maintainers
Readme
Authorization-Z
Authorization-Z is a comprehensive Express middleware package for validating JWT Authorization-Z tokens, attaching permissions to requests, verifying permissions, and granting access accordingly. This package provides a robust solution for implementing role-based access control (RBAC) in Express applications.
🚀 Features
- JWT Token Validation: Validates JWT tokens using Authorization-Z with comprehensive error handling
- Permission Management: Attaches user permissions to the request object for easy access
- Access Control: Grants access based on module and action permission checks
- Multi-language Support: Built-in internationalization (i18n) support with customizable error messages
- TypeScript Support: Full TypeScript support with type definitions
- Express Integration: Seamlessly integrates into any Express-based application
- Error Handling: Comprehensive error handling with proper HTTP status codes
- Security: Secure token verification with proper secret validation
📦 Installation
Install the package via npm:
npm install authorization-z🔧 Usage
Basic Setup
import express from 'express';
import { IsJWTAuthorizationZTokenValid, authorizeAccess } from 'authorization-z';
const app = express();
// Your JWT secret key
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
// Apply the JWT validation middleware globally
app.use(IsJWTAuthorizationZTokenValid(JWT_SECRET));
// Your routes
app.get('/api/users', authorizeAccess('users', 'read'), (req, res) => {
// This route requires 'read' permission for 'users' module
res.json({ message: 'Users data' });
});
app.post('/api/users', authorizeAccess('users', 'create'), (req, res) => {
// This route requires 'create' permission for 'users' module
res.json({ message: 'User created' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});Advanced Usage
Custom Error Messages
The package supports internationalization. You can set the language for error messages:
// Set language middleware (before authorization middleware)
app.use((req, res, next) => {
req.lang = req.headers['accept-language'] || 'en';
next();
});
app.use(IsJWTAuthorizationZTokenValid(JWT_SECRET));Permission Structure
The JWT token should contain permissions in the following format:
{
"userId": "123",
"email": "[email protected]",
"role": "admin",
"permissions": {
"users": ["read", "create", "update", "delete"],
"products": ["read", "create"],
"orders": ["read", "update"]
}
}Multiple Permission Checks
// Check multiple actions for the same module
app.put('/api/users/:id',
authorizeAccess('users', 'update'),
authorizeAccess('users', 'write'),
(req, res) => {
res.json({ message: 'User updated' });
}
);
// Different modules
app.get('/api/dashboard',
authorizeAccess('users', 'read'),
authorizeAccess('analytics', 'view'),
(req, res) => {
res.json({ message: 'Dashboard data' });
}
);Accessing Permissions in Routes
app.get('/api/profile', authorizeAccess('profile', 'read'), (req, res) => {
// Access permissions from request object
const userPermissions = req.permissions;
// Check specific permissions
const canDeleteUsers = userPermissions?.users?.includes('delete') || false;
res.json({
permissions: userPermissions,
canDeleteUsers
});
});🛠️ Development Setup
Prerequisites
- Node.js (v14 or higher)
- npm or yarn
- TypeScript knowledge
Local Development
Clone the repository
git clone <repository-url> cd authorization-zInstall dependencies
npm installBuild the package
npm run buildTest locally
# Link the package locally for testing npm link # In your test project npm link authorization-z
Project Structure
authorization-z/
├── src/
│ ├── constants/
│ │ └── messages.ts # Internationalization logic
│ ├── errors/
│ │ └── AppError.ts # Custom error class
│ ├── locales/
│ │ ├── en.json # English messages
│ │ ├── de.json # German messages
│ │ └── it.json # Italian messages
│ ├── middleware/
│ │ ├── authorizeAccessMiddleware.ts
│ │ └── isJWTAuthorizationZTokenValidMiddleware.ts
│ ├── types/
│ │ └── express/
│ │ └── index.d.ts # TypeScript declarations
│ └── index.ts # Main export file
├── scripts/
│ └── copy-assets.js # Build script for assets
├── package.json
├── tsconfig.json
└── README.md📦 Package Publishing Guide
Initial Package Setup
Create package.json
{ "name": "authorization-z", "version": "1.0.0", "description": "Express middleware for validating JWT Authorization-Z tokens", "main": "dist/index.js", "types": "dist/index.d.ts", "files": ["dist"], "scripts": { "build": "tsc && node ./scripts/copy-assets.js", "prepublishOnly": "npm run build" }, "keywords": ["express", "middleware", "jwt", "authorization"], "author": "Your Name", "license": "MIT" }Configure TypeScript (tsconfig.json)
{ "compilerOptions": { "target": "ES2019", "module": "commonjs", "declaration": true, "outDir": "dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true }, "include": ["src"], "exclude": ["dist", "node_modules"] }Set up build script Create
scripts/copy-assets.jsto copy locale files during build.
Publishing to NPM
First Time Publishing
Login to NPM
npm loginCheck package name availability
npm search authorization-zBuild the package
npm run buildPublish
npm publish
Updating the Package
Update version
# Patch version (1.0.0 -> 1.0.1) npm version patch # Minor version (1.0.0 -> 1.1.0) npm version minor # Major version (1.0.0 -> 2.0.0) npm version majorBuild and publish
npm run build npm publish
Publishing Checklist
- [ ] Update version in
package.json - [ ] Update CHANGELOG.md (if applicable)
- [ ] Test the build locally
- [ ] Run
npm run build - [ ] Check
dist/folder contains all necessary files - [ ] Run
npm publish
🔧 Configuration
Environment Variables
# Required
JWT_SECRET=your-super-secret-jwt-key
# Optional
NODE_ENV=productionTypeScript Configuration
The package extends Express types to include:
interface Request {
userId?: string;
email?: string;
tenantId?: string;
tenantKnex?: any;
permissions?: Record<string, string[]>;
lang?: string;
}🚨 Error Handling
The package provides comprehensive error handling with proper HTTP status codes:
401- Unauthorized (missing/invalid token)403- Forbidden (insufficient permissions)400- Bad Request (malformed permissions)500- Internal Server Error (configuration issues)
Error Messages
All error messages support internationalization:
// English (default)
"AUTHORIZATION_Z_TOKEN_MISSING": "Authorization Z token is missing"
// German
"AUTHORIZATION_Z_TOKEN_MISSING": "Authorization Z Token fehlt"
// Italian
"AUTHORIZATION_Z_TOKEN_MISSING": "Token di autorizzazione Z mancante"🧪 Testing
Manual Testing
Generate a JWT token
const jwt = require('jsonwebtoken'); const token = jwt.sign({ userId: '123', email: '[email protected]', permissions: { users: ['read', 'create'], products: ['read'] } }, 'your-secret-key'); console.log(token);Test with curl
curl -H "Authorization-Z: YOUR_JWT_TOKEN" \ -H "Accept-Language: en" \ http://localhost:3000/api/users
📚 API Reference
IsJWTAuthorizationZTokenValid(secret: string)
Validates JWT tokens and attaches permissions to the request object.
Parameters:
secret(string): JWT secret key for token verification
Returns:
- Express middleware function
authorizeAccess(moduleName: string, action: string)
Checks if the user has permission to perform a specific action on a module.
Parameters:
moduleName(string): The module to check permissions foraction(string): The action to check permissions for
Returns:
- Express middleware function
🤝 Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🆘 Support
For support and questions:
- Create an issue on GitHub
- Check the documentation
- Review the examples in this README
🔄 Version History
1.0.0 - Initial release with JWT validation and permission checking
1.0.1 - Removed the language middleware dependency; language is now taken directly from the request.
1.0.2 - Added super admin access control management, granting complete system access to super admin account.
Future versions will be documented here
Note: This package is designed for Express applications and requires Express as a peer dependency. Make sure you have Express installed in your project.
