Skip to content

Instantly share code, notes, and snippets.

@lazychaser
Created October 2, 2015 06:34
Show Gist options
  • Select an option

  • Save lazychaser/69e061bd35693a6d1b7e to your computer and use it in GitHub Desktop.

Select an option

Save lazychaser/69e061bd35693a6d1b7e to your computer and use it in GitHub Desktop.
<?php
namespace App\Backend;
use App\Components\Core\User;
use Illuminate\Contracts\Auth\Authenticatable;
use Kalnoy\Cruddy\BaseForm;
use Kalnoy\Cruddy\Contracts\Permissions as PermissionsContract;
use Kalnoy\Cruddy\Entity;
use Illuminate\Config\Repository;
use Request;
/**
* Cruddy permissions provider.
*/
class Permissions implements PermissionsContract {
/**
* @var Authenticatable
*/
protected $user;
/**
* @var Repository
*/
protected $config;
/**
* Permissions constructor.
*
* @param Authenticatable $user
* @param Repository $config
*/
public function __construct($user, Repository $config)
{
$this->user = $user;
$this->config = $config;
}
/**
* @return null|string
*/
public function role()
{
if (in_array(Request::getClientIp(), $this->getRootIps())) return User::ROLE_ADMIN;
return $this->user ? $this->user->role : null;
}
/**
* @param string $action
* @param BaseForm $entity
*
* @return bool
*/
public function isPermitted($action, BaseForm $entity)
{
if ( ! $this->isPermittedByRole($entity->getId()))
{
return false;
}
if ($action !== Entity::READ && $this->isReadOnly($entity->getId()))
{
return false;
}
return true;
}
/**
* Get whether entity is permitted by role.
*
* @param string $entity
*
* @return bool
*/
public function isPermittedByRole($entity)
{
switch ($this->role())
{
case User::ROLE_ADMIN: return true;
case User::ROLE_MODERATOR: return ! in_array($entity, $this->getRootEntities());
}
return false;
}
/**
* Get whether the entity is read-only.
*
* @param string $entity
*
* @return bool
*/
public function isReadOnly($entity)
{
return in_array($entity, $this->getReadOnlyEntities());
}
/**
* Get entities modifiable only by an administrator.
*
* @return array
*/
public function getRootEntities()
{
return $this->config->get('cruddy.root_entities', []);
}
/**
* Get a list of read-only entities.
*
* @return array
*/
public function getReadOnlyEntities()
{
return $this->config->get('cruddy.read_only', []);
}
/**
* Get a list of root users.
*
* @return array
*/
public function getRootIps()
{
return $this->config->get('cruddy.root_ips', []);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment