diff options
author | Sam Light <samlight1994@gmail.com> | 2022-09-09 15:29:01 +0100 |
---|---|---|
committer | Sam Light <samlight1994@gmail.com> | 2022-09-09 15:29:01 +0100 |
commit | 448f23c06cf6ec255212bc04e29bda4d8fe37e2b (patch) | |
tree | ac0aeb9446e1d256fcb30c86a50a157267257159 /src/Middleware/ScormPlayerAuthMiddleware.php | |
parent | 157d77625644a97742f6953df6a42476c5387e2c (diff) |
Created auth middleware base class
Diffstat (limited to 'src/Middleware/ScormPlayerAuthMiddleware.php')
-rw-r--r-- | src/Middleware/ScormPlayerAuthMiddleware.php | 91 |
1 files changed, 91 insertions, 0 deletions
diff --git a/src/Middleware/ScormPlayerAuthMiddleware.php b/src/Middleware/ScormPlayerAuthMiddleware.php new file mode 100644 index 0000000..8044821 --- /dev/null +++ b/src/Middleware/ScormPlayerAuthMiddleware.php @@ -0,0 +1,91 @@ +<?php + +namespace Lightscale\ScormPlayer\Middleware; + +use Peopleaps\Scorm\Model\ScormModel as Scorm; +use Lightscale\ScormPlayer\Models\{ + ScormSco, + ScormScoTracking, +}; + +use Closure; +use Illuminate\Http\Request; +use Illuminate\Http\Response; + +use Illuminate\Support\Facades\Cache; + +class ScormPlayerAuthMiddleware +{ + private $cacheTimeout; + + public function __construct() + { + $this->cacheTimeout = config('scorm.cache_timeout'); + } + + public function handle(Request $request, Closure $next) + { + try { + $module = $this->findModule($request); + } + catch(\Exception $e) { + return $this->failedResponse(); + } + + $user = $request->user(); + $authorized = Cache::remember( + 'scorm-player-authorize-{$user->id}_{$module->id}', + $this->cacheTimeout, + fn() => $this->authorize($request, $module) + ); + + if($authorized) return $next($request); + else return $this->failedResponse(); + } + + protected function failedResponse() : Response + { + return response('Not authorized', 503); + } + + protected function findModule(Request $request) : Scorm + { + $route = $request->route(); + $parameters = $route->parameters(); + $routeName = $route->getName(); + + if($routeName === 'scorm-player.serve') { + $uuid = $route->parameter('uuid'); + return Cache::remember( + "scrorm-player-uuid-{$uuid}-scorm", + $this->cacheTimeout, + fn() => Scorm::where('uuid', $uuid)->firstOrFail() + ); + } + else foreach($parameters as $val) { + if(getType($val) !== 'object') continue; + + if(is_a($val, Scorm::class)) + return $val; + elseif(is_a($val, ScormSco::class)) + return Cache::remember( + "scorm-player-sco-{$val->id}-scorm", + $this->cacheTimeout, + fn() => $val->scorm + ); + elseif(is_a($val, ScormScoTracking::class)) + return Cache::remember( + "scorm-player-sco-tracking-{$val->id}-scorm", + $this->cacheTimeout, + fn() => $val->sco->scorm + ); + } + + throw new \Exception('Failed to find module from route'); + } + + protected function authorize(Request $req, Scorm $module) : bool + { + return false; + } +} |