Skip to content

Commit

Permalink
Add filterable field for preventing security issues
Browse files Browse the repository at this point in the history
  • Loading branch information
n7olkachev committed Aug 25, 2017
1 parent 3db021d commit 1d92e0e
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Exceptions/FilterableException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace N7olkachev\LaravelFilterable\Exceptions;

class FilterableException extends \Exception
{

}
13 changes: 13 additions & 0 deletions src/Filterable.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,17 @@

namespace N7olkachev\LaravelFilterable;

use N7olkachev\LaravelFilterable\Exceptions\FilterableException;

trait Filterable
{
public function scopeFilter($query, array $filterData = [])
{
foreach ($filterData as $key => $value) {
if (!$this->isFilterable($key)) {
throw new FilterableException("[$key] is not allowed for filtering");
}

if (is_null($value) || $value === '') continue;

$scopeName = ucfirst(camel_case($key));
Expand All @@ -20,4 +26,11 @@ public function scopeFilter($query, array $filterData = [])
}
}
}

protected function isFilterable($key)
{
$filterable = $this->filterable ?: [];

return in_array($key, $filterable);
}
}
8 changes: 8 additions & 0 deletions tests/FilterableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace N7olkachev\LaravelFilterable\Test;

use Carbon\Carbon;
use N7olkachev\LaravelFilterable\Exceptions\FilterableException;
use N7olkachev\LaravelFilterable\Test\Models\Page;

class FilterableTest extends TestCase
Expand Down Expand Up @@ -45,4 +46,11 @@ public function it_works_for_arrays()
$pages = Page::filter(['title' => ['Third page']])->get();
$this->assertEquals($pages->count(), 0);
}

/** @test */
public function it_throws_on_not_allowed_field()
{
$this->expectException(FilterableException::class);
Page::filter(['foobar' => 'foo']);
}
}
5 changes: 5 additions & 0 deletions tests/Models/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ class Page extends Model
'created_at',
];

protected $filterable = [
'title',
'created_after'
];

public function scopeCreatedAfter($query, $time)
{
return $query->where('created_at', '>', $time);
Expand Down

0 comments on commit 1d92e0e

Please sign in to comment.