Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check conditions without instance of class #101

Closed
bertho-zero opened this issue Aug 13, 2018 · 4 comments
Closed

Check conditions without instance of class #101

bertho-zero opened this issue Aug 13, 2018 · 4 comments
Labels

Comments

@bertho-zero
Copy link

How is it possible to check abilities with conditions and without instance of class?

One can either pass a string of characters (example: 'Post'), or a class instance where the name of the subject is extracted from the constructor.

How to test an object that is not an instance?

@stalniy
Copy link
Owner

stalniy commented Aug 13, 2018

Would be better to ask questions in gitter chat. Recently such case was discussed.

There are at least 4 ways to handle this :)

  • create a temporary model instance with prefilled attrs
  • add rules on Object subject
  • rethink what you actually want to check (usually it comes up that you want to check the request parameters and the model)
  • define a custom subjectName function which can map your object to required model
const ability = new Ability(abilityArray, {
    subjectName(subject) {
      if (subject && subject.subjectType) {
        return subject.subjectType;
      }
    }
  });

  const authSettings = {
    subjectType: 'Post',
    tenant_id,
  };

  const abilityCan = ability.can('read', authSettings);

If doesn't fit your needs, please describe your usecase in details

@bertho-zero
Copy link
Author

Thank you, I'm using a variant that defines a non-enumerable property:

const SUBJECT_NAME = Symbol('casl/subjectName');

const abilitySubject = (subjectName, object) => {
  Object.defineProperty(object, SUBJECT_NAME, {
    value: subjectName,
    configurable: true,
    writable: true
  });

  return object;
};

const ability = new Ability(abilityArray, {
  subjectName(subject) {
    if (subject && subject[ SUBJECT_NAME ]) {
      return subject[ SUBJECT_NAME ];
    }
  }
});

const authSettings = {
  tenant_id,
};

const abilityCan = ability.can('read', abilitySubject('Post', authSettings));

@stalniy
Copy link
Owner

stalniy commented Aug 14, 2018

Nice!

@omidh28
Copy link

omidh28 commented Mar 7, 2022

Any changes to this problem lately? Because those solutions seems very hacky 👎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants