|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Laratrust\Middleware; |
| 4 | + |
| 5 | +use Illuminate\Support\Str; |
| 6 | +use Illuminate\Support\Collection; |
| 7 | +use Illuminate\Support\Facades\Auth; |
| 8 | +use Illuminate\Support\Facades\Config; |
| 9 | + |
| 10 | +class LaratrustMiddleware |
| 11 | +{ |
| 12 | + const DELIMITER = '|'; |
| 13 | + |
| 14 | + /** |
| 15 | + * Check if the request has authorization to continue. |
| 16 | + * |
| 17 | + * @param string $type |
| 18 | + * @param string $rolesPermissions |
| 19 | + * @param string|null $team |
| 20 | + * @param string|null $options |
| 21 | + * @return boolean |
| 22 | + */ |
| 23 | + protected function authorization($type, $rolesPermissions, $team, $options) |
| 24 | + { |
| 25 | + list($team, $requireAll, $guard) = $this->assignRealValuesTo($team, $options); |
| 26 | + $method = $type == 'roles' ? 'hasRole' : 'hasPermission'; |
| 27 | + |
| 28 | + if (!is_array($rolesPermissions)) { |
| 29 | + $rolesPermissions = explode(self::DELIMITER, $rolesPermissions); |
| 30 | + } |
| 31 | + |
| 32 | + return !Auth::guard($guard)->guest() |
| 33 | + && Auth::guard($guard)->user()->$method($rolesPermissions, $team, $requireAll); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * The request is unauthorized, so it handles the aborting/redirecting. |
| 38 | + * |
| 39 | + * @return \Illuminate\Http\Response |
| 40 | + */ |
| 41 | + protected function unauthorized() |
| 42 | + { |
| 43 | + return call_user_func( |
| 44 | + Config::get('laratrust.middleware.handling', 'abort'), |
| 45 | + Config::get('laratrust.middleware.params', '403') |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Generate an array with the real values of the parameters given to the middleware. |
| 51 | + * |
| 52 | + * @param string $team |
| 53 | + * @param string $options |
| 54 | + * @return array |
| 55 | + */ |
| 56 | + protected function assignRealValuesTo($team, $options) |
| 57 | + { |
| 58 | + return [ |
| 59 | + (Str::contains($team, ['require_all', 'guard:']) ? null : $team), |
| 60 | + (Str::contains($team, 'require_all') ?: Str::contains($options, 'require_all')), |
| 61 | + (Str::contains($team, 'guard:') ? $this->extractGuard($team) : ( |
| 62 | + Str::contains($options, 'guard:') |
| 63 | + ? $this->extractGuard($options) |
| 64 | + : Config::get('auth.defaults.guard') |
| 65 | + )), |
| 66 | + ]; |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * Extract the guard type from the given string. |
| 71 | + * |
| 72 | + * @param string $string |
| 73 | + * @return string |
| 74 | + */ |
| 75 | + protected function extractGuard($string) |
| 76 | + { |
| 77 | + $options = Collection::make(explode('|', $string)); |
| 78 | + |
| 79 | + return $options->reject(function ($option) { |
| 80 | + return strpos($option, 'guard:') === false; |
| 81 | + })->map(function ($option) { |
| 82 | + return explode(':', $option)[1]; |
| 83 | + })->first(); |
| 84 | + } |
| 85 | +} |
0 commit comments