node-casbin / typeorm-adapter Goto Github PK
View Code? Open in Web Editor NEWTypeORM adapter for Casbin
Home Page: https://github.com/casbin/node-casbin
License: Apache License 2.0
TypeORM adapter for Casbin
Home Page: https://github.com/casbin/node-casbin
License: Apache License 2.0
(node:42385) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:42385) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Hi.
The following code doesn't delete the policies:
const policies: any[] = await this.enforcer.getFilteredPolicy(0,role, tenant, product);
for (const policy of policies) {
await this.enforcer.removePolicy(policy);
}
await this.enforcer.savePolicy();
('policies' are found, array not empty).
However if I change the code to use 'removePolicies', it is working as expected:
const policies: any[] = await this.enforcer.getFilteredPolicy(0,role, tenant, product);
await this.enforcer.removePolicies(policies);
await this.enforcer.savePolicy();
I'm using typeorm with PG DB.
The latest node-casbin starts to support batch operation, can someone add the support for this adapter?
I am using nestjs and install casbin and typeorm-adapter v1.2.0. I am facing below issue.
Error: AlreadyHasActiveConnectionError: Cannot create a new connection named "node-casbin-official", because connection with such name already exist and it now has an active connection session
Node version: 12.0.0
My code is:
Filename: main.ts
import { authz } from './auth-module/authorization.middleware';
async function bootstrap(): Promise<void> {
app.use(authz(async () => {
const adapter = await TypeORMAdapter.newAdapter(configService.getTypeOrmAdapter());
const e = await newEnforcer('/var/www/html/avantha-audit-pro-api/src/casbin_conf/rbac_model.conf', adapter);
// Load the policy from DB.
await e.loadPolicy();
return e;
}));
}
bootstrap();
Filename:authorization.middleware.ts
import { Enforcer, newEnforcer } from 'casbin';
import TypeORMAdapter from 'typeorm-adapter';
export class BasicAuthorizer {
private req: any;
private enforcer: any;
constructor(req, enforcer) {
this.req = req;
this.enforcer = enforcer;
}
getUserRole() {
const { user } = this.req;
if(typeof user !== 'undefined'){
const { role } = user;
return role;
}
return true;
}
checkPermission() {
const { req, enforcer } = this;
const { originalUrl: path, method } = req;
const userRole = this.getUserRole();
if (userRole){
return enforcer.enforce(userRole, path, method);
}
return true;
}
}
// the authorizer middleware
export function authz(newEnforcer: () => Promise<Enforcer>) {
return async (req, res, next) => {
const enforcer = await newEnforcer();
// user sample
//req.user = { role: 'admin' };
if (!(enforcer instanceof Enforcer)) {
res.status(500).json({ 500: 'Invalid enforcer' });
return;
}
const authorizer = new BasicAuthorizer(req, enforcer);
if (!authorizer.checkPermission()) {
res.status(403).json({ 403: 'Forbidden' });
return;
}
next();
}
};
Please help me to solve this issue.
Hi there,
Thanks for an awesome library!
Just a quick thought. Noticed in the src that a policy can only have up to 6 arguments (v0, v1, v2, v3, v4, v5) - https://github.com/node-casbin/typeorm-adapter/blob/master/src/casbinRule.ts#L18
We're using 7 for our Casbin implementation.
Is there any chance we could perhaps increase the number of arguments you can persist in the database?
Thanks!
how can i use the ExistentConnection?
const conn = getConnection();
const adapter = await TypeORMAdapter.newAdapter({
connection: conn,
});
but i got No metadata for "CasbinRule" was found.
please help me, thanks!
master
branch failed. 🚨I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.
You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.
Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.
Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master
branch. You can also manually restart the failed CI job that runs semantic-release.
If you are not sure how to resolve this, here are some links that can help you:
If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.
The npm token configured in the NPM_TOKEN
environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/
.
If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.
Please make sure to set the NPM_TOKEN
environment variable in your CI with the exact value of the npm token.
Good luck with your project ✨
Your semantic-release bot 📦🚀
Error while creating a new adapter with mysql example.
index.js
const TypeORMAdapter = require("typeorm-adapter");
run = async () => {
const a = await TypeORMAdapter.newAdapter({
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "",
database: "casbin"
});
};
run();
error
(node:6286) UnhandledPromiseRejectionWarning: TypeError: TypeORMAdapter.newAdapter is not a function
at run (/home/david/Documents/projects/casbin-node/index.js:4:34)
at Object.<anonymous> (/home/david/Documents/projects/casbin-node/index.js:14:1)
at Module._compile (internal/modules/cjs/loader.js:936:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
at Module.load (internal/modules/cjs/loader.js:790:32)
at Function.Module._load (internal/modules/cjs/loader.js:703:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:999:10)
at internal/main/run_main_module.js:17:11
(node:6286) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:6286) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Is it possible to create adapter and set the custom database table name? (it defaults to casbin_rule)
It works fine on my Ubuntu laptop, but while I move to deepin, I got a strange error message while all the dependencies have been correctly installed and the connection between the host and the postgres database is ok.
Here what I got while I just cloned this repo and changed the options:
code
const a = await TypeORMAdapter.newAdapter({
type: 'postgres',
host: '127.0.0.1',
port: 5432,
username: 'test',
password: 'test2019',
database: 'test',
});
error message
while executing npm run test
QueryFailedError: column cnst.consrc does not exist
TypeORM adapter fails with ACL model:
198 | // if (astMap) {
199 | // @ts-ignore
> 200 | for (const [ptype, ast] of astMap) {
| ^
201 | for (const rule of ast.policy) {
202 | const line = this.savePolicyLine(ptype, rule);
203 | lines.push(line);
use as example,just add in middleware, but get a nodejs.TypeError
nodejs.TypeError: this.adapter.loadPolicy is not a function
at Enforcer.<anonymous> (E:\workSpace\typeorm_test\node_modules\casbin\lib\coreEnforcer.js:140:32)
Once I want to delete filtered policies and skip some columns I will do something like that
[
[alice, data, read],
[alice, data1, read],
[alice, data1, write]
]
enforcer.removeFilteredPolicy(0, 'alice', '', 'read')
so I expect those policies to be deleted
[alice, data, read],
[alice, data1, read],
await this.getRepository().delete({
...line,
});
on that line, typeorm adapter makes a deletion of policies
the line
looks like this
{
v0: 'alice',
v1: '',
v2: 'read'
}
as a result, rows won't be deleted because there is no rows for which v1 = ''
Hi Team,
I'm calling the loadFilteredPolicy() on TypeORM-Adapter (which return boolean true) and able to filter the policies.
await e.loadFilteredPolicy({
ptype: 'p',
v0: 'alice'
});
There is a printPolicy() in model.js of casbin which prints the filtered policies perfectly.
printPolicy() {
log_1.logPrint('Policy:');
this.model.forEach((map, key) => {
if (key === 'p' || key === 'g') {
map.forEach(ast => {
log_1.logPrint(`key, : ${ast.value}, : , ${ast.policy}`);
console.log(`key, : ${ast.value}, : , ${ast.policy}`); /// added to print on console.
});
}
});
}
I need to understand if I can use any existing method (if there is any) right after loadFilteredPolicy() (something similar to printPolicy()) which can return me all the filtered policies from database (for e.g. alice,data1,read) .
Can you please advise on how to get that from the enforcer object or using any existing method?
Would really appreciate your assistance here.
Thank you
A common practice in building stateful apps is to reuse the same database connection across different functionalities, e.g. logging, authentication, authorisation, etc.
An intuitive approach to ensure that all modules have the same database connection is to initialize the connection somewhere outside of all other modules and to pass the one connection object to them.
However the TypeORMAdapter.newAdapter
, as stated in the README, only receives the connection options. It would be nice and more consistent with other modules if it can accept the connection object instead.
I have notice this error when trying to run typeorm with "dropSchema" option set to true. I usually just stop the app and start it again and the error disappears. Is there any way to prevent this?
I added casbin typeorm-adapter into my existing project which has already a typeorm mssql conenction. An error occured: "No repository for "CasbinRule" was found. Looks like this entity is not registered in current "default" connection?" Please help me or give some solutions. Thank you so much!
Hi all,
This TypeORMAdapter supports FilteredAdapter however not sure why I'm getting below error : -
Error: filtered policies are not supported by this adapter
message:"filtered policies are not supported by this adapter"
stack:"Error: filtered policies are not supported by this adapter
at Enforcer.<anonymous> (/var/task/node_modules/casbin/lib/coreEnforcer.js:159:23)
at Generator.next (<anonymous>)
at /var/task/node_modules/casbin/lib/coreEnforcer.js:21:71
at new Promise (<anonymous>)
at /var/task/node_modules/casbin/lib/coreEnforcer.js:17:12
at Enforcer.loadFilteredPolicy (/var/task/node_modules/casbin/lib/coreEnforcer.js:153:16)
at /var/task/src/loadPermissions.js:35:24
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async Runtime.handler (/var/task/index.js:15:22)"
__proto__:Object {constructor: , name: "Error", message: "", …}
Below is my code: -
'use-strict';
const { newEnforcer } = require('casbin');
const TypeORMAdapter = require('typeorm-adapter');
const { updateCache } = require('./cache-manager/cacheService');
const MODEL = process.env.MODEL || './enforcer/casbin_conf/model.conf';
const { join } = require('path');
module.exports.loadPermissions = async (event, context, callback, logger) => {
let key = null;
if (event.queryStringParameters && event.queryStringParameters.key) {
console.log("Received key: " + event.queryStringParameters.key);
key = event.queryStringParameters.key;
}
const a = await TypeORMAdapter.default.newAdapter({
type: 'mysql',
host: '192.168.1.5',
port: 3306,
username: 'root',
password: '',
database: 'casbin',
});
//a.enabledFiltered(true);
const e = await newEnforcer(join(__dirname, MODEL), a);
// Load the filtered policy from DB.
const fp = await e.loadFilteredPolicy({
'ptype': 'p',
'v0': 'alice'
});
const policies = { "v0": "p", "v1": "admin", "v2": "/*", "v3": "GET" }; //temp code only
return await updateCache(key, policies, logger);
};
I get error whenever I call this method loadFilteredPolicy(). Secondly, I would like to know why the method loadFilteredPolicy(filter) is getting called which is there on CoreEnforcer class. I want to invoke the loadFilteredPolicy(model, filter) which is there on TypeORMAdapter.
Please assist me here.
Thank you
hello, I found that I'm able to save a policy by using:
await e.addPolicy('admin', 'domain1', '/data0', '*');
but how can I put a user in this group (admin of domain1
)?
config.default.js:
config.middleware = ['user','authz'];
config.authz = {
enable: true,
newEnforcer: async() => {
const dbConnect = await TypeORMAdapter.newAdapter({
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "123456",
"database": "casbin"
});
const enforcer = await casbin.newEnforcer('authz_model.conf', dbConnect);
return enforcer
}
}
use .csv is ok,but use database get error when HTTP request more than one time.
ERROR:nodejs.AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session
Hi, I updated to 1.5 after this PR and it seems like there is a huge perf regression in this framework.
I'm essentially doing this:
enforcer = await newEnforcer(join(__dirname, '../model.conf'), this.adapter);
await enforcer.addNamedMatchingFunc(GROUP_TYPE, globMatch);
await enforcer.addNamedDomainMatchingFunc(GROUP_TYPE, globMatch);
await enforcer.loadFilteredPolicy({
v0: subjectIdentifier, // load only what's needed for this user
});
const roles = await enforcer.getRolesForUser(subjectIdentifier);
await Promise.all(roles.map(async (role) => enforcer?.loadIncrementalFilteredPolicy({ v0: role })));
Then when I call enforcer.enforce(subjectIdentifier, domain, object, action);
the process hangs.
For more context, I have ~5500 policies + groups but it should be able to handle that.
I know that many of the patterns in the new TypeORM have moved away from the singleton patterns like getRepository
and other helper functions. I think you need to work with the Typeorm connection instance instead of using helpers like this - https://github.com/node-casbin/typeorm-adapter/blob/master/src/adapter.ts#L115
Running, simple npm install return a dependency error
$ npm install --save @auth/typeorm-adapter
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/mssql
npm ERR! peerOptional mssql@"^6.2.1 || 7" from @auth/[email protected]
npm ERR! node_modules/@auth/typeorm-adapter
npm ERR! @auth/typeorm-adapter@"*" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peerOptional mssql@"^9.1.1" from [email protected]
npm ERR! node_modules/typeorm
npm ERR! peer typeorm@"^0.3.7" from @auth/[email protected]
npm ERR! node_modules/@auth/typeorm-adapter
npm ERR! @auth/typeorm-adapter@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /home/guy/.npm/eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/guy/.npm/_logs/2023-09-14T08_18_52_437Z-debug-0.log
Could you publish the latest version (v1.3.0) to npm?
Thanks
I am using typeorm-adapter
with a Mongo database as a backend.
I am then simply adding a new permission for a user:
enforcer.addPermissionForUser('userId', 'objectId', 'action');
While the permission is created in the database, TypeORM's Mongo adapter throws an exception:
[0] TypeError: Cannot read property 'createValueMap' of undefined
[0] at MongoDriver.createGeneratedMap (/Users/.../uApp/packages/uapp-backend/node_modules/typeorm/driver/mongodb/MongoDriver.js:286:40)
[0] at /Users/.../uApp/packages/uapp-backend/node_modules/typeorm/entity-manager/MongoEntityManager.js:200:79
[0] at Array.forEach (<anonymous>)
[0] at MongoEntityManager.<anonymous> (/Users/.../uApp/packages/uapp-backend/node_modules/typeorm/entity-manager/MongoEntityManager.js:198:61)
[0] at step (/Users/.../uApp/packages/uapp-backend/node_modules/tslib/tslib.js:136:27)
[0] at Object.next (/Users/.../uApp/packages/uapp-backend/node_modules/tslib/tslib.js:117:57)
[0] at fulfilled (/Users/.../uApp/packages/uapp-backend/node_modules/tslib/tslib.js:107:62)
[0] at processTicksAndRejections (internal/process/task_queues.js:93:5)
The problem seems to be that CasbinRule
has no ObjectID
-annotated property. When I change the declaration of id
to
@ObjectIdColumn()
public id: ObjectID;
, everything works fine.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.