@mamoorali295/rbac
Version:
Complete RBAC (Role-Based Access Control) system for Node.js with Express middleware, NestJS integration, GraphQL support, MongoDB & PostgreSQL support, modern admin dashboard, TypeScript support, and dynamic permission management
199 lines (198 loc) • 7.8 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PostgresUserRole = void 0;
class PostgresUserRole {
constructor(pool) {
this.pool = pool;
}
create(roleData) {
return __awaiter(this, void 0, void 0, function* () {
const query = `
INSERT INTO rbac_roles (name, description)
VALUES ($1, $2)
RETURNING *
`;
const values = [roleData.name, roleData.description];
const result = yield this.pool.query(query, values);
return result.rows[0];
});
}
findByName(name) {
return __awaiter(this, void 0, void 0, function* () {
const query = 'SELECT * FROM rbac_roles WHERE name = $1';
const result = yield this.pool.query(query, [name]);
return result.rows[0] || null;
});
}
findById(id) {
return __awaiter(this, void 0, void 0, function* () {
const query = 'SELECT * FROM rbac_roles WHERE id = $1';
const result = yield this.pool.query(query, [id]);
return result.rows[0] || null;
});
}
findByIdWithFeatures(id) {
return __awaiter(this, void 0, void 0, function* () {
const query = `
SELECT
r.*,
json_agg(
CASE
WHEN f.id IS NOT NULL THEN
json_build_object(
'feature', json_build_object(
'id', f.id,
'name', f.name,
'description', f.description
),
'permissions', COALESCE(
(
SELECT json_agg(
json_build_object(
'id', p.id,
'name', p.name,
'description', p.description
)
)
FROM rbac_role_feature_permissions rfp2
JOIN rbac_permissions p ON p.id = rfp2.permission_id
WHERE rfp2.role_id = r.id AND rfp2.feature_id = f.id
),
'[]'::json
)
)
ELSE NULL
END
) FILTER (WHERE f.id IS NOT NULL) as features
FROM rbac_roles r
LEFT JOIN rbac_role_feature_permissions rfp ON r.id = rfp.role_id
LEFT JOIN rbac_features f ON rfp.feature_id = f.id
WHERE r.id = $1
GROUP BY r.id, r.name, r.description, r.created_at, r.updated_at
`;
const result = yield this.pool.query(query, [id]);
const row = result.rows[0];
if (!row)
return null;
return {
id: row.id,
name: row.name,
description: row.description,
created_at: row.created_at,
updated_at: row.updated_at,
features: row.features || []
};
});
}
update(id, updates) {
return __awaiter(this, void 0, void 0, function* () {
const setClause = [];
const values = [];
let paramCount = 1;
if (updates.name !== undefined) {
setClause.push(`name = $${paramCount++}`);
values.push(updates.name);
}
if (updates.description !== undefined) {
setClause.push(`description = $${paramCount++}`);
values.push(updates.description);
}
if (setClause.length === 0)
return;
values.push(id);
const query = `
UPDATE rbac_roles
SET ${setClause.join(', ')}, updated_at = CURRENT_TIMESTAMP
WHERE id = $${paramCount}
`;
yield this.pool.query(query, values);
});
}
delete(id) {
return __awaiter(this, void 0, void 0, function* () {
const client = yield this.pool.connect();
try {
yield client.query('BEGIN');
// Delete role-feature-permission relationships
yield client.query('DELETE FROM rbac_role_feature_permissions WHERE role_id = $1', [id]);
// Update users to remove this role
yield client.query('UPDATE rbac_users SET role_id = NULL WHERE role_id = $1', [id]);
// Delete the role
yield client.query('DELETE FROM rbac_roles WHERE id = $1', [id]);
yield client.query('COMMIT');
}
catch (error) {
yield client.query('ROLLBACK');
throw error;
}
finally {
client.release();
}
});
}
assignFeaturePermissions(roleId, featurePermissions) {
return __awaiter(this, void 0, void 0, function* () {
const client = yield this.pool.connect();
try {
yield client.query('BEGIN');
// Remove existing feature permissions for this role
yield client.query('DELETE FROM rbac_role_feature_permissions WHERE role_id = $1', [roleId]);
// Add new feature permissions
for (const fp of featurePermissions) {
for (const permissionId of fp.permission_ids) {
yield client.query('INSERT INTO rbac_role_feature_permissions (role_id, feature_id, permission_id) VALUES ($1, $2, $3)', [roleId, fp.feature_id, permissionId]);
}
}
yield client.query('COMMIT');
}
catch (error) {
yield client.query('ROLLBACK');
throw error;
}
finally {
client.release();
}
});
}
getAll(limit, offset) {
return __awaiter(this, void 0, void 0, function* () {
// Get total count
const countQuery = 'SELECT COUNT(*) FROM rbac_roles';
const countResult = yield this.pool.query(countQuery);
const total = parseInt(countResult.rows[0].count);
// Get roles with pagination
let query = `
SELECT r.*,
COUNT(DISTINCT u.id) as user_count,
COUNT(DISTINCT rfp.feature_id) as feature_count
FROM rbac_roles r
LEFT JOIN rbac_users u ON r.id = u.role_id
LEFT JOIN rbac_role_feature_permissions rfp ON r.id = rfp.role_id
GROUP BY r.id, r.name, r.description, r.created_at, r.updated_at
ORDER BY r.created_at DESC
`;
const params = [];
let paramCount = 1;
if (limit) {
query += ` LIMIT $${paramCount++}`;
params.push(limit);
}
if (offset) {
query += ` OFFSET $${paramCount}`;
params.push(offset);
}
const result = yield this.pool.query(query, params);
return { roles: result.rows, total };
});
}
}
exports.PostgresUserRole = PostgresUserRole;