User Level Access in yii can't run well - php

I am newbie in yii, I am making an website with yii framework. It is my first time in making USER LEVEL ACCESS. I've created a file EWebUser.php in protected/controllers/, this is my code `
protected function loadUser(){
if ($this->_model === null){
$this->_model= User::model()->findByPk($this->id);
}
return $this->_model;
}
function getLevel(){
$user = $this->loadUser();
if ($user)
return $user->status;
return '';
}
}
then I've also created function namely accessRules in AdminController. This my code
public function accessRules() {
return array(
array('allow',
'actions'=>array('index','delete','btnconf'),
'expression'=>'$user->getLevel()="supadmin"'
)
);
}
`
When I type http://localhost/coretankuyii/index.php/admin/index in URL while I login with user, admin or even has not login can still access it. My hope someone who can access that URL only someone who has status=supadmin. Do you can help me please?

Change the expression to "=="
public function accessRules() {
return array(
array('allow',
'actions'=>array('index','delete','btnconf'),
'expression'=>'$user->getLevel()=="supadmin"'
)
);
}
Or if this does not work try the below
public function accessRules() {
return array(
array('allow',
'actions'=>array('index','delete','btnconf'),
'expression'=>array('AdminController','getLevel');
)
);
}
public function getLevel(){
$user = $this->loadUser();
if($user->status=='supadmin')
return true;
else
return false;
}

Related

(Phalcon) How to redirect (Phalcon\Http\Response) from static method in model

I'm trying to create a reusable static function which redirects if true.
This function will be in a model.
public function checkEmtpy(ResultsetInterface $resultset)
{
$di = \Phalcon\DI::getDefault();
if (empty($resultset->toArray())) {
$di->get('flash')->error('Page not found.');
return $di->get('response')->redirect('content');
} else {
return false;
}
}
I tried several ways to redirect but I can't get it to redirect from the model.
What can I change to make this work or isn't this possible at all?
It is against MVC principle to do redirects in models. The redirect has to be done in the Controller. What you should do is return only the status from your model only. Something like this:
// Model
public function checkEmtpy(ResultsetInterface $resultset)
{
return empty($resultset->toArray());
}
// Controller
public action someAction()
{
$isEmpty = (new YourModelName)->checkEmtpy($someVariable);
if ($isEmpty === true) {
return $this->response->redirect(...);
}
}

Laravel - Callable returning blank screen

I'm trying to create a callback to return my views based on data from my current logged-in user. If I do something basic like echoing 'hi' it works, is there any way accomplish this?
function checkUser($type,$callback){
if( is_callable($callback) ){
call_user_func($callback);
}
}
class FichaController extends Controller
{
public function contarFichas()
{
checkUser('particular',function(){
$currentUser = Auth::user();
$countFichas = Ficha::where('user_id',$currentUser->id)->count();
return view('particular.index', array('countFichas' => $countFichas));
});
}
}
Return the result from checkUser
if( is_callable($callback) ){
return $callback();
}
public function contarFichas()
{
return checkUser('particular',function(){
$currentUser = Auth::user();
$countFichas = Ficha::where('user_id',$currentUser->id)->count();
return view('particular.index', array('countFichas' => $countFichas));
});
}

Authorize users based on roles in CakePHP 3

I would like to authorize users based on few roles. All visitors should be able to reach method show. So I wrote in AppController:
public function beforeFilter(Event $event) {
$this->Auth->allow(['show']);
}
It works.
In initialize() method of AppController I've got also:
$this->loadComponent('Auth', [
'authorize' => 'Controller'
]);
I would like to allow logged users with role "user" to reach all "index", and "add" methods, so I wrote in AppController:
public function isAuthorized($user) {
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
if (isset($user['role']) && $user['role'] === 'user') {
$this->Auth->allow(['index', 'logout', 'add']);
}
return false;
}
Admin can reach all methods as expected. User logged with role "user" can't reach "index" or "add" method. How can I fix this?
Instead of using your logic to add additional Auth allows, just use the logic to determine if they're in an action they're allowed, by checking the action, and return true if they're authorized.
public function isAuthorized($user) {
// Admin allowed anywhere
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
// 'user' allowed in specific actions
if (isset($user['role']) && $user['role'] === 'user') {
$allowedActions = ['index', 'logout', 'add'];
if(in_array($this->request->action, $allowedActions)) {
return true;
}
}
return false;
}
(obviously this code could be shortened to your liking, but it shows the concept)
I find this solution to be great and easier to maintain.
//in all controllers that you want to restrict access
public function isAuthorized($user)
{
//an array since we might want to add additional roles
$possibleRoles = array('admin');
return $this->confirmAuth($user['role'], $possibleRoles);
}
//in AppController
public function confirmAuth($userRole, $allowedRoles)
{
return in_array($userRole, $allowedRoles);
}

RBAC is not working in yii

I have a employee table which it contains emp_id,email,password and roles. I have given user and admin as a value for the field roles. I have also created webuser component which it extends CWebUser. This is my webuser code.
class WebUser extends CWebUser
{
public function checkAccess($operation, $params=array())
{
if (empty($this->id)) {
// Not identified => no rights
return false;
}
$role = $this->getState("roles");
if ($role === 'admin') {
return true; // admin role has access to everything
}
return ($operation === $role);
}
}
This is my UserIdentity code.
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$user= Employee::model()->find('LOWER(email)=?',array(strtolower($this->username)));
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if(!$user->validatePassword($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$user->emp_id;
$this->setState('roles',$user->roles);
$this->username=$user->email;
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode==self::ERROR_NONE;
}
}
This is my controller code.
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','update','delete'),
'roles'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
It seems everything is fine. But when i try to update then it is not working and i have tried this for a person who have a admin value for the roles. Please correct me if am wrong.
I think problem is in checkAccess - you need to access a model Employee
class WebUser extends CWebUser
{
private $_model = null;
public function getModel(){
if (!$this->isGuest && $this->_model === null) {
$this->_model = Employee::model()->findByPk($this->id);
}
return $this->_model;
}
public function checkAccess($operation, $params=array()){
return $this->model->roles == 'admin';
}
}
If your app will not be compicated this should work.
But better use PhpAuthManager (or DbVersion) with full RBAC support

Yii Simple RBAC Error

I just a newbie in Yii. I have read http://www.yiiframework.com/wiki/328/simple-rbac/ and followed all instructions there, but I had error User.roles is not defined when I tried to login. Here is my UserIdentity.php
<?php
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$user = User::model()->findByAttributes(array
('username'=>$this->username));
if($user===null){
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else{
if($user->password!==$user->encrypt($this->password)){
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
else{
$this->_id = $user->username;
$this->setState('roles', $user->roles);
$this->errorCode=self::ERROR_NONE;
}
}
return !$this->errorCode;
}
public function getId(){
return $this->_id;
}
}
And then EWebUser.php
<?php
class EWebUser extends CWebUser
{
public function checkAccess($operation, $params=array())
{
if (empty($this->id)) {
// Not identified => no rights
return false;
}
$role = $this->getState("roles");
if ($role === 'admin') {
return true; // admin role has access to everything
}
// allow access if the operation request is the current user's role
return ($operation === $role);
}
}
At last accessRules method in UserController.php
public function accessRules()
{
.....
return array(
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
//'users'=>array('admin'),
'roles'=>array('admin'),
.....
);
}
I hope anyone can help me solve this problwm, thank you very much

Categories