Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 58 additions & 42 deletions src/Entrust/Middleware/EntrustRole.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
<?php namespace Zizaco\Entrust\Middleware;
<?php

namespace Zizaco\Entrust\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
* This file is part of Entrust,
Expand All @@ -7,47 +14,56 @@
* @license MIT
* @package Zizaco\Entrust
*/

use Closure;
use Illuminate\Contracts\Auth\Guard;

class EntrustRole
{
const DELIMITER = '|';

protected $auth;

/**
* Creates a new instance of the middleware.
*
* @param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param Closure $next
* @param $roles
* @return mixed
*/
public function handle($request, Closure $next, $roles)
{

if (!is_array($roles)) {
// Convert $roles to an empty string if it's null or not a string
$roles = $roles ?? '';
$roles = explode(self::DELIMITER, $roles);
}

if ($this->auth->guest() || !$request->user()->hasRole($roles)) {
abort(403);
}

return $next($request);
}
const DELIMITER = '|';

protected Guard $auth;

/**
* Creates a new instance of the middleware.
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}

/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure $next
* @param string|array $roles
* @return Response
*/
public function handle($request, Closure $next, $roles): Response
{
$roles = $this->normalizeRoles($roles);

if ($this->unauthorized($roles)) {
abort(403);
}

return $next($request);
}

/**
* Normalize roles to array format
*/
protected function normalizeRoles($roles): array
{
if (is_array($roles)) {
return $roles;
}

return explode(self::DELIMITER, (string)($roles ?? ''));
}

/**
* Check if user is unauthorized
*/
protected function unauthorized(array $roles): bool
{
return $this->auth->guest() || !$this->auth->user()->hasRole($roles);
}
}