<?php

namespace middlewares;

class RbacGuard implements BaseRequestMiddleware
{
    public static function handle(\Request $request): void
    {
        $resource = $request->loadResource();

        /**
         * Check user permission
         * Check only resources which require authorization, otherwise we won't know a user role.
         */
        if (is_subclass_of($resource, \CfProtectedResource::class)) {
            $permissions = (new \CfRBAC())->getPermissionsByRoles((new \CfUsers($resource->username))->getUserRoles());
            if (!\RbacAccessService::isControllerAllowed(get_class($resource), $request->method, $permissions)) {
                syslog(
                    LOG_DEBUG,
                    'User ' . $resource->username . ' does not have permission to access resource: ' . $request->uri
                );
                throw new \ResponseException(
                    'You do not have the right permission to complete '. $request->method . ':' . $request->uri .' operation',
                    \Response::FORBIDDEN
                );
            }
        }
    }
}
