UNPKG

@rbac/rbac

Version:

Blazing Fast, Zero dependency, Hierarchical Role-Based Access Control for Node.js

57 lines (56 loc) 2.39 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MySQLRoleAdapter = void 0; let mysql; function loadMySQL() { if (!mysql) { try { mysql = require('mysql2/promise'); } catch (err) { throw new Error('Please install "mysql2" to use MySQLRoleAdapter'); } } return mysql; } class MySQLRoleAdapter { constructor(options) { this.options = options; this.defaultTenant = 'default'; this.options.columns = { name: 'name', role: 'role', tenantId: 'tenant_id', ...this.options.columns }; } async getConnection() { if (!this.connection) { const driver = loadMySQL(); this.connection = this.options.uri ? await driver.createConnection(this.options.uri) : await driver.createConnection(this.options.config || {}); } return this.connection; } async getRoles(tenantId) { const conn = await this.getConnection(); const cols = this.options.columns; const [rows] = await conn.query(`SELECT \`${cols.name}\`, \`${cols.role}\` FROM \`${this.options.table}\` WHERE \`${cols.tenantId}\` = ?`, [tenantId !== null && tenantId !== void 0 ? tenantId : this.defaultTenant]); return rows.reduce((acc, row) => { acc[row[cols.name]] = JSON.parse(row[cols.role]); return acc; }, {}); } async addRole(roleName, role, tenantId) { const conn = await this.getConnection(); const cols = this.options.columns; await conn.query(`INSERT INTO \`${this.options.table}\` (\`${cols.name}\`, \`${cols.role}\`, \`${cols.tenantId}\`) VALUES (?, ?, ?)`, [roleName, JSON.stringify(role), tenantId !== null && tenantId !== void 0 ? tenantId : this.defaultTenant]); } async updateRoles(roles, tenantId) { const conn = await this.getConnection(); const cols = this.options.columns; await Promise.all(Object.entries(roles).map(([name, role]) => conn.query(`REPLACE INTO \`${this.options.table}\` (\`${cols.name}\`, \`${cols.role}\`, \`${cols.tenantId}\`) VALUES (?, ?, ?)`, [name, JSON.stringify(role), tenantId !== null && tenantId !== void 0 ? tenantId : this.defaultTenant]))); } } exports.MySQLRoleAdapter = MySQLRoleAdapter;