OPTION verb is not working for a list of all records in Yii 2 app - rest

I have created a blank Yii 2 project that have created a REST UserController for already existing User model:
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
I have modified the model to have all fields safe:
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETED]],
[['username', 'email'], 'required'],
[['username', 'email'], 'unique'],
['email', 'email'],
[['password_hash', 'password_reset_token', 'verification_token', 'auth_key', 'status,created_at', 'updated_at', 'password'], 'safe'],
];
}
I have configured URL rules to have both pluralized and non-pluralized paths:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'pluralize' => false,
'except' => ['index'],
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'patterns' => [
'GET,HEAD,OPTIONS' => 'index',
],
],
],
I have enabled JSON input, if that matters:
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]
All the verbs are processed correctly except for OPTIONS /users:
When I execute OPTIONS /user/20 then I am getting:
200 OK
Empty content
List of allowed methods
But, when I execute OPTIONS users then I am getting 405 Method not Allowed.
What can be wrong or what am I missing?

You are getting 405 Method Not Allowed not because of routing but because of yii\filters\VerbFilter.
The yii\rest\Controller uses verbs() method to set up VerbFilter.
The yii\rest\ActiveController overrides verbs() method and sets VerbFilter to only allow GET and HEAD requests for index action.
It uses options action for OPTIONS method.
If you really want to use index action for OPTIONS method. You have to override verbs() method yourself and add OPTIONS as allowed method for that action. For example like this:
protected function verbs()
{
$verbs = parent::verbs();
$verbs['index'][] = 'OPTIONS';
return $verbs;
}
Or if you want to use options action you have to modify patterns settings as suggested by #Bizley in comments.

Related

Yii2 advanced change views default path (theming)

I would like for my application to automatically change template
so i created this structure frontend/web/themes/myTheme
following http://www.yiiframework.com/doc-2.0/guide-output-theming.html i added this code in frontend/config/main.php
'components' => [
'view' => [
'theme' => [
'basePath' => '#app/themes/myTheme',
'baseUrl' => '#web/themes/myTheme',
'pathMap' => [
'#app/views' => '#app/themes/myTheme',
],
],
],
],
however i kept getting the error that " /var/www/html/myProject/app/frontend/views/site/index.php" The view file does not exist???
i also tried to put this function inside the controller based on How to change default view path in Yii2?
public function getViewPath()
{
return Yii::getAlias('#web/themes/myTheme/site');
}
so my question is:
1. how can I change the views default path?
2. how can i do it automatically since i can not change the common/config/main.php settings during a session?
site controller
class SiteController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['index'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['index'],
'allow' => true,
'roles' => ['#'],
],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
$searchModel = new ProductSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
}
I think you are configuring the wrong file.Don't configure themes in the common/config
Try this:
in frontend/config/main.php
'components' => [
'view' => [
'theme' => [
'pathMap' => [
'#frontend/views'=>'#frontend/themes/myTheme',
],
],
],
],
if you need to configure the backend then in the backend/config/main.php
'components' => [
'view' => [
'theme' => [
'pathMap' => [
'#backend/views'=>'#backend/themes/myTheme',
],
],
],
],
The common folder is has to contain the files that are required by both
frontend and backend.
Hope this helps.
First question:
I think than you have a common mistake in yii when used advanced app: the alias #app references root directory of frontend, backend, or common depending on where you access it from View documentation here.
You would used the solution proposed by ovicko.
Second question:
You can change the theme configuration dynamically in controller through view object:
$this->view->theme->pathMap =['#app/views' => '#app/themes/myTheme/',];
EDIT
According to Documentation:
Theming is a way to replace a set of views with another without the need of touching the original view rendering code.
What means that the original view file must exist and theming simply replace it in during rendering. So you must create a file in /var/www/html/myProject/app/frontend/views/site/index.php (a empty file is valid) in order to theming works.
This sounds quite ridiculous, I Know, but it works.
But I think that is much better and easier the use of differents layouts, again, to change dinamically the layout in your controller:
$this->layout = 'route/yourlayout';

Yii2 Rest URL Routing for Regular Controllers

How is it possible to extend yii\rest\UrlRule in a way I can rewrite rules for actions of a controller? For example, I want to generate the following URIs:
/user/[username]
/user/keywords
/user/keyword/[key1]/[key2]/[...]
...
Every above actions are rendering their own view too.
You don't need to extend yii\rest\UrlRule. Just add your rules to routes of UrlManager by putting them on extraPatterns property of yii\rest\UrlRule.
For example suppose You defined a list action in your controller:
class BarController extends Controller
{
public $modelClass = 'app\models\Foo';
public function actionList()
{
return ['id' => 1];
}
}
Then in configuration file add extra route:
<?php
// some configs are here
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => [
'v1/bar',
],
'extraPatterns' => [
'GET list' => 'list',
],
],
],
],
// and some other configs are here
Now you can browse the api with /v1/bars/list. Read Yii2 Documentations for more examples.
you must change the extends of Controller in ActiveController
class ArticleController extends ActiveController

How to debug Yii REST controller file with xdebug and Netbeans (where to put breakpoint and what url use)?

I have installed Netbenas, XAMPP, xdebug and Yii2 and I have simple REST controller:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class ContractController extends ActiveController
{
public $modelClass = 'app\models\Contract';
}
which connects to the Firebird 2.1 database (WIN1257) and gives error:
error on line 2 at column 431: Encoding error
I want to debug this error to determine how can I improve Yii-Firebird plugin but where can I put breakpoint if this controller has no action (action from base class is used). In run congfiguration I have Project URL:
http://localhost:8081/myproject/
and index file:
web/index.php
My intention was to put here url that gives error:
http://localhost:8081/myproject/web/index.php/contract
But Netbeans does not accept /contract part in index file field.
So - which file should I open in Netbenas and how to indicate that I want to debug url http://localhost:8081/myproject/web/index.php/contract?
Your
class ContractController extends ActiveController
is an extension of ActiveController
So you could place your breakpoint to the proper ActiveController action ..
in
vendor/yiisoft/yii2/rest/ActionController
you can find
public function actions()
{
return [
'index' => [
'class' => 'yii\rest\IndexAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'view' => [
'class' => 'yii\rest\ViewAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'create' => [
'class' => 'yii\rest\CreateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->createScenario,
],
'update' => [
'class' => 'yii\rest\UpdateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->updateScenario,
],
'delete' => [
'class' => 'yii\rest\DeleteAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'options' => [
'class' => 'yii\rest\OptionsAction',
],
];
}
where you can see that for each action you have a proper class eg:..
'class' => 'yii\rest\IndexAction',
In the same dir vendor/yiisoft/yii2/rest/ActionController you can find the class code
Then you could place the breakpoint on the related class run function
public function run()
{
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id);
}
return $this->prepareDataProvider();
}

Way to redirect login page if user not login

I want to redirect user to login page if he is not logged on page. But i have actionLogin in my registrationController
So when I use in my common/main:
'as beforeRequest' => [ //if guest user access site so, redirect to login page.
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
It always redirect me to index.php?r=site%2Flogin
Is it possible to change main login redirect to index.php?r=registration%2Flogin?
If it possible where I should overwrite code or change something..
'user' => [ 'loginUrl' => ['registration/login'], ],
resolve problem but when I want to go to registration/index to signup user it redirect me to registration/login.
Is it possible to rule out this url from being enforced? I Want to make index.php?r=registration the only available path.
And here is my facebook login; I want to enable this too
public function oAuthSuccess($client) {
// get user data from client
$userAttributes = $client->getUserAttributes();
$user = User::find()->where(['Email' => $userAttributes['email']])->one();
if (!$user) {
$newuser = New SignupForm();
$newuser->oAuthSuccess($client);
$user = User::find()->where(['Email' => $userAttributes['email']])->one();
if ($newuser->validate() && Yii::$app->getUser()->login($user)) {
Yii::$app->session->setFlash('success', Yii::t('app', 'Udało się poprawnie zalogować. Prosimy dokonać zmian w ustawianiach profilu.'));
return $this->redirect('index.php?r=content/news');
}
}
Yii::$app->user->login($user);
}
In your app/config/web.php (for basic template) or
app/frontend/config/main.php (for advance template) - reference
return [
// ...
'components' => [
// ...
'user' => [
'identityClass' => 'common\models\UserIdentity',
'enableAutoLogin' => true,
'loginUrl'=>['registration/login']
],
// ...
and in your controller for eg RegistrationController.php
// ...
class RegistrationController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'signup'], // those action only which guest (?) user can access
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['home', 'update'], // those action only which authorized (#) user can access
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
// ...
The simple way is using index.php from backend web or public directory
<?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/../../config/web.php';
$config["controllerNamespace"]='app\controllers\backend';
(new yii\web\Application($config))->run();
if(Yii::$app->user->isGuest){
$request_headers = apache_request_headers();
$srv=$request_headers['Host'];
header("Location: https://".$srv);
die();
}

ZF2 access to config in router configuration

i route by hostname and i want to get my domain name by local.php config file in config/autoload in zf2
i know how should i get configs in controller,
but i dont know how can i get it in my router configuration file
i comment what i want in my code
'router' => array(
'routes' => array(
'advertise' => array(
'type' => 'Hostname',
'options' => array(
'route' => 'www.myhome.com', // here i want to get my domain by config
'defaults' => array(
'controller' => 'Advertise\Controller\Advertise',
'action' => 'index',
),
),
.............
You can use the API of the 'router' service (an instance of Zend\Mvc\Router\Http\TreeRouteStack) and add a route dynamically.
How you attach the route to the route stack is up to you, you could extend the default router factory Zend\Mvc\Service\RouterFactory with your own routes from config.
use MyModule\Mvc\Service;
use Zend\Mvc\Service\RouterFactory;
use Zend\ServiceManager\ServiceLocatorInterface;
class MyRouterFactory extends RouterFactory
{
public function createService(ServiceLocatorInterface $serviceLocator, $cName = null, $rName = null)
{
$serviceManager = $serviceLocator->getServiceLocator();
$router = parent::createService($serviceLocator, $cName, $rName);
$config = $serviceManager->get('config');
$router->addRoute('advertise', [
'type' => 'hostname',
'options' => [
'route' => $config['some_other_config_key'],
'defaults' => [
'controller' => 'Advertise\Controller\Advertise',
'action' => 'index'
]
],
'priority' => 123
]);
return $router;
}
}
Remember to register it with the name Router in module.config.php to replace the default implementation.
'service_manager' => [
'factories' => [
'Router' => 'MyModule\Mvc\Service\MyCustomRouterFactory',
],
],
The nice thing with this approach is that the routers construction is all kept in one place; also as you are adding it with a factory class
you have access to other services should you need them.
Alternatively, you could add it via an event, although being triggered via the event manager, this method would likely be more resource intensive.
namespace MyModule;
use Zend\ModuleManager\InitProviderInterface;
use Zend\ModuleManager\ModuleManagerInterface;
use Zend\Mvc\Application;
use Zend\Mvc\MvcEvent;
class Module implements InitProviderInterface
{
// init is called when the module is initilised, we can use this to add a listener to the
// 'bootstrap' event
public function init(ModuleManagerInterface $manager)
{
$eventManager = $manager->getEventManager()->getSharedManager();
$eventManager->attach(Application::class, MvcEvent::EVENT_BOOTSTRAP, [$this, 'addRoutes']);
}
public function addRoutes(MvcEvent $event)
{
$serviceManager = $event->getApplication()->getServiceManager();
$router = $serviceManager->get('Router');
$config = $serviceManager->get('Config');
$router->addRoute('advertise', [
'type' => 'hostname',
'options' => [
'route' => $config['some_other_config_key'],
'defaults' => [
'controller' => 'Advertise\Controller\Advertise',
'action' => 'index'
]
],
'priority' => 123
]);
}
}