Git Product home page Git Product logo

typeorm-adapter's People

Contributors

andrienkoaleksandr avatar anthrax63 avatar anton-fomichev avatar dependabot[bot] avatar divy9881 avatar fchristl avatar hariprasadiit avatar harveyappleton avatar hsluoyz avatar jkalberer avatar nodece avatar reinaldooli avatar selflocking avatar shivansh-yadav13 avatar skipperq avatar vinod827 avatar voile-source avatar xianjiezh avatar zxilly avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

typeorm-adapter's Issues

RESOLVE unable to resolve dependency tree

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

typeORM.newAdapter is not a function

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.

TypeORM adapter fails with ACL model

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);

AlreadyHasActiveConnectionError issue in nestjs

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.

"TypeError: Cannot read property 'createValueMap' of undefined" when trying to store a new permission in MongoDB

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.

QueryFailedError: column cnst.consrc does not exist

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

use ExistentConnection

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!

v1.5 Performance regression

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

Promise Error

(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.

removePolicy not working

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 automated release is failing 🚨

🚨 The automated release from the 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.


Invalid npm token.

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 📦🚀

use database replace .csv get error:nodejs.AlreadyHasActiveConnectionError

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

this.adapter.loadPolicy is not a function

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)

batch operation support

The latest node-casbin starts to support batch operation, can someone add the support for this adapter?

Custom database table name

Is it possible to create adapter and set the custom database table name? (it defaults to casbin_rule)

[feat] pass connection object to newAdapter

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.

casbin_rule does not exist

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?

Any existing function to retrieve filtered policies

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

Error: filtered policies are not supported by this adapter

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

No repository for "CasbinRule" was found.

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!

[bug] removeFilteredPolicy is not working properly

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 = ''

assign role, domain to user

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)?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.