johnny 5
johnny 5

Reputation: 20995

Db Generic Resource Authorization

I'm trying to figure out how to dynamically authorize my context based on a role.

public interface IConstraintResolver
{
    Expression<Func<TEntity, bool>>[] GetConstraintsForTypeByRole<TEntity>() 
        where TEntity : class;
}
public class AuthorizationContext : DbContext
{
    protected IConstraintResolver _constraintResolver;
    public AuthorizationContext(IConstraintResolver constraintResolver)
    {
        this._constraintResolver = constraintResolver;
    }

    public override DbSet<TEntity> Set<TEntity>()
    {
        var defaultSet = base.Set<TEntity>();

        var constraints = this._constraintResolver.GetConstraintsForTypeByRole<TEntity>();

        var filteredSet = base.Set<TEntity>().AsQueryable();

        foreach(var constraint in constraints)
        {
            filteredSet = filteredSet.Where(constraint);
        }

        //how do I apply this back to the innerQueryable
        return filteredSet;
    }
}

My issue is that after applying my queryable how can I make this the default queryable for the Set.

I found a gyst which works with the old DbSet here

But .Net Core does not contain IDBSet

How can I create a custom dbset, or How can I filter the existing dbSet?

Upvotes: 0

Views: 78

Answers (1)

Slava Utesinov
Slava Utesinov

Reputation: 13488

There is better approach via global filters:

public class AuthorizationContext : DbContext
{
    static AuthorizationContext()
    {
         QueryFilterManager.Filter<Orders>(q => q.Where(x => x.Price <= 5000));
    }

    public AuthorizationContext()
    {
         QueryFilterManager.InitilizeGlobalFilter(this);
    }
}

Upvotes: 1

Related Questions