Check if token is valid

@param \Cake\Controller\Controller $controller Instantiating controller
@throws \Cake\Controller\Exception\SecurityException
@return string fields token
552668
protected function _validToken(Controller $controller)
    {
        $check = $controller->getRequest()->getData();

        $message = '\'%s\' was not found in request data.';
        if (!isset($check['_Token'])) {
            throw new AuthSecurityException(sprintf($message, '_Token'));
        }
        if (!isset($check['_Token']['fields'])) {
            throw new AuthSecurityException(sprintf($message, '_Token.fields'));
        }
        if (!isset($check['_Token']['unlocked'])) {
            throw new AuthSecurityException(sprintf($message, '_Token.unlocked'));
        }
        if (Configure::read('debug') && !isset($check['_Token']['debug'])) {
            throw new SecurityException(sprintf($message, '_Token.debug'));
        }
        if (!Configure::read('debug') && isset($check['_Token']['debug'])) {
            throw new SecurityException('Unexpected \'_Token.debug\' found in request data');
        }

        $token = urldecode($check['_Token']['fields']);
        if (strpos($token, ':')) {
            list($token, ) = explode(':', $token, 2);
        }

        return $token;
    }
761881
public function startup(Controller $controller) {
        $this->Controller = $controller;

        // Thrown an exception if accessing an override action without requestAction()
        if (substr($controller->action, 0, 6) === 'admin_' && empty($controller->request->params['override'])) {
            throw new ForbiddenException();
        }

        // Set ACL session
        $user_id = $this->Auth->user('id');

        if (!$user_id || $this->Auth->user(Configure::read('User.fieldMap.status')) == Configure::read('User.statusMap.banned')) {
            return;
        }

        if (!$this->Session->check('Acl')) {
            $roles = ClassRegistry::init('Admin.RequestObject')->getRoles($user_id);
            $isAdmin = false;
            $isSuper = false;
            $roleMap = array();

            foreach ($roles as $role) {
                if (!$isAdmin && $role['RequestObject']['alias'] == Configure::read('Admin.aliases.administrator')) {
                    $isAdmin = true;
                }

                if (!$isSuper && $role['RequestObject']['alias'] == Configure::read('Admin.aliases.superModerator')) {
                    $isSuper = true;
                }

                $roleMap[$role['RequestObject']['id']] = $role['RequestObject']['alias'];
            }

            $this->Session->write('Acl.isAdmin', $isAdmin);
            $this->Session->write('Acl.isSuper', $isSuper);
            $this->Session->write('Acl.roles', $roleMap);
        }

        // Set reported count
        if (Configure::read('Admin.menu.reports')) {
            Configure::write('Admin.menu.reports.count', Admin::introspectModel('Admin.ItemReport')->getCountByStatus());
        }
    }
1070174
public function initialize(Controller $controller) {
        $autoLogin = (array) Configure::read('AutoLogin');

        // Is debug enabled?
        $this->_debug = (!empty($autoLogin['ips']) && in_array(env('REMOTE_ADDR'), (array) $autoLogin['ips']));
    }
1066337
public function can($action, $controller)
    {
        return app(Gate::class)
            ->forUser($this)
            ->check('decoy.auth', [$action, $controller]);
    }
635659
public function generateToken()
	{
		$controller = new AjaxController();
		$controller->restrictAccess(Auth::isAdmin());
		
		$token = Functions::generateRandomToken();		
		$this->module->setSetting('MAJ_AT_FORCE_EXEC_TOKEN', $token);
		Log::addConfigurationLog($this->module->getTitle().' : New token generated.');
		
		$controller->pageHeader();
		echo $token;
	}
1322961
public function controller($controller)
    {

        // Instantiate a string controller
        if (is_string($controller)
            && class_exists($controller)
            && is_subclass_of($controller, 'Bkwld\Decoy\Controllers\Base')) {
            $this->controller_name = $controller;
            $this->controller = new $controller;

            // Apply the parent if one was set
            if ($this->parent_item && $this->controller) {
                $this->controller->parent($this->parent_item);
            }

        // Or, validate a passed controller instance
        } elseif (is_object($controller)
            && is_a($controller, 'Bkwld\Decoy\Controllers\Base')) {
            $this->controller_name = get_class($controller);
            $this->controller = $controller;
        }

        // Chain
        return $this;
    }
1151036
protected function functions(String & $controller)
    {
        $parameters = NULL;

        if( ! empty($this->settings['functions']) ) foreach( $this->settings['functions'] as $isKey => $function )
        {
            if( ! empty($function) )
            {
                if( ! is_numeric($isKey) )
                {
                    if( is_array($function) )
                    {
                        $subValue = '';

                        foreach( $function as $key => $val )
                        {
                            if( ! is_numeric($key) )
                            {
                                $subValue = $val;
                                $val      = $key;
                            }

                            if( strpos($val, '...') === 0 )
                            {
                                $varprefix = str_replace('...', '...$', $val);
                                $subValue  = '';
                            }
                            else
                            {
                                $varprefix = '$'.$val;
                            }

                            $parameters .= $varprefix.( ! empty($subValue) ? ' = '.$subValue : '').', ';
                        }

                        $parameters = rtrim($parameters, ', ');
                    }

                    $function = $isKey;
                }

                $function = $this->vartype($function);

                $controller .= HT.$function->priority." function {$function->var}({$parameters})".EOL;
                $controller .= HT."{".EOL;
                $controller .= HT.HT."// Your codes...".EOL;
                $controller .= HT."}".EOL.EOL;
            }
        }
    }
351590
public function hookTheme(Controller $controller)
    {
        if ($controller->isCurrentTheme('backend') && !$controller->isInternalRoute()) {
            $this->setAssets($controller);
            $this->setMetaTags($controller);
        }
    }
540205
public function initialize(Controller $controller) {
        if ($controller->request->is('ajax')) {
            Configure::write('debug', 0);

            // Must disable security component for AJAX
            if (isset($controller->Security)) {
                $controller->Security->validatePost = false;
                $controller->Security->csrfCheck = false;
            }

            // If not from this domain, destroy
            if (!$this->allowRemote && (strpos(env('HTTP_REFERER'), trim(env('HTTP_HOST'), '/')) === false)) {
                if (isset($controller->Security)) {
                    $controller->Security->blackHole($controller, 'Invalid referrer detected for this request.');
                } else {
                    $controller->redirect(null, 403, true);
                }
            }
        }

        $this->controller = $controller;
    }
348966
public function setControllerData($controller)
    {
        if (is_string($controller)) {
            $controller = $this->app->normalizeClassName($controller, 'Data');
        } elseif (!$controller instanceof Controller_Data) {
            throw $this->exception('Inappropriate Controller. Must extend Controller_Data');
        }
        $this->controller = $this->setController($controller);

        return $this->controller;
    }
1236764
public function startup(Controller $controller) {
		if ($this->settings['isTest']) {
			return;
		}

		foreach ($this->routes as $route) {
			if (!$this->_parse($route['route'])) {
				continue;
			}

			if (!$this->_execute($route)) {
				break;
			}

			$this->Session->write('Sanction.referer', $this->request->here());
			return $this->redirect($controller, $route);
		}
	}
297092
public function startup(Controller $controller) {
        $handled = ($this->_handled === array('*') || in_array($controller->action, $this->_handled));

        if ($handled && !$controller->request->is('ajax')) {
            if (isset($controller->Security)) {
                $controller->Security->blackHole($controller, 'You are not authorized to process this request.');
            } else {
                $controller->redirect(null, 401, true);
            }
        }

        $this->controller = $controller;
    }
61021
public static function is(string $controller, string $action): bool
    {
        return $controller == Application::route()->getControllerUrl() && $action == Application::route()->getActionUrl();
    }
1137044
public function slugController($controller)
    {
        // Get the controller name
        $controller = preg_replace('#^('.preg_quote('Bkwld\Decoy\Controllers\\')
            .'|'.preg_quote('App\Http\Controllers\Admin\\').')#', '', $controller);

        // Convert study caps to dashes
        $controller = Str::snake($controller, '-');

        // Done
        return $controller;
    }
1294317
protected function checkUserRequireReset($controller) {

        $user = $this->getContainer()->get('user')->load();

        if ($user->requireReset) {

            /*
             * Par défaut, c'est la page d'édition du profil qui est utilisée.
             * Cette page permet de changer plus que le mot de passe et peut ne pas être le comportement désiré.
             * On peut surcharger la page qui gère la remise à zero en changeant la configuration.
             */
            $classname = $this->get('controller_prefix') . $this->get('reset_password.controller');

            if ($classname !== null && !($controller instanceof $classname)) {

                $text = $this->getContainer()->get('language')->getText();

                // On redirige vers la page.
                $this->enqueueMessage($text->translate('APP_GLOBAL_PASSWORD_RESET_REQUIRED'), 'notice');
                $this->redirect("/".$this->get('reset_password.uri'));

            }

        }
    }
416390
private function getControllerActionAnnotations($controller, $action)
    {
        if ($controller instanceof \Closure) {
            return $this->annotation->readFunction($controller);
        }

        return $this->annotation->readMethod($controller, $action . 'Action');
    }
1051477
public function authenticateRequest(DispatcherContext $context)
    {
        if($token = $this->getToken())
        {
            if($token->verify($this->getSecret()))
            {
                $user = $token->getSubject();
                $data = (array) $token->getClaim('user');

                //Ensure the token is not expired
                if($this->_check_expire)
                {
                    if(!$token->getExpireTime() || $token->isExpired()) {
                        throw new ControllerExceptionRequestNotAuthenticated('Token Expired');
                    }
                }

                //Ensure the token is not too old
                if($this->_check_age)
                {
                    if (!$token->getIssueTime() || $token->getAge() > $this->_max_age) {
                        throw new ControllerExceptionRequestNotAuthenticated('Token Expired');
                    }
                }
                //Ensure the user exists
                if($this->_check_user)
                {
                    //Ensure we have a username
                    if(empty($user)) {
                        throw new ControllerExceptionRequestNotAuthenticated('Invalid User');
                    }

                    if($this->getObject('user.provider')->getUser($user)->getId() == 0) {
                        throw new ControllerExceptionRequestNotAuthenticated('User Not Found');
                    }
                }

                //Login the user
                return $this->loginUser($user, $data);
            }
            else throw new ControllerExceptionRequestNotAuthenticated('Invalid Token');
        }
    }