Get controller and action of URL - yii

I'm extending the UrlRuleInterface class for custom URL rules
I'm trying to redirect the url to add a suffix / if the url doesn't have it.
public function parseRequest($manager, $request)
{
$matches = explode('/', $request->getPathInfo());
//if last array is empty, unset it!
if (empty(end($matches))) {
unset($matches[count($matches) - 1]);
} else {
//add code to redirect to controller and action here
}
How do i get the controller and action of the URL so i can redirect my custom URLs to add the /
The forcing suffix works fine on other URLS, but not my custom URLS.
in my main.php i have this
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
'suffix' => '/',
'normalizer' => [
'class' => 'yii\web\UrlNormalizer',
],
'rules' => require ('urls.php'),
],

Related

Get full url of current webpage in Yii2

How to get the full URl in address bar to my Yii2 Model using yii\helpers\Url ?
I use $currentUrl = Yii::$app->request->url; but it return site/submit which is defined already in my UrlManager :
'urlManager' => [
'enableStrictParsing' => true,
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'/' => 'site/index',
'site/submit' => 'site/submit',
'admin' => 'admin/index',
'admin/login' => 'admin/login',
'admin/index' => 'admin/index',
'admin/logout' => 'admin/logout',
'/<url:.+>' => 'site/index',
'defaultRoute' => 'site/index',
],
],
Best regards,
Yii::$app->request->absoluteUrl
Plz follow this yii2 document
Yii::app()->createAbsoluteUrl(Yii::app()->request->url)

Yii2 as beforeRequest authentication rule in config not working for pages

In a Yii2 advance application, I am trying to allow users to the login page and about page only.
So i put in the /common/config/web.php configuration file the following rule
'as beforeRequest' => [ //if guest user access site so, redirect to login page.
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'actions' => ['login', 'error', 'request-password-reset', 'about'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
The login, error and request-password-reset it is working fine but not the about page.
I also tried '/page/about' and 'page/about' but i had no luck.
Any ideas how to fix or troubleshoot this.
Thanks
It should be 'view' instead of 'about'
I am sorry I found the answer the rule it is fine but i am using a page component and the PageController it is getting the view from the admin (database) in the following controller
class PageController extends Controller{
public function actionView($slug)
{
$model = Page::find()->where(['slug'=>$slug, 'status'=>Page::STATUS_PUBLISHED])->one();
if (!$model) {
throw new NotFoundHttpException(Yii::t('frontend', 'Page not found'));
}
$viewFile = $model->view ?: 'view';
return $this->render($viewFile, ['model'=>$model]);
}}
So in the rule I need to use 'view' for all the views rendered by the PageController
try this code
'as beforeRequest' => [ //if guest user access site so, redirect to login page.
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'actions' => ['login', 'error', 'request-password-reset', 'about'],
'roles' => ['#']
'allow' => true,
],
[
'allow' => true,
'roles' => ['?'],
],
],
],
i hope it will work for you

yii2 custom REST api issue

I have tried all the way to make these run but no use.There is lots of problem and confusion i m going through.
I have make api which return all the countries which is working fine.Now need to write api function to list all the states of perticular country.
api : http://phpserver:8090/ssn-project/newzit/api/web/state/customstate?country_id=102
StateController.php
class StateController extends ActiveController{
public $modelClass = 'api\modules\state\models\State';
public function actionCustomState($country_id)
{
$model = new $this->modelClass;
$result = $model::find()
->where(['country_id' => $country_id])
->all();
return $result;
}
}
main.php
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['country/country','state/state','category/category','seller/seller'],
'extraPatterns' => [
'GET CustomState' => 'CustomState',
],
]
],
]
Am I doing anything wrong.Please help
What do you mean by 'controller' => ['country/country','state/state','category/category','seller/seller'] ? This will be treated as module/controller. You have placed all controllers inside different modules? With this logic, your api url will be
http://phpserver:8090/ssn-project/newzit/api/web/state/state/customstate?country_id=102
instead of
http://phpserver:8090/ssn-project/newzit/api/web/state/customstate?country_id=102
Found the solution.
made 'pluralize'=>false and used custom-state in url
My main.php
'rules' => [
[
'pluralize'=>false,
'class' => 'yii\rest\UrlRule',
'controller' => ['country/country','state/state','category/category','seller/seller','contactus/contactus'],
'extraPatterns' => [
'GET custom-state' => 'custom-state',
],
]
],
Thank you.

Module route with rewrite redirect to product on Prestahop

I created a custom route for an artist page:
public function hookModuleRoutes($params)
{
return [
'module-artists-artist' => [
'controller' => 'artist',
'rule' => 'artists/{id_artist}',
'keywords' => [
'id_artist' => ['regexp' => '[0-9]+', 'param' => 'id_artist'],
],
'params' => [
'fc' => 'module',
'module' => 'artists',
'controller' => 'artist'
],
],
];
}
If I test with /artists/1, this works. But I want to add the link_rewrite property. So I modified the configuration like this:
public function hookModuleRoutes($params)
{
return [
'module-artists-artist' => [
'controller' => 'artist',
'rule' => 'artists/{id_artist}-{rewrite}',
'keywords' => [
'id_artist' => ['regexp' => '[0-9]+', 'param' => 'id_artist'],
'rewrite' => ['regexp' => '[_a-zA-Z0-9\pL\pS-]*'],
],
'params' => [
'fc' => 'module',
'module' => 'artists',
'controller' => 'artist'
],
],
];
}
But when I try /artists/1-baxter, I'm redirected to the product page of product with ID 1. My artist controller is never called.
[Debug] This page has moved
Please use the following URL instead: http://localhost:8000/fr/estampes/1-est-ce-que-etre
How can I solve it?
This is because URLs generated by your pattern also match the product URL pattern, which has higherprecedence. PrestaShop doesn't check whether product exists, it just redirects directly to ProductController. Page patterns in PrestaShop differ from each other so that URLs can be quickly recognized to be associated with X controller. You can confirm this by checking the default patterns.
You can check the product URL pattern in back-office: SEO & URLs or in DispatcherCore class. Anyway, if you want an easy fix I'd suggest making this pattern:
artists/{id_artist}/{rewrite}

How to login user using rest api in yii2

I new in yii2, I want login user using rest api but unable to do this.I have setup basic REST API From This blog:
budiirawan.com/setup-restful-api-yii2/
After that I have created :
api\modules\v1\controllers\SiteController.php
<?php
namespace api\modules\v1\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use common\models\LoginForm;
use yii\filters\VerbFilter;
use yii\rest\ActiveController;
/**
* Site controller
*/
class SiteController extends ActiveController
{
/**
* #inheritdoc
*/
public $modelClass = 'api\modules\v1\models\user';
public function actionIndex()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
And Created Model
RtWorkForce\api\modules\v1\models\User.php
<?php
namespace api\modules\v1\models;
use \yii\db\ActiveRecord;
/**
* User Model
*
*/
class User extends ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
}
Here Is my main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'modules' => [
'v1' => [
'basePath' => '#app/modules/v1',
'class' => 'api\modules\v1\Module'
]
],
'components' => [
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['v1/country','v1/user','v1/site'],
'tokens' => [
'{id}' => '<id:\\w+>'
]
]
],
]
],
'params' => $params,
];
But IT's not working i don't know where i am wrong ??
From Yii 2.0 REST Authentication docs :
Unlike Web applications, RESTful APIs are usually stateless, which
means sessions or cookies should not be used.
And from this other docs about the user class which implement yii\web\IdentityInterface :
if your application is a pure stateless RESTful application, you would
only need to implement findIdentityByAccessToken() and getId() while
leaving all other methods with an empty body.
RESTfull is about routing. If following a token based authentication, then, It should return a resources or a collections if the request sent to server is holding a valid token. Otherwise it should be rejected.
Login process in that case, is one request holding a username/password pair that will be exchanged with a valid token by server, that is the token you are going to include with all your next requests.
If session is disabled on server side by setting enableSession to false as described in Yii documentation (see links above) and as recommended by the stateless nature of REST, then \Yii::$app->user->isGuest should not provide info as your server won't have any session to get it from. (unless it verifies token validity instead of checking session)
When building a class extending yii\rest\ActiveController you can't render a html page like :
return $this->render('login', [
'model' => $model,
]);
or redirect to a different HTML page like :
return $this->goHome();
That will work with a yii\base\Controller when building a HTML based web app instead of yii\rest\ActiveController. with ActiveController you just return data which will be serialized to json or xml before output.
Please refer to Yii RESTful API framework documentations for more details. Then you may find useful information in this great tutorial on How to implement Yii2 REST Authentication :
http://blog.neattutorials.com/angularjs-and-yii2-part-2-authentication/