Skip to content

Commit

Permalink
Added model's ownership
Browse files Browse the repository at this point in the history
  • Loading branch information
santigarcor committed Sep 24, 2016
1 parent 901cafc commit 5b30af7
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
15 changes: 15 additions & 0 deletions docs/usage/concepts.rst
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,18 @@ The ``Laratrust`` class has a shortcut to ``ability()`` for the currently logged
// is identical to
Auth::user()->ability('admin,owner', 'create-post,edit-user');
Model's Ownership
^^^^^^^^^^^^^^^^^

If you need to check if the user owns a model you can use the user function ``owns``:

.. code-block:: php
public function update (Post $post) {
if ($user->owns($post)) {
abort(403);
}
...
}
12 changes: 12 additions & 0 deletions src/Laratrust/Traits/LaratrustUserTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,18 @@ public function detachRoles($roles = null)
return $this;
}

/**
* Checks if the user owns the thing
* @param Model $thing
* @return boolean
*/
public function owns($thing)
{
$foreignKeyName = snake_case(get_class($this). 'Id');

return $thing->$foreignKeyName == $this->getKey();
}

/**
* This scope allows to retrive users with an specific role
* @param Illuminate\Database\Eloquent\Builder $query
Expand Down
13 changes: 13 additions & 0 deletions tests/LaratrustUserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1102,6 +1102,19 @@ public function testDetachAllRoles()

}

function testUserOwnsaPostModel()
{
$user = m::mock('HasRoleUser')->makePartial();
$post = new stdClass();
$post->mockery_11__has_role_user_id = $user->getKey();

$post2 = new stdClass();
$post2->mockery_11__has_role_user_id = 9;

$this->assertTrue($user->owns($post));
$this->assertFalse($user->owns($post2));
}

protected function mockPermission($permName)
{
$permMock = m::mock('Laratrust\Permission');
Expand Down

0 comments on commit 5b30af7

Please sign in to comment.