Yii framework not checking roles in accessRules - yii

I am creating some kind of admin panel in Yii framework, and im setting state at login like this
public function authenticate()
{
$record=AdminTbl::model()->findByAttributes(array('usr'=>$this->username));
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->pwd!==$this->password)
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$record->id;
$this->setState('roles','main');
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
I checked if state was really set, echoed out on view. Later i put that role in accessrules()
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','create','update','admin','delete'),
'roles'=>array('main'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
And i can't access those pages with this user logged in. What is the problem ?

Have a look here, http://www.yiiframework.com/doc/guide/1.1/en/topics.auth
You need to create the main role and assign it via the user id.

If you need simple Role based access control without the long RBAC process then this article is just for you
http://www.yiiframework.com/wiki/328/simple-rbac/

Related

Laravel Authorize Multiple Permission

I want to control the index of my controller via two permissions, the user must have either 'Permission1' or 'Permission2'. Both together is also possible.
Currently I check for one permission:
$this->authorize('Permission1');
I have tried:
$this->authorize('Permission1' || 'Permission2');
$this->authorize(['Permission1' || 'Permission2']);
$this->authorize(['Permission1', 'Permission2']);
Controller Constructor:
public function __construct()
{
$this->middleware('auth');
$this->middleware('permission:' . Permission::PERMSSION1, ['only' => [
'permission1',
]]); // Here I don't know how to adjust it too
}
And a few more, but nothing seems to work.
How can I query the authorization for Permission1 OR Permission2?
Did you tried with $this->authorizeEither('Permission1', 'Permission2'); ?

Redirect user after login in laravel 5.1

I am trying to implement a feature where, after logging in, a user gets redirected to a URL depending on their role. I have the roles part set up, but I'm having trouble testing the user's properties immediately after login.
I followed the instructions here to create a user login page. I have an AuthController that looks like this:
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/test';
...
}
My __construct() function validates the user, but I don't know how to access the user object only immediately after login. This is what I presently have:
public function __construct() {
$this->middleware('guest', ['except' => 'getLogout']);
if ( \Auth::check() ) {
$user = \Auth::user();
if ( $user->admin() ) {
// an admin
$this->redirectTo = '/admin';
} else {
// it's a client
$this->redirectTo = '/client/dashboard';
}
}
$user = \Auth::user();
if ( is_object($user) ) {
} else {
$this->redirectTo = '/auth-not-object';
}
}
When I first attempt to log in with an administrator account, I get to the path /auth-not-object, because there isn't any authenticated user object at that point.
After having attempted to log in, but getting a bad redirect, when I revisit the /login url, I get redirected to /home, which I believe is the default $redirectTo in the traits this class uses. So that means we've passed the AuthController __construct() method without having changed the $redirectTo, even though there is an authenticated user.
I've found other questions, such as How to add extra logic on login condition in Laravel 5.2 and laravel redirect to url after login, but I don't understand how to apply those answers. For instance, the accepted answer to the second question shows new methods, getCredentials() and login(), which don't exist in the poster's original class. I am not sure in what class to add them, or where to call them from, in my codebase.
Other similar answers show a radically different way of authenticating users, such as this. It seems that, to use that solution, I would need to re-write my code, and forgo the use of the traits, which include bonus features like login throttling and so on.
Is there a way I can redirect users based on role after login, while still using these built-in traits?
Im not sure if the 5.1 auth is the same as the 5.2 auth, but if it is, remove all that from the construct and add this method:
protected function handleUserWasAuthenticated( Request $request, $throttles, $guard )
{
if ($throttles) {
$this->clearLoginAttempts( $request );
}
if ( method_exists( $this, 'authenticated' ) ) {
return $this->authenticated( $request, Auth::guard( $guard )->user() );
}
return redirect()->intended( $this->redirectTo );
}
this is the method that will determine the redirect and you have access to the user object.
EDIT
I take the above back, just add the following to your controller;
protected function authenticated( $request, $user ) {
return redirect()->intended( $user->admin() ? '/admin' : '/client/dashboard' );
}
That should work nicely

Authorization with rbac yii

I am trying to understand authorization in rbac and getting confused a bit with a couple of things.
In the accessControl rules i am using roles as such:
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index', 'view'),
'roles'=>array('user'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'roles'=>array('author'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'roles'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
I am also using the following setup :
$auth = Yii::app()->authManager;
$auth->createOperation('createPost', 'create a post');
$auth->createOperation('readPost', 'Read a post');
$auth->createOperation('updatePost', 'update a post');
$auth->createOperation('deletePost', 'delete a post');
$role = $auth->createRole('user');
$role->addChild('readPost');
$role = $auth->createRole('author');
$role->addChild('user');
$role->addChild('createPost');
$role = $auth->createRole('admin');
$role->addChild('author');
$role->addChild('updatePost');
$role->addChild('deletePost');
$auth->assign('user', 3);
$auth->assign('author', 2);
$auth->assign('admin', 1);
$auth->save();
There are 4 different operations with names (createPost, deletePost , readPost, udpatePost). However in the controller the action names are different such as actionIndex, actionView, actionCreate, actionDelete, actionUpdate and actionAdmin.
Questions:
How are operations being mapped to controller actions.
Should more operations be created such as IndexPost, ViewPost etc ..?
While using rbac, should we still keep the accesscontrol filter and rules as I have done here?
I am not sure if I am doing it right. Lots of confusion and lost. Please shed some light. Cheers.
They aren't being mapped, in each action you need to check this manually
if (Yii::app()->authManager->checkAccess('updatePost'))
thorow new HttpException(404);
Your can create IndexPost, ViewPost if some user can't see these actions.
In accessControl you can keep only check that user is logged, when it's needed.
For more information check this articles: Simple RBAC, Getting to Understand Hierarchical RBAC Scheme

Yii Rights :: Error 403 You Are Not Authorized To Perform This Action

I am newb in yii. I installed yii-rights in protected/modules/rights as per documentation. But can't use properly. There are something missing that I couldn't find out. localhost/index.php/right page is working well. But when I press on "permissions", "roles", "tasks", "operations". It shows
"Error 403
You are not authorized to perform this action."
Here is my main config::
'import'=>array(
'application.modules.right.*',
'application.modules.right.models*',
'application.modules.rights.components.*',
),
'rights'=>array(
'superuserName'=>'Admin', // Name of the role with super user privileges.
'authenticatedName'=>'Authenticated', // Name of the authenticated user role.
'userIdColumn'=>'id', // Name of the user id column in the database.
'userNameColumn'=>'username', // Name of the user name column in the database.
'enableBizRule'=>true, // Whether to enable authorization item business rules.
'enableBizRuleData'=>false, // Whether to enable data for business rules.
'displayDescription'=>true, // Whether to use item description instead of name.
'flashSuccessKey'=>'RightsSuccess', // Key to use for setting success flash messages.
'flashErrorKey'=>'RightsError', // Key to use for setting error flash messages.
'baseUrl'=>'/rights', // Base URL for Rights. Change if module is nested.
'layout'=>'rights.views.layouts.main', // Layout to use for displaying Rights.
'appLayout'=>'application.views.layouts.main', // Application layout.
'cssFile'=>'rights.css', // Style sheet file to use for Rights.
'install'=>false, // Whether to enable installer.
'debug'=>false,
),
'components'=>array(
'user'=>array(
'class'=>'RWebUser',
// enable cookie-based authentication
'allowAutoLogin'=>true,
'loginUrl'=>array('/user/login'),
),
AssignementController
public function accessRules()
{
return array(
array('allow', // Allow superusers to access Rights
'actions'=>array(
'view',
'user',
'revoke',
),
'users'=>$this->_authorizer->getSuperusers(),
),
array('deny', // Deny all users
'users'=>array('*'),
),
);
}
I need your help. PLEASE
Note that:: I am using yii-user also. yii-user is working well.
In your controller, you are required to name your action to perform function.
public function accessRules(){
.......
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','districts','center'),
'users'=>array('#'),
......
}
For example in the above code, district and center are actions.
Hopefully, you will get the idea.
I know it's an older question but have you add
public function filters()
{
return array(
'accessControl',
);
}
to the AssignementController? Yii needs it to regard function accessRules() for access controlling.
Set your "Yii::app()->user->name";
Try this
<?php
class UserIdentity extends CUserIdentity
{
protected $_id;
const USER_INACTIVE = 3;
public function authenticate()
{
$p= Person::model()->findByUsername($this->username);
if (empty($p))
$this->errorCode = self::ERROR_USERNAME_INVALID;
elseif (!CPasswordHelper::verifyPassword($this->password, $p->password))
$this->errorCode = self::ERROR_PASSWORD_INVALID;
else
{
$this->_id = $p->id;
$this->username = $p->username;
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId() {
return $this->_id;
}
}
the line "$this->username = $p->username;";
Hope this help.

Multiple identity properties for authentication in ZF2 with Doctrine 2

I have login form with input text fields:
Group Name
User Name
User Password
I have two tables
groups
id
name
users
id
name
group_id
I have its mapping entities and associations.
But user name not unique within table users, because different groups can include users with equal names. Therefore i need:
find group by name in table groups
find user by name in table users with condition where group_id=<group_id>
How to do it correctly in Zend Framework 2 using Doctrine 2?
All official documentation and examples depict situation, where identity property is single column (example).
Sorry for my bad language. Thanks.
Instead of making my own implementation of Doctrine's authentication services i decide to implement it via form validation inside isValid() method of my authentication form.
Example:
<?php
namespace My\Form\Namespace;
use Zend\Form\Form;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\InputFilter\InputFilterProviderInterface;
class Auth extends Form implement InputFilterProviderInterface
{
protected $_em;
public function __construct(ServiceLocatorInterface $sm)
{
parent::__construct('auth');
// inject Doctrine's Entity Manager
$this->_em = $sm->get('Doctrine\ORM\EntityManager');
// login field
$this->add(...);
// password field
$this->add(...);
// group_name field
$this->add(...);
}
public function getInputFilterSpecification()
{
//Input filter specification here
...
}
public function isValid()
{
/*
* input filter validations
*/
if (!parent::isValid())
return false;
/*
* group exists validation
*/
$group = $this->_em
->getRepository('<Group\Entity\Namespace>')
->findOneBy(array(
'name' => $this->get('group_name')->getValue(),
));
if (!$group){
$this->get('group_name')
->setMessages(array(
'Group not found',
));
return false;
}
/*
* user exists validation
*/
$user = $this->_em
->getRepository('<User\Entity\Namespace>')
->findOneBy(array(
'group_id' => $group->getId(),
'name' => $this->get('login')->getValue(),
));
if (!$user){
/*
* It's not good idea to tell that user not found,
* so let it be password error
*/
$this->get('password')
->setMessages(array(
'Login or password wrong',
));
return false;
}
/*
* password validation
*/
$password = $this->get('password')->getValue();
// assume that password hash just md5 of password string
if (md5($password) !== $user->getPassword()){
$this->get('password')
->setMessages(array(
'Login or password wrong',
));
return false;
}
return true;
}
}
Inside controller it is enough to call $form->isValid() to make sure that user entered correct authentication data.
I have the same problem.
I have to do two authentications in same application, because my boss doesn't wanna two databases. So, I had to make two user tables and two login pages.
One route to admin -> /admin/login
And the front-end for other users -> /login
I've tried to put on more authenticate in doctrine authentication array but it didn't work.
I think I'll open a issue on doctrine github page.