Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Implement PostFilter to PagingAndSortingRepository?

I'm looking for how to implement a @PostFilter annotation to a PagingAndSortingRepository interface

I created my custom repository class extending

public interface PublishableEntityRepository<T, ID extends Serializable>
        extends PagingAndSortingRepository<T, ID> {
    @PostFilter("hasPermission(filterObject, 'read')")
    Page<T> findAll(Pageable var1);
}

Then created a custom PermissionEvaluator class

public class AccessPermissionEvaluator implements PermissionEvaluator {

    @Override
    public boolean hasPermission(Authentication authentication, Object o, Object o1) {
        boolean hasPermission = false;

        if (authentication != null) {
            User user = (User) authentication.getPrincipal();
            if (((PublishableEntity) o).getStatus().equals(AccessStatus.PUBLISHED)) {
                hasPermission = true;
            }
        }

        return hasPermission;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}

However, an IllegalArgumentException is thrown:

RepositoryRestExceptionHandler - Filter target must be a collection or array type, but was Page 0 of 0 containing UNKNOWN instances

I know that the filterObject in question is a Page class, so how do I filter against the Page contents?

like image 997
John Giotta Avatar asked May 27 '16 15:05

John Giotta


Video Answer


1 Answers

Found answer and it is to use @Query and SpEL with security extentions.

@NoRepositoryBean
public interface PublishableEntityRepository<T, ID extends Serializable>
       extends PagingAndSortingRepository<T, ID> {
    @PostFilter("hasPermission(filterObject, 'read')")
    List<T> findAll();

    @PostAuthorize("hasPermission(returnObject, 'read')")
    T findOne(ID id);

    // where entity.status is PUBLISHED or security SpEL with hasRole
    @Query("select o from #{#entityName} o where o.status = 'PUBLISHED' " +
        "or 1 = ?#{security.hasRole('ROLE_ADMIN') ? 1 : 0}")
    Page<T> findAll(Pageable var1);
}

http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#data-query

like image 180
John Giotta Avatar answered Nov 02 '22 23:11

John Giotta