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
Markdown
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');
});
```
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));
```
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"]
}
}
```
```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' });
}
);
```
```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
});
});
```
- Node.js (v14 or higher)
- npm or yarn
- TypeScript knowledge
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
npm link
npm link authorization-z
```
```
authorization-z/
โโโ src/
โ โโโ constants/
โ โ โโโ messages.ts
โ โโโ errors/
โ โ โโโ AppError.ts
โ โโโ locales/
โ โ โโโ en.json
โ โ โโโ de.json
โ โ โโโ it.json
โ โโโ middleware/
โ โ โโโ authorizeAccessMiddleware.ts
โ โ โโโ isJWTAuthorizationZTokenValidMiddleware.ts
โ โโโ types/
โ โ โโโ express/
โ โ โโโ index.d.ts
โ โโโ index.ts
โโโ scripts/
โ โโโ copy-assets.js
โโโ package.json
โโโ tsconfig.json
โโโ README.md
```
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.
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
```
1. **Update version**
```bash
npm version patch
npm version minor
npm version major
```
2. **Build and publish**
```bash
npm run build
npm publish
```
- [ ] 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`
```bash
JWT_SECRET=your-super-secret-jwt-key
NODE_ENV=production
```
The package extends Express types to include:
```typescript
interface Request {
userId?: string;
email?: string;
tenantId?: string;
tenantKnex?: any;
permissions?: Record<string, string[]>;
lang?: string;
}
```
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
```
Validates JWT tokens and attaches permissions to the request object.
**Parameters:**
- `secret` (string): JWT secret key for token verification
**Returns:**
- Express middleware function
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
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.
`Authorization-Z`