node-casbin/sequelize-adapter

Calling savePolicy() create duplicates

gbertoncelli opened this issue · 4 comments

I'm using sequelize adapter for creating a persistent implementation of my ACL. As I said in this issue #19 I'm loading from file all the default policy that my system must have. I've noticed that after I've loaded all the infos I need in Caspin and then I call savePolicyin the Postrgre database all the entities get duplicated. This is supposed to work like that with the Auto-Save?

Please show your code.

This is my schema model:

[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && (regEqJollyMatch(r.act, p.act) || actionGroupMatch(r.obj, r.act, p.act))

This is the ACL Manager:

const casbin = require('casbin');
const { SequelizeAdapter } = require('casbin-sequelize-adapter');
const { conf } = require('shared/config');
const { acls } = conf;
const { stream: dbConfig } = conf.db;
const fs = require('fs');
const { resolve, join } = require('path');
const { loadMatchers } = require('./aclMatchers');

const loadAclEnforcer = async function loadAclEnforcer(ctx) {
  let caspinEnforcer;

  try {

    const sequelizeAdapter = await SequelizeAdapter.newAdapter({
      username: dbConfig.user,
      host: dbConfig.host,
      port: dbConfig.port,
      password: dbConfig.pw,
      database: dbConfig.name,
      schema: dbConfig.schema,
      dialect: 'postgres',
      logging: conf.logQuery
    });

    const confPath = resolve(process.cwd(), acls.confPath);
    const policiesDir = resolve(process.cwd(), acls.policiesDir);

    caspinEnforcer = await casbin.newEnforcer(
      confPath,
      sequelizeAdapter
    );

    loadMatchers(ctx, caspinEnforcer);

    let policiesNeedsRefresh = false;

    fs.readdirSync(policiesDir).forEach(filePath => {

      if (!filePath.match(/^(.*)\.acl\.json$/gi)) {
        return;
      }

      const policyPath = join(policiesDir, filePath);
      const policiesGroup = require(policyPath);
      if (policiesGroup && policiesGroup.length > 0) {
        policiesGroup.forEach(async (policy) => {
          let added;
          if (policy[0] === 'g') {
            added = await caspinEnforcer.addNamedGroupingPolicy(...policy);
          } else if (policy[0] === 'p') {
            added = await caspinEnforcer.addNamedPolicy(...policy);
          }
          policiesNeedsRefresh = policiesNeedsRefresh || added;
        });
      }
    });

    // here Casbin duplicates the policies
    await caspinEnforcer.savePolicy();

  } catch (error) {
    ctx.logger.error('An error occurred loading the ACLs.');
    throw error;
  }

  return caspinEnforcer;
};

module.exports = { loadAclEnforcer };

Remove the await caspinEnforcer.savePolicy();

Casbin can automatically save policies.