yii2 errorhandler: Redirect to frontend/site/error - redirect

When implementing the access control on the backend, I would like to redirect disallowed users to the frontend error page (instead of the backend error page).
The backend controller:
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['admin'],
],
backend/config/main.php
'components'=>[
'errorHandler' => [
'errorAction' => 'site/error',
],
How do I redirect non-admin users to frontend/site/error? Everything I try results in an error.
Many thanks

if I understand correctly you want the frontend user if logged in and tries to access the backend's modules or controllers he/she should not be allowed to do so, This was a Session Sharing bug reported earlier, and this was added into Yii 2.0.9 milestones and is already integrated since 2016.
If you are working on an existing Yii2 project with an older version and haven't migrated or upgraded to the latest version, I would suggest you do the following settings
/backend/config/main.php:
return [
'id' => 'app-backend',
// ...
'components' => [
'user' => [
'identityClass' => 'common\models\Admin',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_backendUser', // unique for backend
]
],
'session' => [
'name' => 'PHPBACKSESSID',
'savePath' => sys_get_temp_dir(),
],
// ..
];
/frontend/config/main.php:
return [
'id' => 'app-frontend',
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_frontendUser',
]
],
'session' => [
'name' => 'PHPFRONTSESSID',
'savePath' => sys_get_temp_dir(),
],
///...
]
];

Related

Laminas Cache config issue after updated to PHP 8.1 from zend3

I work on a project which is recently updated to Laminas and PHP 8.1 from Zend3 and PHP 7.4.
in config/autoload/global.php
'caches' => require __DIR__ . '/caches.php',
and this is caches.php
$cacheDefault = [
'adapter' => [
'name' => 'Memcached',
'options' => [
'servers' => Module::isRunningOnVM()
? ['127.0.0.1:11211']
: Module::getMemcachedServersFromEnvironment(),
],
],
];
return [
'cache_instrument_manager_search' => array_merge_recursive(
$cacheDefault,
[
'adapter' => [
'options' => [
'namespace' => 'instrument_manager_search',
'ttl' => 20,
],
],
]
),
'cache_weekly' => array_merge_recursive(
$cacheDefault,
[
'adapter' => [
'options' => [
'namespace' => 'weekly',
'ttl' => 604800, // whole week
],
],
]
),
];
It worked well in zend 3. but after updating to Laminas and PHP8.1 I got this error
Laminas\ServiceManager\Exception\ServiceNotCreatedException
File:
/project/vendor/laminas/laminas-servicemanager/src/ServiceManager.php:620
Message:
Service with name "cache_instrument_manager_search" could not be created. Reason: Configuration must contain a "adapter" key.
I have changed it to
return [
'cache_instrument_manager_search' => [
'adapter' => 'Memcached',
'options' => ['ttl' => 3600],
'plugins' => [
[
'name' => 'exception_handler',
'options' => [
'throw_exceptions' => false,
],
],
],
]
];
But Still has this error
Laminas\ServiceManager\Exception\ServiceNotFoundException
File:
/project/vendor/laminas/laminas-servicemanager/src/ServiceManager.php:557
Message:
Unable to resolve service "Memcached" to a factory; are you certain you provided it during configuration?
I need help. I read documents in Laminas but still could not solve this.
I'm using Redis Cache and I had to add:
'Laminas\Cache\Storage\Adapter\Redis'
to my modules.config.php file

Yii2 facebook login

I am trying to integrate facebook login in my website. I created the app and i got the app id and app secret. After successfull login in facebook, how should i got the return data. Here is my code.
public function actions() {
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
'auth' => [
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'oAuthSuccess'],
],
];
}
public function oAuthSuccess($client) {
// get user data from client
$userAttributes = $client->getUserAttributes();
print_r($userAttributes);
exit;
}
here is my config/main.php:
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'authUrl' => 'https://www.facebook.com/dialog/oauth?display=popup',
'clientId' => '****',
'clientSecret' => '*****',
'attributeNames' => ['name', 'email', 'first_name', 'last_name'],
// 'returnUrl' => 'https://www.example.com/site/auth',
],
],
],
Is it required to give any return url?
After login to the facebook it returned to a not found page. What is the issue?

Yii2 Rest Custom actions with OPTIONS request

I am working on api up to now it has only been tested in Postman so cors wasnt an issue. However now developing the front end and when it comes to custom Yii actions they are failing the preflight request. I solved this by adding these lines to url-manager config:
[
'class' => 'yii\rest\UrlRule',
'controller' => ['v1/call-rates'],
'pluralize' => false,
'extraPatterns' => [
'OPTIONS' => 'options',
'GET all-resellers' => 'all-resellers',
'POST updatefromcsv' => 'updatefromcsv',
'OPTIONS all-resellers' => 'options',
'OPTIONS updatefromcsv' => 'options',
// other end points....
],
So every custom action has to have a corresponding OPTIONS pattern. I have seen on a similar question that it is possible to apply the OPTIONS pattern to all custom actions in one line like so:
[
'class' => 'yii\rest\UrlRule',
'controller' => [
'v1/call-rates',
// rest of controllers...
],
'pluralize' => false,
'extraPatterns' => [
'OPTIONS <action:\w+>' => 'options',
],
],
However that is not working. I have also tried with a token like this:
[
'class' => 'yii\rest\UrlRule',
'controller' => [
'v1/call-rates'
],
'tokens' => [
'{action}' => '<action:\\w+>',
],
'pluralize' => false,
'extraPatterns' => [
'OPTIONS {action}' => 'options',
],
],
But again no luck. Any help would be appreciated. Thank you in advance.
Solved by adding the following in to urlmanager config:
[
'class' => 'yii\rest\UrlRule',
'controller' => [
'v1/call-rates',
'v1/call-recordings',
],
'tokens' => [
'{action}' => '<action:[a-zA-Z0-9\\-]+>',
],
'pluralize' => false,
'extraPatterns' => [
'OPTIONS {action}' => 'options',
'OPTIONS' => 'options'
],
],
Because my custom actions were named like:
public function actionGetResellers
The Url would be get-resellers so the pattern was incorrect as it didn't accept -'s. So now what whatever controller I add it will add OPTIONS pattern for every custom action
I use Regular Expression <action:\w+-\w+>. Here is the solution:
[
'class' => 'yii\rest\UrlRule', //
'controller' => 'v1/content/my',
'pluralize' => false,
'extraPatterns' => [
'OPTIONS <action:\w+-\w+>' => 'options',
'GET foot-print' => 'foot-print',
'GET my-courses' => 'my-courses',
]

CakePHP 3 Rest Api JWT plugin Form login Not working

I am using ADmad/cakephp-jwt-auth plugin for Json web token authentication for rest api.
For the token generation we i am sending email and password to login via form . but it fails i don't what is issue.
Here is the my settings. in AppController.php
$this->loadComponent('Auth', [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
],
'authenticate' => [
'ADmad/JwtAuth.Jwt' => [
'parameter' => '_token',
'userModel' => 'Users',
'scope' => ['Users.active' => 1],
'fields' => [
'id' => 'id'
]
]
],
'unauthorizedRedirect' => false,
// Config below is available since CakePHP 3.1.
// It makes user info available in controller's beforeFilter() which is not possible in CakePHP 3.0.
'checkAuthIn' => 'Controller.initialize',
]);
UsersController Token generation method script;
public function token(){
$user = $this->Auth->identify();
if (!$user) {
throw new UnauthorizedException('Invalid email or password');
}
$this->set([
'success' => true,
'data' => [
'token' => $token = \JWT::encode([
'id' => $user['id'],
'exp' => time() + 604800
],
Security::salt())
],
'_serialize' => ['success', 'data']
]);
}
The json data i am posting is
{
'email' : 'muni#smart.com',
'password': '123'
}
Please say me what is mistake?
Form must be in the authenticate
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
],
'ADmad/JwtAuth.Jwt' => [
'parameter' => '_token',
'userModel' => 'Users',
'fields' => [
'id' => 'id'
]
]
]
]);

Cant use tockens and extrapattern together for REST services in Yii2

Yii2 REST query
I found this for using custom action in the controller for that i added the extrapattern mentioned in the above link
And its working fine when we search .but cant use the normal actions for the controller
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country',
'extraPatterns' => [
'GET search' => 'search'
],
'tokens' => [
'{id}' => '<id:\\w+>'
]
]
],
]
Regards
Thanks all
this solved my problem after lots of trying..
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country',
'extraPatterns' => [
'GET search' => 'search'
],
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country',
'tokens' => [
'{id}' => '<id:\\w+>'
]
],
],