Simultaneous authorization in advanced app - php

In advanced app, I tried to implement divided authorization for backend and frontend.
In first case, I used User class from basic app, in order to use users without database. But for frontend part, I used User class from advanced app.
It would seemthat everything is working perfectly. But when you try to log in at the same time on both sides, the latter takes precedence over the previous one. Ie after entering the frontend parts - automatically eject the user from the backend and vice versa.

You have to set different cookies for frontend and backend in config/main.php file. For Eg.:
In backend:
'components' => [
'session' => [
'name' => 'BACKENDID', //Set name
'savePath' => __DIR__ . '/../tmp', //create tmp folder and set path
],
],
In Frontend:
'components' => [
'session' => [
'name' => 'FRONTENDID',
'savePath' => __DIR__ . '/../tmp',
],
],

Related

Separate authentication for front-end user and admin in cakephp 3.x

We are working on a project where are 4 roles. But in cakephp 3.x Auth component holds authenticate user data in session with Auth.User indexing using
$this->Auth->setUser($user);
Due to this we are not able to access front-end user account from admin panel for some purpose, because of when we login to front-end user from admin panel, front-end login action performs and over write of session value.
So if there is any process to handle this please suggest us.
Thank you in advance.
As well I have understood that you are not using prefix to manage back-end and front-end user then may be you worked with separate folder structure for back-end, May I right?
You are right that $this->Auth->setUser($user); always holds session with Auth.User indexing. So you need to write different session indexing for back-end, and you can do it as follow :
For back-end user authentication :
**
$this->loadComponent('Auth', [
'authorize' => ['Controller'], // Added this line
'loginRedirect' => [
'controller' => 'Users',
'action' => 'dashboard',
'prefix' => 'admin_panel'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login',
'prefix' => 'admin_panel'
],
'storage' => [
'className' => 'Session',
'key' => 'Auth.Admin',
]
]);
**
Here you can pass your desired index in 'storage' array key value.
I think it'll works for you.
Check out the section Authentication and Authorization in this curated list of CakePHP Plugins.
You could, for example, use dereuromarks TinyAuth Plugin to authorize your users and configure what they are able to see.
This way you can use the same authentication (be aware of the differences between Authentication and Authorization) and the same users table, which will prevent the Session conflict you mentioned.
The Auth component overwrite the previous session because it store the session in Auth.users all the time so we have to change the session key for different role.
If you are using URL prefix for the different roles to access then you can do like this.
AppController.php
public function beforeFilter(Event $event)
{
if($this->request->params['prefix']){
$this->Auth->config('storage', [
'key'=>'Auth.'.$this->request->params['prefix'],
'className'=>'Session'
]);
}
return parent::beforeFilter($event); // TODO: Change the autogenerated stub
}
This will create different roles in Auth as you required.
The session will be like this
[
'Auth'=>[
'User'=>['id'=>''],
'Admin'=>['id'=>''],
]
]
Tested it, working great for me.

Yii2 logger not exporting messages from log targets

I'm tightening up the logging for our Yii2 application and are struggling with getting the Logger to actually write messages to a log file when dealing with specific categories.
Our project consists of the following Yii2 'Applications' : console, common, frontend, backend and the logging for each of these components work fine for Exceptions generated by Yii and general PHP Exceptions. However when I add some info messages for a specific category in the console part (which I execute by running commands via SHH) the directory that the file should be in is created but the file itself is not. I see that the newly specified log messages are inside the correct 'FileTarget' when I do a var_dump of it.
I've set the flushInterval of the 'log' component to 1 and the exportInterval of the logTarget to 1 to make sure that the messages are to be written to the targets directly. I'm aware that this should be set to a larger value at some point, but for now I want to make sure that the logs are actually being saved. Changing the interval values doesn't seem to have any effect.
A workaround I came up with is to manually call target->export() for the specific FileTarget. This is how I currently make sure logs are being written:
In the Controller where I want to log message I do
Yii::info('Report created succesfully.', 'reports-create');
UtilitiesController::forceLogExport('reports-create');
The forceLogExport method does this:
public function forceLogExport($categoryName = ''){
$logger = \Yii::getLogger();
foreach($logger->dispatcher->targets as $target){
if(!empty($categoryName)){
foreach($target->categories as $category){
if($category == $categoryName){
$target->export();
}
}
}
}
$logger->flush(true);
}
This does actually write the logs to the .log file, however there seem to be duplicate entries in the log now and it feels just plain wrong to call an export after every message.
As I read in the docs the actual writing of logs only happens when either these intervals are met OR when the application ends. I could imagine the application not ending properly so I tried forcing this by calling Yii:$app->end() directly after logging the message, but the file stays empty.
Since the problem is neither the application not ending (I can see that it does end) nor the interval being met (I see at least one message in the target and the interval is set to 1) I'm kind of at my wit's end why the logs are not exported. If anyone could perhaps elaborate any further on when/where Yii calls the ->export() method itself that would be a big help.
EDIT: added the console/config/main.php settings. Slightly changed my story, initially I wrote that 'the log file was being created but the messages were not being written in it.' but in fact only the directory that should contain the files was created, not the log file itself.
<?php
return [
'id' => 'console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
],
'session' => [ // for use session in console application
'class' => 'yii\web\Session'
],
'log' => [
'flushInterval' => 1,
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error','info', 'warning'],
'categories' => ['reports-schedule'],
'exportInterval' => 1,
'logVars' => [null],
'logFile' => '#app/../logs/console/'. date('Y') . '/' . date('m') . '/reports-schedule/' . 'reports-schedule_' . date('d-m-Y') . '.log'
],
[
'class' => 'yii\log\FileTarget',
'levels' => ['error','info', 'warning'],
'categories' => ['reports-create'],
'exportInterval' => 1,
'logVars' => [null],
'logFile' => '#app/../logs/console/'. date('Y') . '/' . date('m') . '/reports-create/' . 'reports-create_' . date('d-m-Y') . '.log'
],
// and 6 other similarly structured targets
[...],
[...],
[...],
[...],
[...],
[...],
],
]
];
UPDATE: it seems like I'll have to stick to manually calling ->export() on the desired log target. The problem I had with duplicate log entries (same message, same timestamp) being written was due to the fact that I had set the exportInterval property to 1 for the target (which I initially did to make sure the messages were exported at all). I suppose the logger stores messages until the value of exportInterval is met and then expect those messages to be written to the targets. I fixed duplicate entries from being written by removed the exportInterval property so Yii takes the default value (1000). For my case this would be sufficient since I wouldn't run into those numbers but for anyone reading this please consider your use case and check if you would run into anything close to that in a single cycle.
I had a similar issue at some point and I think this should be sufficient enough for your case.
Yii::$app->log->targets['reports-schedule']->logFile = $logPath;
Yii::info($message, $category);
Yii::getLogger()->flush();
This way you can specify a dynamic log path inside your schedule target and after flush the logger continues as it should.

Yii2 make a path alias from information stored in DB

Right now I'm trying to implement themming for my Yii2 based project.
How I see the thing now:
User chooses an application theme from the list on the settings
page in backend.
Using yii2-settings I'm saving all the
configuration data in DB (pretty easy).
In the application
bootstrap.php I'm creating new alias called #theme. Basically it
should lead us to a application theme base path (used in search
paths, assets manager, e.t.c.).
According to official
documentation, that's how I configured my view component:
'view' => [
'theme' => [
'basePath' => '#theme',
'baseUrl' => '#theme',
'pathMap' => [
'#app/views' => '#theme',
'#app/widgets' => '#theme/widgets',
'#app/modules' => '#theme/modules',
],
],
],
An issue I have is with p.3. According to yii2-settings documentation that's how I supposed to read the settings:
$theme = Yii::$app->settings->get('name', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
But obviously, it's not working for me because of yii2-settings component didn't initialized yet when bootstrap.php is called. I've been trying to initialize it later in the init() method of my base controller, then adjust other aliases manually, but I feel that way being somewhat 'unclean', and also it still fails because of #theme alias is also used in asset file which is Yii2 starting to publish before calling the controller's init method.
So does anyone has any thoughts of how to do that 'hacking' the code as less as possible? I know I could just move configuration to some file, then read it manually before the application initialization, but it's still not the way I want to go.
Maybe there's some way to override some system component to set the alias after db component is loaded, but before view component configuration? Or Yii loads this components in a different order? Anyway. Any help would be appreciated!
You could try an Application Event in bootstrap:
\Yii::$app->on(\yii\base\Application::EVENT_BEFORE_REQUEST, function ($event) {
$theme = Yii::$app->settings->get('name', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
});
OR in configuration file:
[
'on beforeRequest' => function ($event) {
// ...
},
]
From Yii 2 docs:
EVENT_BEFORE_REQUEST This event is triggered before an application
handles a request. The actual event name is beforeRequest.
When this event is triggered, the application instance has been
configured and initialized. So it is a good place to insert your
custom code via the event mechanism to intercept the request handling
process. For example, in the event handler, you may dynamically set
the yii\base\Application::$language property based on some parameters.
Here's the final solution:
config/bootstrap.php:
// Setting a temporary path for components configuration - will be changed later
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/"));
config/main.php
'components' => [
'view' => [
'theme' => [
'basePath' => '#theme',
'baseUrl' => '#theme',
'pathMap' => [
'#app/views' => '#theme',
'#app/widgets' => '#theme/widgets',
'#app/modules' => '#theme/modules',
],
],
],
],
'on beforeRequest' => function ($event) {
$theme = Yii::$app->settings->get('theme', 'general');
Yii::setAlias('#theme', realpath(dirname(__FILE__)."/../../themes/$theme"));
},

Yii2 session problems for multiple application in single domain

We configured like /var/www/app1 and /var/www/app2 , Both are logging in single session. How can I make this different session.
I tried with following solution from yii2 wiki. But it doesn't workout here.
'identityCookie' => [
'name' => '_backendUser', // unique for backend
'path'=>'/advanced/backend/web' // correct path for the backend app.
]
Please give solution for this issue.
Use a different session $name for each application. This can be set in your config as:
'components' => [
'session' => [
'class' => '\yii\web\Session',
'name' => 'mycustomname',

ZF2: Define URL http or https

Here is my problem.
I have a few pages in my application who uses SSL, like the lggin page. When i am in the main page (who doens't have SSL), every link created by the view ( href=$this->url(...) ) is plain html, even the login page. On the other hand, when i am in the login page, every other links displays with https.
In the controller, i manipulate if the page uses SSL or not, that is OK. But i want to show the correct link for the user when he navigates through the site, https for ssl pages and http for non-ssl ones.
Thanks.
First of all, if you have HTTPS available, you should use it on any page. It is really against the web of trust when you have some pages available via HTTPS, but others not. Sure, you might enforce HTTPS on some pages (so there is no HTTP), but vice versa is always a bad idea.
That being said, you can create a scheme route. With the scheme you are able to specify HTTPS on some routes:
'secure' => [
'type' => 'scheme',
'options' => [
'scheme' => 'https',
'defaults' => [
// the usual stuff
],
],
'may_terminate' => false,
'child_routes' => [
// all your https routes here
],
],
Because some of these "secure" routes might be defined at vendor level (e.g. you use ZfcUser), you can use "prototyping" of routes. For example all ZfcUser routes should only be accessible via HTTPS. The "main" route of ZfcUser is zfcuser:
'router' => [
'prototypes' => [
// Define "secure" prototype to add to routes
'secure' => [
'type' => 'scheme',
'options' => ['scheme': 'https'],
],
],
// Apply the scheme route to ZfcUser
'routes' => [
'zfcuser' => [
'chain_routes' => ['secure'],
],
],
],
Prototyping "prepends" the secure route to zfcuser. So this makes zfcuser and all its childs a child-route of secure. Therefore, all zfcuser routes are defined with HTTPS.
When you've come this far: if you now assemble the routes, they will get HTTPS automatically. When you have a route login inside the secure route of my first example, you get the url via $this->url('secure/login');.
In the second case (prototyping) you don't need to mention the prototype, just use $this->url('zfcuser'); for the user's route.

Categories