Skip to content

Commit

Permalink
Merge pull request #135 from mostafamaklad/v5.0
Browse files Browse the repository at this point in the history
V5.0
  • Loading branch information
mostafamaklad authored Jul 1, 2022
2 parents 1078fcf + b433f23 commit 30e1b4a
Show file tree
Hide file tree
Showing 27 changed files with 289 additions and 227 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
vendor/
build/
composer.lock
.idea/
*.DS_Store
.phpunit.result.cache
9 changes: 5 additions & 4 deletions src/Commands/CreatePermission.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
namespace Maklad\Permission\Commands;

use Illuminate\Console\Command;
use Maklad\Permission\Contracts\PermissionInterface as Permission;
use function app;
use function config;

/**
* Class CreatePermission
Expand All @@ -17,15 +18,15 @@ class CreatePermission extends Command

protected $description = 'Create a permission';

public function handle(): void
public function handle()
{
$permissionClass = \app(\config('permission.models.permission'));
$permissionClass = app(config('permission.models.permission'));

$permission = $permissionClass::create([
'name' => $this->argument('name'),
'guard_name' => $this->argument('guard')
]);

$this->info("Permission `{$permission->name}` created");
$this->info("Permission `$permission->name` created");
}
}
11 changes: 6 additions & 5 deletions src/Commands/CreateRole.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
namespace Maklad\Permission\Commands;

use Illuminate\Console\Command;
use Maklad\Permission\Contracts\RoleInterface as Role;
use function app;
use function config;

/**
* Class CreateRole
Expand All @@ -18,9 +19,9 @@ class CreateRole extends Command

protected $description = 'Create a role';

public function handle(): void
public function handle()
{
$roleClass = \app(\config('permission.models.role'));
$roleClass = app(config('permission.models.role'));

$name = $this->argument('name');
$guard = $this->argument('guard');
Expand All @@ -31,10 +32,10 @@ public function handle(): void
'guard_name' => $guard
]);

$this->info("Role `{$role->name}` created");
$this->info("Role `$role->name` created");

$role->givePermissionTo($permissions);
$permissionsStr = $role->permissions->implode('name', '`, `');
$this->info("Permissions `{$permissionsStr}` has been given to role `{$role->name}`");
$this->info("Permissions `$permissionsStr` has been given to role `$role->name`");
}
}
4 changes: 1 addition & 3 deletions src/Contracts/PermissionInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Maklad\Permission\Contracts;

use Jenssegers\Mongodb\Relations\BelongsToMany;
use Maklad\Permission\Exceptions\PermissionDoesNotExist;

/**
Expand All @@ -13,9 +12,8 @@ interface PermissionInterface
{
/**
* A permission can be applied to roles.
* @return BelongsToMany
*/
public function roles(): BelongsToMany;
public function rolesQuery();

/**
* Find a permission by its name.
Expand Down
4 changes: 1 addition & 3 deletions src/Contracts/RoleInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Maklad\Permission\Contracts;

use Jenssegers\Mongodb\Relations\BelongsToMany;
use Maklad\Permission\Exceptions\RoleDoesNotExist;

/**
Expand All @@ -13,9 +12,8 @@ interface RoleInterface
{
/**
* A role may be given various permissions.
* @return BelongsToMany
*/
public function permissions(): BelongsToMany;
public function permissionsQuery();

/**
* Find a role by its name and guard name.
Expand Down
13 changes: 7 additions & 6 deletions src/Directives/PermissionDirectives.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Maklad\Permission\Directives;

use Illuminate\View\Compilers\BladeCompiler;
use function explode;

/**
* Class PermissionDirectives
Expand All @@ -25,7 +26,7 @@ public function roleDirective(): void
$this->bladeCompiler->directive('role', function ($arguments) {
list($role, $guard) = $this->extractRoleGuard($arguments);

return "<?php if(auth({$guard})->check() && auth({$guard})->user()->hasRole({$role})): ?>";
return "<?php if(auth($guard)->check() && auth($guard)->user()->hasRole($role)): ?>";
});

$this->bladeCompiler->directive('endrole', function () {
Expand All @@ -41,7 +42,7 @@ public function hasroleDirective(): void
$this->bladeCompiler->directive('hasrole', function ($arguments) {
list($role, $guard) = $this->extractRoleGuard($arguments);

return "<?php if(auth({$guard})->check() && auth({$guard})->user()->hasRole({$role})): ?>";
return "<?php if(auth($guard)->check() && auth($guard)->user()->hasRole($role)): ?>";
});
$this->bladeCompiler->directive('endhasrole', function () {
return '<?php endif; ?>';
Expand All @@ -56,7 +57,7 @@ public function hasanyroleDirective(): void
$this->bladeCompiler->directive('hasanyrole', function ($arguments) {
list($roles, $guard) = $this->extractRoleGuard($arguments);

return "<?php if(auth({$guard})->check() && auth({$guard})->user()->hasAnyRole({$roles})): ?>";
return "<?php if(auth($guard)->check() && auth($guard)->user()->hasAnyRole($roles)): ?>";
});
$this->bladeCompiler->directive('endhasanyrole', function () {
return '<?php endif; ?>';
Expand All @@ -71,7 +72,7 @@ public function hasallrolesDirective(): void
$this->bladeCompiler->directive('hasallroles', function ($arguments) {
list($roles, $guard) = $this->extractRoleGuard($arguments);

return "<?php if(auth({$guard})->check() && auth({$guard})->user()->hasAllRoles({$roles})): ?>";
return "<?php if(auth($guard)->check() && auth($guard)->user()->hasAllRoles($roles)): ?>";
});
$this->bladeCompiler->directive('endhasallroles', function () {
return '<?php endif; ?>';
Expand All @@ -85,8 +86,8 @@ public function hasallrolesDirective(): void
*/
private function extractRoleGuard($arguments): array
{
$arguments = preg_replace('(\(|\)| )', '', $arguments);
$arguments = preg_replace('([() ])', '', $arguments);

return \explode(',', $arguments . ',');
return explode(',', $arguments . ',');
}
}
6 changes: 4 additions & 2 deletions src/Exceptions/MakladException.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use InvalidArgumentException;
use Throwable;
use function app;
use function config;

/**
* Class MakladException
Expand All @@ -22,8 +24,8 @@ public function __construct(string $message = null, int $code = 0, Throwable $pr
{
parent::__construct($message, $code, $previous);

if (\config('permission.log_registration_exception')) {
$logger = \app('log');
if (config('permission.log_registration_exception')) {
$logger = app('log');
$logger->alert($message);
}
}
Expand Down
10 changes: 6 additions & 4 deletions src/Exceptions/UnauthorizedException.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@
namespace Maklad\Permission\Exceptions;

use Symfony\Component\HttpKernel\Exception\HttpException;
use function app;
use function config;

/**
* Class UnauthorizedException
* @package Maklad\Permission\Exceptions
*/
class UnauthorizedException extends HttpException
{
private array $requiredRoles = [];
private array $requiredPermissions = [];
private array $requiredRoles;
private array $requiredPermissions;

/**
* UnauthorizedException constructor.
Expand All @@ -29,8 +31,8 @@ public function __construct(
) {
parent::__construct($statusCode, $message);

if (\config('permission.log_registration_exception')) {
$logger = \app('log');
if (config('permission.log_registration_exception')) {
$logger = app('log');
$logger->alert($message);
}

Expand Down
16 changes: 10 additions & 6 deletions src/Guard.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
namespace Maklad\Permission;

use Illuminate\Support\Collection;
use ReflectionClass;
use ReflectionException;
use function get_class;
use function is_object;

/**
* Class Guard
Expand All @@ -12,25 +16,25 @@ class Guard
{
/**
* return collection of (guard_name) property if exist on class or object
* otherwise will return collection of guards names that exists in config/auth.php.
* otherwise will return collection of guards names that exist in config/auth.php.
*
* @param $model
*
* @return Collection
* @throws \ReflectionException
* @throws ReflectionException
*/
public function getNames($model) : Collection
{
$guardName = null;
$class = null;

if (\is_object($model)) {
if (is_object($model)) {
$guardName = $model->guard_name ?? null;
}

if ($guardName === null) {
$class = \is_object($model) ? \get_class($model) : $model;
$guardName = (new \ReflectionClass($class))->getDefaultProperties()['guard_name'] ?? null;
$class = is_object($model) ? get_class($model) : $model;
$guardName = (new ReflectionClass($class))->getDefaultProperties()['guard_name'] ?? null;
}

if ($guardName) {
Expand All @@ -56,7 +60,7 @@ public function getNames($model) : Collection
* @param $class
*
* @return string
* @throws \ReflectionException
* @throws ReflectionException
*/
public function getDefaultName($class): string
{
Expand Down
21 changes: 12 additions & 9 deletions src/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Maklad\Permission;

use Illuminate\Support\Collection;
use function collect;
use function config;

/**
* Class Helpers
Expand All @@ -17,9 +19,9 @@ class Helpers
*/
public function getModelForGuard(string $guard): ?string
{
return \collect(\config('auth.guards'))
return collect(config('auth.guards'))
->map(function ($guard) {
return \config("auth.providers.{$guard['provider']}.model");
return config("auth.providers.{$guard['provider']}.model");
})->get($guard);
}

Expand All @@ -31,7 +33,8 @@ public function getModelForGuard(string $guard): ?string
*/
public function getGuardDoesNotMatchMessage(Collection $expected, string $given): string
{
return "The given role or permission should use guard `{$expected->implode(', ')}` instead of `{$given}`.";
$expectedStr = $expected->implode(', ');
return "The given role or permission should use guard `$expectedStr` instead of `$given`.";
}

/**
Expand All @@ -42,7 +45,7 @@ public function getGuardDoesNotMatchMessage(Collection $expected, string $given)
*/
public function getPermissionAlreadyExistsMessage(string $name, string $guardName): string
{
return "A permission `{$name}` already exists for guard `{$guardName}`.";
return "A permission `$name` already exists for guard `$guardName`.";
}

/**
Expand All @@ -53,7 +56,7 @@ public function getPermissionAlreadyExistsMessage(string $name, string $guardNam
*/
public function getPermissionDoesNotExistMessage(string $name, string $guardName): string
{
return "There is no permission named `{$name}` for guard `{$guardName}`.";
return "There is no permission named `$name` for guard `$guardName`.";
}

/**
Expand All @@ -64,7 +67,7 @@ public function getPermissionDoesNotExistMessage(string $name, string $guardName
*/
public function getRoleAlreadyExistsMessage(string $name, string $guardName): string
{
return "A role `{$name}` already exists for guard `{$guardName}`.";
return "A role `$name` already exists for guard `$guardName`.";
}

/**
Expand All @@ -76,7 +79,7 @@ public function getRoleAlreadyExistsMessage(string $name, string $guardName): st
*/
public function getRoleDoesNotExistMessage(string $name, string $guardName): string
{
return "There is no role named `{$name}` for guard `{$guardName}`.";
return "There is no role named `$name` for guard `$guardName`.";
}

/**
Expand All @@ -86,7 +89,7 @@ public function getRoleDoesNotExistMessage(string $name, string $guardName): str
*/
public function getUnauthorizedRoleMessage(string $roles): string
{
$message = "User does not have the right roles `{$roles}`.";
$message = "User does not have the right roles `$roles`.";
if (! config('permission.display_permission_in_exception')) {
$message = 'User does not have the right roles.';
}
Expand All @@ -101,7 +104,7 @@ public function getUnauthorizedRoleMessage(string $roles): string
*/
public function getUnauthorizedPermissionMessage(string $permissions): string
{
$message = "User does not have the right permissions `{$permissions}`.";
$message = "User does not have the right permissions `$permissions`.";
if (! config('permission.display_permission_in_exception')) {
$message = 'User does not have the right permissions.';
}
Expand Down
11 changes: 6 additions & 5 deletions src/Middlewares/PermissionMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
namespace Maklad\Permission\Middlewares;

use Closure;
use Illuminate\Http\Request;
use Maklad\Permission\Exceptions\UnauthorizedException;
use Maklad\Permission\Exceptions\UnauthorizedPermission;
use Maklad\Permission\Exceptions\UserNotLoggedIn;
use Maklad\Permission\Helpers;
use function explode;
use function is_array;

/**
* Class PermissionMiddleware
Expand All @@ -16,21 +17,21 @@
class PermissionMiddleware
{
/**
* @param Request $request
* @param $request
* @param Closure $next
* @param array|string $permission
* @param $permission
*
* @return mixed
* @throws UnauthorizedException
*/
public function handle(Request $request, Closure $next, array|string $permission): mixed
public function handle($request, Closure $next, $permission): mixed
{
if (app('auth')->guest()) {
$helpers = new Helpers();
throw new UserNotLoggedIn(403, $helpers->getUserNotLoggedINMessage());
}

$permissions = \is_array($permission) ? $permission : \explode('|', $permission);
$permissions = is_array($permission) ? $permission : explode('|', $permission);


if (! app('auth')->user()->hasAnyPermission($permissions)) {
Expand Down
Loading

0 comments on commit 30e1b4a

Please sign in to comment.