Yii2 - module login in basic application template - yii2

Using the "basic" application template, what is the correct way of setting up a module login that is separate from the main site login?
For example I have an "admin" module which requires a login. I also need a user login for the main site.
I have done the following:
Created admin module using gii tool
Created models folder within the admin module folder
Placed LoginForm.php and User.php within this folder (also updated the namespace declarations in these files)
Added AccessControl behaviour and login/logout actions to modules\admin\controllers\DefaultController.php
Updated config\web.php as follows:
'modules' => [
'admin' => [
'class' => 'app\modules\admin\Module',
],
],
Updated app\modules\admin\Module.php as follows:
public function init()
{
parent::init();
Yii::$app->set('user', [
'class' => 'yii\web\User',
'identityClass' => 'app\modules\admin\models\User',
'enableAutoLogin' => true,
'loginUrl' => ['admin/default/login'],
]);
Yii::$app->set('session', [
'class' => 'yii\web\Session',
'name' => '_adminSessionId',
]);
}
The problem I am having is that if I try to access an admin page when I am not logged in, it shows the login form (this is correct). However upon logging in, it is just redirects me back to the main site. It should redirect me to the admin page I was trying to access.
In DefaultController.php, it has the following (default code):
if ($model->load(Yii::$app->request->post()) && $model->login())
return $this->goBack();
What is the correct way of doing this so I can have independent logins for the admin module and for the main site? I don't want to use the "advanced application template" as that adds some unnecessary complexity.

The User component allows you to set a returnUrl, the getter explained: This method reads the return URL from the session. It is usually used by the login action which may call this method to redirect the browser to where it goes after successful authentication.
Recommended: Before processing the data, set the returnUrl by calling Yii::$app->user->setReturnUrl(Url::current()); (this will store the page the user was on in the session, moreover, you can manipulate GET parameters using Url::current() before passing it to the session), and let the framework do its magic.
Not recommended: After processing the data, you can rely on referrer (which won't work in some cases) as following
return Yii::$app->request->referrer ? $this->redirect(Yii::$app->request->referrer) : $this->goHome(); or instead of goHome which basically redirects to app->homeUrl that can be set during Module init, you could say $this->redirect('your/admin/index');
I recommend setting the ['homeUrl' => 'your/admin/index'] during the initialization of the Module, as you might need it for other features as well and Yii2 uses it as a "fallback" to some redirects as well.

The best way is to create new controller in the admin module, which should have login, logout actions. Because, in future you may add there some extra logic.
In that login action you can use same LoginForm.
You can specify redirect url in that login action.
Admin module class can looks like this:
namespace app\modules\admin;
class Module extends \yii\base\Module
{
public $layout = 'main';
public $defaultRoute = 'main/index';
public function init()
{
parent::init();
Yii::$app->errorHandler->errorAction = '/admin/main/error';
Yii::$app->user->loginUrl = '/admin/main/login';
.....
}
}

goBack() defaults to the homeUrl if the returnUrl for the user hasn't been set.
Why not just redirect?
if ($model->load(Yii::$app->request->post()) && $model->login())
return $this->redirect(['myadminmodule']);

go to config/web.php and add it to the components
'backendUrlManager'=>[
'class' => 'yii\web\urlManager',
'enablePrettyUrl'=>true,
'showScriptName'=>false,
'baseUrl'=>'/admin',
],
In DefaultController.php, it has the following (default code):
if ($model->load(Yii::$app->request->post()) && $model->login())
return Yii::$app->getResponse()->redirect(Yii::$app->backendUrlManager->baseUrl);

Related

Yii 2 Module wise configuration setting

I have setup Yii2 nested module and I want to set different configuration and each modules has own component and other settings with there own models
Like in School Management System, I have created a nested module like V1 is my API (main module) and under these, I have created a Student module, Teacher module, Parent module, driver module, admin module each has a different table and different model. I want to login differently with each user like..
API calls for each
https://example.com/v1/admin/login
https://example.com/v1/student/login
https://example.com/v1/parent/login
https://example.com/v1/user/login
https://example.com/v1/driver/login
How can I manage these login and their own configuration?
Thanks
Jitendra
In the module Class you can set components, aliases and other settings and using something like this:
Here is an example for the admin module:
class Admin extends Module
{
// ...
/**
* {#inheritdoc}
*/
public function init()
{
parent::init();
// custom initialization code goes here
$this->setComponents([
// array of components
]);
// ...
}
}
or if you prefer you can set the components like this
$this->components = [
// array of components
]);
if you are using nested modules, you are already specifying "settings" for the module - i.e all sub modules
To use different login for all modules when specifying components set different name for the identityCookie of the user component for each module.
Example for admin module:
$this->components => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-admin', 'httpOnly' => true],
],
// ... other components

accessing an array in a component from the layout in yii2

I need to check the records in the notifications table at every page load of every controller.
So I wrote it in a component and the component is executed in the bootstraping process.
I need the notifications to be available in the layout so that i can show them in the notification menu.
below is what I have tried so far:
component:
namespace admin\components;
use Yii;
use yii\base\Component;
use admin\models\Notification;
class NotificationManager extends \yii\base\Component{
public function init() {
$notifications = Notification::find()->orderBy('id DESC')->asArray()->all();
//echo "<pre>"; print_r($notifications);exit;
if(count($notifications)>0){
foreach ($notifications as $notif) {
if($notif['type'] == 'courier')
$courier_notifications[] = $notif;
elseif($notif['type'] == 'order')
$order_notifications[] = $notif;
}
Yii::$app->view->params['courier_notifications'] = $courier_notifications;
Yii::$app->view->params['order_notifications'] = $order_notifications;
}
}
}
Layout:
$courier_notifications = $this->params['courier_notifications'];
I am not sure which part am I going wrong: in component or in the layout?
I appreciate your help.
Im not sure why your component execution during bootstrap fails to add the value to params.But believe it to be an overkill.
You can rather move the logic to component method and access in layout whenever necessary
Component.
namespace admin\components;
use Yii;
use yii\base\Component;
use admin\models\Notification;
class NotificationManager extends Component{
public function notifications($type = 'courier') {
$notifications = Notification::find()
->where(['type' => $type])
->orderBy('id DESC')
->asArray()->all();
return $notifications;
}
}
Add the component class under Components section in your config file
'notificationManager ' => [
'class' => 'admin\components\NotificationManager'
]
Layout
$courier_notifications = yii::$app->notificationManager->notifications('courier');
If you really want to go bootstrap mode, you need to implement yii\base\BootstrapInterface and put your logic in the bootstrap($app) method in order for the param to be available site-wide by setting the value of Yii::$app->params['notifications'] to the result of your logic.
Another common approach is to add a new method public function displayNotifications or whatever you want to name it, to your component, move all the logic in it and then in your layout/view etc., call it with Yii::$app->notificationManager->displayNotifications(). You can also pass additional parameters to it and enhance your logic.
notificationManager has to be replaced with the name you registered your custom component in the Yii app config (web.php for basic app, main.php for advanced app).
LE - If you only registered your component for bootstrap, you should also register it in the components array.
'notificationManager' => [
'class' => '\admin\components\NotificationManager'
]

Why Authorize is to set to Controller in AuthComponent?

Why authorize is to set to Controller while Authentication is done in AppController?
Like: I got it when Blog example is doing but did not get details explanation on it
$this->loadComponent('Auth', [
'authorize' => ['Controller']
]);
I read the Authorize Section but could not understand it. So Could someone please help making me understand it?
The book is describing how you would control your own authorization at the controller level.
Authentication identifies a valid user. If any logged in user may access any part of your app, then you don't need to implement any further authorization. But if you wish to restrict access to certain controllers, based on role for example, you could set 'authorize' => ['Controller'] in the Auth config as described, and then in each controller define your own isAuthorized() method, based on the role of the user.
For example, if in your InvoicesController you only want to let users whose role is 'Accounting' access the methods, you could include a test for that in an isAuthorized() method in the InvoicesController:
// src/Controller/InvoicesController.php
class InvoicesController extends AppController
{
public function isAuthorized($user)
{
if ($user['role'] === 'Accounting'){
return true;
}
return parent::isAuthorized($user);
}
// other methods
}

Execute my code before any action of any controller

I would like to check if my user have filled certain fields in his profile before he can access any action of any controller.
For example
if(empty(field1) && empty(field2))
{
header("Location:/site/error")
}
In yii1 I could do it in protected\components\Controller.php in init() function
But in yii2 I'm not sure where to put my code. I cannot modify core files, but not sure what to do in backend of my advanced application to make it work.
I know I can user beforeAction() but I have too many controllers to do that and to keep track of every controller
In case you need to execute a code before every controller and action, you can do like below:
1 - Add a component into your components directory, for example(MyGlobalClass):
namespace app\components;
class MyGlobalClass extends \yii\base\Component{
public function init() {
echo "Hi";
parent::init();
}
}
2 - Add MyGlobalClass component into your components array in config file:
'components' => [
'MyGlobalClass'=>[
'class'=>'app\components\MyGlobalClass'
],
//other components
3 - Add MyGlobalClass into bootstarp array in config file:
'bootstrap' => ['log','MyGlobalClass'],
Now, you can see Hi before every action.
Please note that, if you do not need to use Events and Behaviors you can use \yii\base\Object instead of \yii\base\Component
Just add in config file into $config array:
'on beforeAction' => function ($event) {
echo "Hello";
},
Create a new controller
namespace backend\components;
class Controller extends \yii\web\Controller {
public function beforeAction($event)
{
..............
return parent::beforeAction($event);
}
}
All your controllers should now extend backend\components\Controller and not \yii\web\Controller. with this, you should modify every controller. I would go for this solution.
I believe you might also replace 1 class with another (so no change to any controller necessary), something like
\Yii::$classMap = array_merge(\Yii::$classMap,[
'\yii\web\Controller'=>'backend\components\Controller',
]);
See more details here: http://www.yiiframework.com/doc-2.0/guide-tutorial-yii-integration.html and I took the code from here: https://github.com/mithun12000/adminUI/blob/master/src/AdminUiBootstrap.php
you can put this in your index.php file. However, make sure you document this change very well as somebody that will come and try to debug your code will be totally confused by this.
Just i think this code on config file can help you:
'on beforeAction' => function ($event) {
// To log all request information
},
'components' => [
'response' => [
'on beforeSend' => function($event) {
// To log all response information
},
],
];
Or, https://github.com/yiisoft/yii2/blob/master/docs/guide/security-authorization.md use RBAC, to restrict access to controllers actions one at a time based on rules. Why would you want to restrict access to controller actions based on user fields is beyond me. You will not be able to access anything (including the login form) if you put a restriction there.

ZF2 View strategy

I'm trying to implement the following:
Simple controller and action. Action should return response of 2 types depending on the request:
HTML in case of ordinary request (text\html),
JSON in case of ajax request (application\json)
I've managed to do this via a plugin for controller, but this requres to write
return $this->myCallBackFunction($data)
in each action. And what if I wan't to do this to whole controller? Was trying to figure out how to implement it via event listener, but could not succed.
Any tips or link to some article would be appreciated!
ZF2 has the acceptable view model selector controller plugin specifically for this purpose. It will select an appropriate ViewModel based on a mapping you define by looking at the Accepts header sent by the client.
For your example, you first need to enable the JSON view strategy by adding it to your view manager config (typically in module.config.php):
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy'
)
),
(It's likely you'll already have a view_manager key in there, in which case add the 'strategies' part to your current configuration.)
Then in your controller you call the controller plugin, using your mapping as the parameter:
class IndexController extends AbstractActionController
{
protected $acceptMapping = array(
'Zend\View\Model\ViewModel' => array(
'text/html'
),
'Zend\View\Model\JsonModel' => array(
'application/json'
)
);
public function indexAction()
{
$viewModel = $this->acceptableViewModelSelector($this->acceptMapping);
return $viewModel;
}
}
This will return a normal ViewModel for standard requests, and a JsonModel for requests that accept a JSON response (i.e. AJAX requests).
Any variables you assign to the JsonModel will be shown in the JSON output.