4. Identity & Access Module step‐by‐step - Wiz-DevTech/prettygirllz GitHub Wiki
Here's a clear step-by-step guide for implementing and using the Identity & Access Module:
Identity & Access Module
Step-by-Step Implementation Guide
🚀 1. Prerequisites Setup
# Install Node.js (v18+) and npm
brew install node # MacOS
choco install nodejs # Windows
# Install MongoDB (or use Docker)
docker run -d -p 27017:27017 --name auth-mongo mongo:6
# Install Redis for rate limiting (optional)
docker run -d -p 6379:6379 --name auth-redis redis
📦 2. Install the Module
# Option A: NPM
npm install @prettygirllz/identity-access
# Option B: Docker
docker pull prettygirllz/identity-access:latest
# Option C: Clone repository
git clone https://github.com/prettygirllz/identity-access.git
cd identity-access && npm install
⚙️ 3. Configuration
Create .env
file:
# Required
MONGO_URI=mongodb://localhost:27017
DB_NAME=auth_dev
JWT_SECRET=your_32char_secure_key_here
ENCRYPTION_KEY=32_char_key_for_field_encryption
# Optional
PORT=3000
GRPC_PORT=50051
RATE_LIMIT=100/15m # 100 requests per 15 minutes
🛠️ 4. Integration (Express Example)
// server.js
const express = require('express');
const iam = require('@prettygirllz/identity-access')({
mongoUri: process.env.MONGO_URI,
jwtSecret: process.env.JWT_SECRET
});
const app = express();
app.use(express.json());
// 4.1 Add Authentication Routes
app.post('/login', async (req, res) => {
try {
const token = await iam.auth.login(req.body.email, req.body.password);
res.json({ token });
} catch (err) {
res.status(401).json({ error: err.message });
}
});
// 4.2 Add Protected Route Middleware
app.get('/profile',
iam.middlewares.authenticate, // JWT verification
(req, res) => {
res.json({ user: req.user }); // User data from JWT
}
);
app.listen(3000, () => console.log('Server running on port 3000'));
🔐 5. User Management
// Create admin user (first-run setup)
const createAdmin = async () => {
await iam.users.create({
email: '[email protected]',
password: 'SecurePass123!',
roles: ['admin'],
metadata: {
name: 'System Admin',
// Encrypted automatically:
ssn: '123-45-6789'
}
});
};
🛡️ 6. Authorization Setup
// config/roles.js
module.exports = {
admin: {
permissions: ['users:create', 'users:delete', 'content:*'],
inherits: ['editor']
},
editor: {
permissions: ['content:create', 'content:edit']
}
};
// In your route:
app.delete('/users/:id',
iam.middlewares.authenticate,
iam.middlewares.authorize('users:delete'),
(req, res) => { /* ... */ }
);
📡 7. gRPC Setup (Optional)
// adapters/grpc/auth.proto
service AuthService {
rpc Login (LoginRequest) returns (AuthResponse);
rpc VerifyToken (TokenRequest) returns (TokenInfo);
}
// Start server
iam.grpc.start(process.env.GRPC_PORT);
🧪 8. Testing
# Unit tests
npm test
# Integration test (requires MongoDB)
curl -X POST http://localhost:3000/login \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"SecurePass123!"}'
# Expected response:
# { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." }
🚀 9. Deployment
# Build Docker image
docker build -t your-registry/identity-access:1.0 .
# Kubernetes example (deployment.yaml)
apiVersion: apps/v1
kind: Deployment
metadata:
name: identity-access
spec:
containers:
- name: auth
image: your-registry/identity-access:1.0
envFrom:
- secretRef:
name: auth-secrets
🔄 10. Maintenance
# Key rotation procedure:
1. Update JWT_SECRET in .env
2. Notify clients to re-authenticate
3. Set old token expiration to 5 minutes during transition
# Monitoring:
- Track failed login attempts
- Monitor token generation rate
- Audit role changes
Key Features Implemented:
-
End-to-End Encryption
- All sensitive fields automatically encrypted in MongoDB
// Example stored document: { email: 'EncryptedBase64String==', ssn: 'EncryptedBase64String==', _keyVersion: 2 // Supports key rotation }
-
Zero-Trust Security Model
- JWT tokens contain minimal claims
- Every request requires re-authorization
- IP-based anomaly detection
-
Multi-Protocol Support
graph LR A[Client] -->|REST| B[Express/Fastify] A -->|gRPC| C[Microservices] B & C --> D[Core Auth] D --> E[MongoDB]
Need additional help? Contact [email protected] for production deployment support.