UNPKG

authorization-z

Version:

`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

420 lines (316 loc) โ€ข 10.5 kB
# 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: ```bash npm install authorization-z ``` ## ๐Ÿ”ง Usage ### Basic Setup ```typescript 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: ```typescript // 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: ```json { "userId": "123", "email": "user@example.com", "role": "admin", "permissions": { "users": ["read", "create", "update", "delete"], "products": ["read", "create"], "orders": ["read", "update"] } } ``` #### Multiple Permission Checks ```typescript // 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 ```typescript 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 1. **Clone the repository** ```bash git clone <repository-url> cd authorization-z ``` 2. **Install dependencies** ```bash npm install ``` 3. **Build the package** ```bash npm run build ``` 4. **Test locally** ```bash # 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 1. **Create package.json** ```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" } ``` 2. **Configure TypeScript (tsconfig.json)** ```json { "compilerOptions": { "target": "ES2019", "module": "commonjs", "declaration": true, "outDir": "dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true }, "include": ["src"], "exclude": ["dist", "node_modules"] } ``` 3. **Set up build script** Create `scripts/copy-assets.js` to copy locale files during build. ### Publishing to NPM #### First Time Publishing 1. **Login to NPM** ```bash npm login ``` 2. **Check package name availability** ```bash npm search authorization-z ``` 3. **Build the package** ```bash npm run build ``` 4. **Publish** ```bash npm publish ``` #### Updating the Package 1. **Update version** ```bash # 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 major ``` 2. **Build and publish** ```bash 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 ```bash # Required JWT_SECRET=your-super-secret-jwt-key # Optional NODE_ENV=production ``` ### TypeScript Configuration The package extends Express types to include: ```typescript 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: ```typescript // 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 1. **Generate a JWT token** ```javascript const jwt = require('jsonwebtoken'); const token = jwt.sign({ userId: '123', email: 'test@example.com', permissions: { users: ['read', 'create'], products: ['read'] } }, 'your-secret-key'); console.log(token); ``` 2. **Test with curl** ```bash 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 for - `action` (string): The action to check permissions for **Returns:** - Express middleware function ## ๐Ÿค Contributing 1. Fork the repository 2. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## ๐Ÿ“„ License This project is licensed under the MIT License - see the [LICENSE](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.