Receive white screen when adding guards to bjyauthorize - php

I'm new to ZF2 and bjyauthorize - so in a way hoping this is a silly mistake on my part :D
I have setup the ZF2 skeleton app and zfcUser successfully and am trying to add bjyAuthorize to the mix. I am also using the Zend/Db connection type to mySQL - NOT DOCTRINE (:D). The versions I am using are PHP(5.5), ZF2(2.3.*), zfcUser(1.2.1), bjyAuthorize(1.4.0).
I have followed the instructions found to the letter in the GitHub Readme. It didn't take me long to realise that the example "bjyauthorize.global.php" file there contains way too many settings (as examples) and also has an incorrect field reference under "\BjyAuthorize\Provider\Role\ZendDb::class" ("role_id" s/b "roleid").
Basically, as soon as I uncomment either the route based or controller based guards in my config file (i don't intend to do both - just want one working) I get a white screen - no error message to be helpful - when trying to access my skeleton apps home page. I'm worried this is therefore a PHP syntax error on my part.
I have also included ZendDeveloperTools and not even the tool bar on the footer appears when I get this error.
Here is my config file:
<?php
return [
'bjyauthorize' => [
// set the 'guest' role as default (must be defined in a role provider)
'default_role' => 'guest',
/* this module uses a meta-role that inherits from any roles that should
* be applied to the active user. the identity provider tells us which
* roles the "identity role" should inherit from.
*
* for ZfcUser, this will be your default identity provider
*/
'identity_provider' => \BjyAuthorize\Provider\Identity\ZfcUserZendDb::class,
/* role providers simply provide a list of roles that should be inserted
* into the Zend\Acl instance. the module comes with two providers, one
* to specify roles in a config file and one to load roles using a
* Zend\Db adapter.
*/
'role_providers' => [
// this will load roles from the user_role table in a database
// format: user_role(role_id(varchar], parent(varchar))
\BjyAuthorize\Provider\Role\ZendDb::class => [
'table' => 'user_role',
'identifier_field_name' => 'id',
'role_id_field' => 'roleid',
'parent_role_field' => 'parent_id',
],
],
/* Currently, only controller and route guards exist
*
* Consider enabling either the controller or the route guard depending on your needs.
*/
'guards' => [
/* If this guard is specified here (i.e. it is enabled], it will block
* access to all controllers and actions unless they are specified here.
* You may omit the 'action' index to allow access to the entire controller
*/
// \BjyAuthorize\Guard\Controller::class => [
// ['controller' => 'zfcuser', 'roles' => ['guest']],
// ['controller' => ['Application\Controller\Index'], 'roles' => ['guest']],
// ],
// /* If this guard is specified here (i.e. it is enabled], it will block
// * access to all routes unless they are specified here.
// */
// \BjyAuthorize\Guard\Route::class => [
// ['route' => 'zfcuser', 'roles' => ['user']],
// ['route' => 'zfcuser/logout', 'roles' => ['user']],
// ['route' => 'zfcuser/login', 'roles' => ['guest']],
// ['route' => 'zfcuser/register', 'roles' => ['guest']],
// // Below is the default index action used by the ZendSkeletonApplication
// ['route' => 'home', 'roles' => ['guest', 'user']],
// ],
],
],
];
When I run as coded above without guards, I can login through site/user/login and the Zend Dev ToolBar shows me the correct role for that user. So that is at least positive.
Happy to provide any further info or settings - just trying to learn.

OK, so I feel quite silly now.
The DB schema that bjyauthorize ships with has the field "roleId" - in my code above I didn't take into account case sensitivity and had "roleid". Changed that and everything works perfectly.

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 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"));
},

CakePHP 3.2 - Specify different datasource for session handler

I am having an issue specifying a different datasource to use in a custom session handler inside config/app.php. Here are the relevant bits:
config/app.php
<?php
return [
... ,
'Datasources' => [
'default' => [...],
'test' => [...],
'session' => [...]
],
'Session' => [
'defaults' => 'database',
'ini' => ['session.cookie_domain' => '.example.com'],
'handler' => [
'engine' => 'CustomSessionHandler', // file and class name of custom handler
'model' => 'sessions' // table name
]
]
];
CustomSessionHandler.php is a copy of the default DatabaseSession.php with a few customisations in the query building to work with our existing sessions table schema.
Right now, it's trying to use the 'default' datasource, and as you might guess, I'm trying to get it to use the 'session' datasource. However I can't find any information on how to do that.
Any assistance is greatly appreciated!
The session handler only knows about the model, respectively the table class, and it shouldn't really know more than that.
So what you could do is configure that table class to use a non-default connection. If you don't have a concrete SessionsTable class yet, create one, and override Table::defaultConnectionName(), like
public static function defaultConnectionName()
{
return 'session';
}
See also Cookbook > Database Access & ORM > Table Objects > Configuring Connections

How to use laravel's Auth class in different table?

I created a simple login and registration in my page and I also added some new columns in the default users table. Now my problem is I have another table named as admin and the default Laravel's Auth table is users. How can I implement the same functionality in my table?
In the Users model it has the declaration for the table name
protected $table = 'users';
Can you give me an example how can I use the default laravel's auth class?
Thats all thanks. :-)
Laravel takes default users table for an application. For a change of laravel authentication different table relevant table name, we need to make a small change in authentication file of config.
Go to
config/auth.php
'providers' => [
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\User::class,
// ],
'users' => [
'driver' => 'database',
'table' => 'user',
],
],
Do you hear about Multiauth in laravel. in this library there are two or more type user can login in one laravel application. In our case there are two type user Admin and Public that means User right.
Both forgot password and reset password functionality works separately in one application.
After install this library have have one step like below.
'multi' => [ 'admin' => [ 'driver' => 'database', 'table' => 'admin', 'email' => 'client.emails.password' ], 'users' => [ 'driver' => 'database', 'table' => 'users', 'email' => 'client.emails.password', ] ],
change your Auth.php file code with this one.
installation
Firstly you want to include this package in your composer.json file.
"require": {
"sboo/multiauth" : "4.0.*"
}
Now you'll want to update or install via composer.
composer update
Usage
Everything is done the exact same way as the original library, the one exception being that all method calls are prefixed with the key (account or user in the above examples) as a method itself.
Auth::admin()->attempt(array(
'email' => $attributes['email'],
'password' => $attributes['password'],
));
Auth::client()->attempt(array(
'email' => $attributes['email'],
'password' => $attributes['password'],
));
Auth::admin()->check();
Auth::client()->check();
Here is your library
I don't think the best way is to duplicate your table. I would extend users table with a role field that indicates if the user is a standard one or an admin. This way, you can keep the same code and add the ADMIN functionality that you are looking for.
If you NEED to do that and you are using Laravel 4, maybe you can use this plugin:
https://github.com/ollieread/multiauth/
Also in this thread you have code that implements Auth in different tables:
https://gist.github.com/danielcoimbra/64b779b4d9e522bc3373
But I strongly suggest to integrate both tables in one with an Admin flag/field

Doubts about Yii2 RBAC

I've been developing web apps using Yii 1.1.14 so far, but now it's time for an upgrade.
The company where I work has developed its own Access Control system, and I was really OK with it until I saw what it was really like... A combination of 8 tables in the database (not counting the users table), with a bunch of foreign keys.
1 table for controllers
1 table for the actions
1 table for the menu categories
1 table for types of users
And the other tables basically just connect 2 or 3 of those tables at a time.
It works well, but in my point of view it's highly time consuming to maintain all those tables, and at some point, when your application goes online, if it hits a certain amount of users it could get really slow. specially because 2 of those tables have the user's table primary key as foreign key.
So I've decided that, when I start developing on Yii 2, I'm going to start using RBAC, so I started looking for tutorials online... Only finding many different versions of the same code with author's role, and permissions for create or update posts.
I found a combination of 5 videos on Youtube, but they are about Yii 1 RBAC. They were helpful because I managed to understand most of RBAC's functionality, but I still have some doubts that I'll
enumerate below. And keep in mind that for this Access Control system I'm using the DBManager class.
My Doubts
Yii 1's RBAC used to have 3 tables: auth_assignment, auth_item and auth_item_child. Now in Yii 2 RBAC, a new table appears that is called auth_rule and I still don't understand what that specific table is doing there, how to use it or how to populate it.
I see that it's possible to restrict the user's access to some actions by using the controller's behavior method, and assigning access to some actions depending on the user's role, but when it comes to this I have to split my question into 2:
2.1. First: If you can just restrict the access to actions by setting it up in the behaviors method, then what's the use of saving permissions to the auth_item table?
2.2. Second: If you DO decide to control access according to permissions, then how exactly do you do it, because I find myself writing the following type of code inside of every function and I don't think using RBAC is supposed to be this tedious. There has to be another way.
public function actionView($id)
{
if(Yii::$app->user->can('view-users')){
return $this->render('view', [
'model' => $this->findModel($id),
]);
}else{
#Redirect to a custom made action that will show a view
#with a custom error message
$this->redirect(['//site/notauthorized']);
}
}
Because of the Access Control System that we use right now, when a user logs in, a complex query is executed that will end up returning an array that will be saved as a session variable, and will be used to create a menu with as many dropdownlists as menu categories, that the controllers that the user has access to belong to. How can this be done with RBAC?
I can only really answer 2.2 of your question, as 3 doesn't sound at all like something an RBAC should do. You could, however, get the information you needed from the rules table most likely, provided you followed a naming convention that matched your controllers or actions.
On to answering 2.2 though:
You can simply set the behavior like such:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['view'],
'roles' => ['view-users'], //<-- Note, rule instead of role
],
]
]
}
This doesn't solve a different problem of 'view-own-users' style permissions, as this needs to inspect the ActiveRecord model (well, at least it does in my application). If You want to achieve this, take a look at my post in the Yii forums here:
http://www.yiiframework.com/forum/index.php/topic/60439-yii2-rbac-permissions-in-controller-behaviors/#entry269913
I use it in one of the simplest method,I use them in the behaviours of my controller.
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['sysadmin'],
'actions' => ['index','view','update'],
],
[
'allow' => true,
'roles' => ['staff'],
'actions' => ['index','create','update','view'],
],
],
],
];
}
Here roles are the one created in the auth-item table in the database and they have been assigned for users in auth-assignment table. In the behaviours we just use it as above. In the above code sysadmin can have access to index, view and update action, whereas staff can have access to index,create, update and view action.
Yii2 needs a little setup when it comes to using RBAC under your controllers AccessControl. I got around it by making my own AccessRule file.
namespace app\components;
use Yii;
class AccessRule extends \yii\filters\AccessRule
{
protected function matchRole($user)
{
if (empty($this->roles)) {
return true;
}
foreach ($this->roles as $role) {
if(Yii::$app->authManager->checkAccess($user->identity->code, $role))
return true;
}
return false;
}
then in your controller u can use something like this:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'ruleConfig' => [
'class' => 'app\components\AccessRule'
],
'rules' => [
[
'actions' => ['index', 'resource-type'],
'allow'=> true,
'roles' => ['admin'],
],
],
],
];
}
Where admin is defined as a auth_item and the user is in the auth_item_assignments.
As I have created a new Rbac system for yii2. you can direct permission for a action and action will show you are not authorisez for this action.
By this you find that you will only provide access for action that need to identify.
I uploaded my detail here you can find lot of solution here.
This is the best solution i could come up with when facing the need to filter access by permissions, it's bothersome but can be useful if you're trying to create roles in a productive enviroment and want to use rbac.
use yii\web\ForbiddenHttpException;
if(Yii::$app->user->can('view-users')){
return $this->render('view', [
'model' => $this->findModel($id),
]);
}else{
throw new ForbiddenHttpException('You dont have access to this site');
}

Categories