@rbac/rbac
Version:
Blazing Fast, Zero dependency, Hierarchical Role-Based Access Control for Node.js
61 lines (60 loc) • 2.25 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MongoRoleAdapter = void 0;
let MongoClient;
function loadMongoClient() {
if (!MongoClient) {
try {
MongoClient = require('mongodb').MongoClient;
}
catch (err) {
throw new Error('Please install "mongodb" to use MongoRoleAdapter');
}
}
return MongoClient;
}
class MongoRoleAdapter {
constructor(options) {
this.options = options;
this.defaultTenant = 'default';
const Mongo = loadMongoClient();
this.client = new Mongo(options.uri);
this.collectionName = options.collection;
this.options.columns = {
name: 'name',
role: 'role',
tenantId: 'tenantId',
...this.options.columns
};
}
async getCollection() {
if (!this.db) {
await this.client.connect();
this.db = this.client.db(this.options.dbName);
}
return this.db.collection(this.collectionName);
}
async getRoles(tenantId) {
const col = await this.getCollection();
const cols = this.options.columns;
const docs = await col
.find({ [cols.tenantId]: tenantId !== null && tenantId !== void 0 ? tenantId : this.defaultTenant })
.toArray();
return docs.reduce((acc, doc) => ({ ...acc, [doc[cols.name]]: doc[cols.role] }), {});
}
async addRole(roleName, role, tenantId) {
const col = await this.getCollection();
const cols = this.options.columns;
await col.insertOne({
[cols.name]: roleName,
[cols.role]: role,
[cols.tenantId]: tenantId !== null && tenantId !== void 0 ? tenantId : this.defaultTenant
});
}
async updateRoles(roles, tenantId) {
const col = await this.getCollection();
const cols = this.options.columns;
await Promise.all(Object.entries(roles).map(([name, role]) => col.updateOne({ [cols.name]: name, [cols.tenantId]: tenantId !== null && tenantId !== void 0 ? tenantId : this.defaultTenant }, { $set: { [cols.role]: role } }, { upsert: true })));
}
}
exports.MongoRoleAdapter = MongoRoleAdapter;