gov_auth_logging_lib
Version:
logging library for cerbos
107 lines (84 loc) • 3.17 kB
JavaScript
require("reflect-metadata");
const jwt = require('jsonwebtoken');
class EndpointLogger {
constructor(options) {
this.options = {
excludePaths: [],
includeMetadata: false,
...options
};
this.logRepository = options.dataSource.getRepository('LogEntry');
}
logActivity() {
return async (req, res, next) => {
// Skip logging for excluded paths
if (this.options.excludePaths?.includes(req.path)) {
return next();
}
try {
// Extract the Bearer token from the Authorization header
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Bearer <token>
let userId = 'anonymous';
if (token) {
// Decode the token (assuming it's a JWT)
const decoded = jwt.decode(token); // You can also use jwt.verify if you have a secret
if (decoded && decoded.userId) {
userId = decoded.userId;
}
}
const logEntry = {
path: req.url,
method: req.method,
userId: userId, // Use the extracted userId
ip: req.ip || "192.168.0.1", // Use the actual IP from the request
userAgent: req.headers['user-agent'] || 'unknown'
};
if (this.options.includeMetadata) {
logEntry.metadata = {
query: req.query,
headers: req.headers,
body: req.body
};
}
await this.logRepository.save(logEntry);
} catch (error) {
console.error('Error saving log entry:', error);
}
next();
};
}
async getLogs(options = {}) {
const query = this.logRepository.createQueryBuilder('log');
if (options.userId) {
query.andWhere('log.userId = :userId', { userId: options.userId });
}
if (options.path) {
query.andWhere('log.path = :path', { path: options.path });
}
if (options.startDate) {
query.andWhere('log.timestamp >= :startDate', { startDate: options.startDate });
}
if (options.endDate) {
query.andWhere('log.timestamp <= :endDate', { endDate: options.endDate });
}
if (options.skip) {
query.skip(options.skip);
}
if (options.take) {
query.take(options.take);
}
query.orderBy('log.timestamp', 'DESC');
return query.getMany();
}
async clearLogs() {
return this.logRepository.clear();
}
async getLogsByUser(userId) {
return this.getLogs({ userId });
}
async getLogsByDateRange(startDate, endDate) {
return this.getLogs({ startDate, endDate });
}
}
module.exports = EndpointLogger;