class IsRecipientOwnPermissionArgumentVoter extends BasicObjectPermissionArgumentVoter {

    @Override
    protected boolean isPermitted(Authentication authentication, ObjectPermission objectPermission, Object object) {
        boolean res = false;
        if (objectPermission.getPermissionRecipient() instanceof User){
            User recipient = (User)objectPermission.getPermissionRecipient();
            User user = (User)authentication.getPrincipal();
            res = (recipient.getUsername() == user.getUsername() || (recipient.getUsername() != null && recipient.getUsername().equals(user.getUsername()))) &&
                  (recipient.getTenantId() == user.getTenantId() || (recipient.getTenantId() != null && recipient.getTenantId().equals(user.getTenantId())));
        } else
        if (objectPermission.getPermissionRecipient() instanceof Role){
            Role recipient = (Role)objectPermission.getPermissionRecipient();
            final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

            for (GrantedAuthority authority : authorities){
                String name = authority.getAuthority();
                String tenantId = authority instanceof TenantQualified ? ((TenantQualified)authority).getTenantId() : null;

                if (name.equals(recipient.getRoleName()) && (tenantId == recipient.getTenantId() || (tenantId != null && tenantId.equals(recipient.getTenantId())))){
                    res = true;
                    break;
                }
            }
        }

        return res;
    }

}