Auth is a module for the Yii PHP framework that provides a web user interface for Yii's built-in authorization manager

Overview

yii-auth

Auth is a module for the Yii PHP framework that provides a web user interface for Yii's built-in authorization manager (CAuthManager). You can read more about Yii's authorization manager in the framework documentation under Authentication and Authorization.

Auth was developed to provide a modern and responsive user interface for managing user permissions in Yii projects. To achieve its goals it was built using my popular Twitter Bootstrap extension.

Auth is written according to Yii's conventions and it follows the separation of concerns priciple and therefore it doesn't require you to extend from its classes. Instead it provides additional functionality for the authorization manager through a single behavior.

Demo

You can try out the live demo here.

Requirements

Usage

Setup

Download the latest release from Yii extensions.

Unzip the module under protected/modules/auth and add the following to your application config:

return array(
  'modules' => array(
    'auth',
  ),
  'components' => array(
    'authManager' => array(
      .....
      'behaviors' => array(
        'auth' => array(
          'class' => 'auth.components.AuthBehavior',
        ),
      ),
    ),
    'user' => array(
      'class' => 'auth.components.AuthWebUser',
      'admins' => array('admin', 'foo', 'bar'), // users with full access
    ),
  ),
);

protected/config/main.php

Please note that while the module doesn't require you to use a database, if you wish to use CDbAuthManager you need it's schema (it can be found in the framework under web/auth).

Configuration

Configure the module to suit your needs. Here's a list of the available configurations (with default values).

'auth' => array(
  'strictMode' => true, // when enabled authorization items cannot be assigned children of the same type.
  'userClass' => 'User', // the name of the user model class.
  'userIdColumn' => 'id', // the name of the user id column.
  'userNameColumn' => 'name', // the name of the user name column.
  'defaultLayout' => 'application.views.layouts.main', // the layout used by the module.
  'viewDir' => null, // the path to view files to use with this module.
),

Enabling caching

To enable caching for CDbAuthManager you can use CachedDbAuthManager that provides caching for access checks. Here's an example configuration for the component:

'authManager'=>array(
  'class'=>'auth.components.CachedDbAuthManager',
  'cachingDuration'=>3600,
),

Checking access

When you wish to check if the current user has a certain permission you can use the CWebUser::checkAccess() method which can be access from anywhere in your application through Yii::app() like so:

if (Yii::app()->user->checkAccess('itemName')) // itemName = name of the operation
{
  // access is allowed.
}

In order to keep your permissions dynamic you should never check for a specific role or task, instead you should always check for an operation. For more information on Yii's authorization manager refer to the framework documentation on Authentication and Authorization.

Checking access using a filter

You can also use a filter to automatically check access before controller actions are called. Operations used with this filter has to be named as follows (moduleId.)controllerId.actionId, where moduleId is optional. You can also use a wildcard controllerId.* instead of the actionId to cover all actions in the controller or module.* instead of the controllerId to cover all controllers in the module.

public function filters()
{
  return array(
    array('auth.filters.AuthFilter'),
  );
}

For more information on how filters work refer to the framework documentation on Controllers.

Internationalization

Do you wish to provide a translation for Auth? If so, please do a pull request for it. Translations should be placed in the messages folder under a folder named according to its locale (e.g. en_us).

Note

Note: Version 1.0.6-wip use and require yiistrap!! yiistrap is next generation yii-bootsrap

Comments
  • The page isn't redirecting properly

    The page isn't redirecting properly

    After enabling module it shows me "The page isn't redirecting properly" and site is no longer accessible.

    Here is config file http://codepad.org/ux4fCtEm

    and here main controller class http://codepad.org/GFoPJn1s

    opened by tahiryasin 9
  • added SingleDbAuthManager

    added SingleDbAuthManager

    The class fetches all auth items at once and store them in memory in a tree-like array to avoid any further SELECT queries. This tree is synchronized with the database when modified.

    It's necessary when managing very large amount of auth items. Also, this works nicely with current CachedDbAuthManager in production enviroment.

    Class is modeled after CPhpAuthManager and tested using tests from the framework.

    Further adjustments could include caching of the tree structure to avoid rebuilding it with every request.

    opened by nineinchnick 7
  • Make it more compatible

    Make it more compatible

    I've done a little edits to make it work with CPhpAuthManager by adding $am->save() in your controllers after modifications on $am items.

    I had also to workaround this problem: in my db the user name is not unique and the uniqueness is given by the email address.. so if you use Yii::app()->user->getName() in AuthModule.php to check if user have permission to view the module I cannot do anything to make it work checking against email. You should provide a configurable method to retrieve the desired value from user model. As a workaround i used Yii::app()->user->model->{$this->userNameColumn} , adding access to the model in my WebUser.php

    question 
    opened by manuel-84 7
  • composer support

    composer support

    I've raised a similar request for yii-bootstrap a while ago here: https://bitbucket.org/Crisu83/yii-bootstrap/pull-request/30/info-file-for-composer/diff

    Would be nice if you could think about including composer.json files again - I'll send you a pull-request if you want to - since extension dependencies are becoming more and more important.

    Just as an example: yii-auth depends on yii-bootstrap (which may also depend on twitter/bootstrap) and both depend on yiisoft/yii.

    opened by schmunk42 6
  • Transitioning from Yii Rights

    Transitioning from Yii Rights

    Is this extension production ready? Is it better to use this one vs Yii Rights?

    If the answer is yes to both, could you post a Wiki with a tutorial on how to transition from Yii Rights to Yii Auth?

    My project is still young so if Yii Auth is the way to go, I could transition.

    question 
    opened by NathanHazout 6
  • custom user class

    custom user class

    I'm using a custom User's class and I can't use the built-in AuthWebUser

    So I added the checkAccess method to my class and in AuthModule.php, line 114, I propose to add checks for methods instead of having only the name of the class

    
    if ($user instanceof AuthWebUser || method_exists($user, 'getIsAdmin'))
    
    opened by manuel-84 5
  • Ux improvement

    Ux improvement

    Hi, here is a couple of UX improvements I use with your extension. The improvements are :

    • MultiSelect form fields (I use the bootstrap-select component : https://github.com/silviomoreto/bootstrap-select writen by silviomoreto )
    • AuthItem names appear in grid view in addition to the description
    • AuthItem description appear in assignement grid view
    • User filter in AuthAssignement grid view (based on User->username)
    • Column filter in AuthItem view (I use the table-filter js https://github.com/hail2u/jquery.table-filter writen by hail2u )
    opened by luxcem 4
  • Backward Compatibility

    Backward Compatibility

    Auth module does compatible with your bootstrap extension available on http://www.yiiframework.com/extension/bootstrap but you said that it was compatible with that.

    opened by rifaideen 4
  • how can without ForeignKey it's a big problem for mysql dump

    how can without ForeignKey it's a big problem for mysql dump

    I really can not stand, foreign key associations, always insert data errors, or export errors, errors in short everywhere, foreign keys, really not a good thing, excluding foreign keys, please

    opened by djfly 4
  • Yii-Auth and Menubuilder

    Yii-Auth and Menubuilder

    Auth and Menubuilder apparently don't get along. I'm getting this response with the both of them in effect:

     Object configuration must be an array containing a "class" element.
    
    L:\xampp\htdocs\larrylutz\protected\extensions\menubuilder\components\EMBRbacDataFilter.php(28)
    
    16 {
    17 
    18     /**
    19      * Get the roles from the authManager
    20      *
    21      * @param $userId
    22      * @return array
    23      */
    24     protected static function _getRoles($userId)
    25     {
    26         $roles = array();
    27 
    28         $authRoles = Yii::app()->authManager->getRoles($userId);
    29         if(!empty($authRoles))
    30             foreach($authRoles as $role=>$authItem)
    31                 $roles[$role]=$authItem->name;
    32 
    33         return $roles;
    34     }
    

    When I was using Rights, I never got this message; it only appeared after installing Auth and removing Rights.

    Since Menubuilder is the only game in Yii-town when it comes to a database-driven menu system (an absolute necessity for anything beyond a simple, fairly primitive Web site), I really need an access control system that plays nicely with it. Any ideas how to overcome this with Auth?

    opened by larry-tx 4
  • Update yii-auth to the newest yiistrap

    Update yii-auth to the newest yiistrap

    Currently there are multiple issues with TbHtml constants, which were altered in (this commit)[https://github.com/Crisu83/yiistrap/commit/e3249ec72b8b995c31272f92a8795d46f3f259d4]

    opened by waitekk 4
  • yii-auth with db transaction

    yii-auth with db transaction

    Hi All,

    I have an issue with this extension (might be) and db transaction. When I login as superuser, I can call unpost method (and other method with db transaction) without any problem. But, when I login as other user, I got an error that said, There is no active transaction!

    Can anyone help me with this?

    Below is the method: ` public function actionUnpost($id) { if (Yii::app()->request->isPostRequest) { $model = $this->loadModel($id); $qtyCheck = array();

            $transaction = Yii::app()->db->beginTransaction(); // Transaction begin
    
            try {
                // If unpost this will resulting in negative remaining quantity, we should cancel this unpost!!!
                foreach ($model->formDetails as $detail) {
    
                    if (isset($qtyCheck[$detail->id])) {
                        $qtyCheck[$detail->id] -= ($detail->quantity * $detail->type);
                    } else {
                        $qtyCheck[$detail->id] = Journal::model()->getRemReceivingQty($detail->id, $detail->locationFk) - ($detail->quantity * $detail->type);
                    }
    
                    // remaining has normal balance positif, so check the remaining should not be less than 0
                    if (0 > $qtyCheck[$detail->id]) {
                        throw new CDbException('Stok barang ' . $detail->item->name . ' menjadi negatif, FB tidak bisa diunposting!');
                    }
    
                    // Delete journal entries
                    foreach ($detail->journalEntries as $entry) {
                        $entry->delete();
                    }
                }
    
                $model->postingStatus = FormHeader::UNPOSTED;
                $model->save(false);
    
                $transaction->commit();
                Yii::app()->user->setFlash('success', "FB $model->headerNo telah berhasil diunposting.");
            } catch (Exception $e) {
                $transaction->rollBack();
                Yii::app()->user->setFlash('error', $e->getMessage());
            }
    
            $this->redirect(array('view', 'id' => $model->id));
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again!');
        }
    }
    

    `

    TIA Daniel

    opened by dadinugroho 0
  • Fix flatten permission for numeric authitem name

    Fix flatten permission for numeric authitem name

    Julian Egelstaff at php dot net: In some situations, the union operator ( + ) might be more useful to you than array_merge. The array_merge function does not preserve numeric key values. If you need to preserve the numeric keys, then using + will do that.

    opened by tamhv 0
  • how can i add the filter

    how can i add the filter

    If the user too much One user requires authorization Find difficulty, I try to add

    array( 'header' => Yii::t('AuthModule.main', 'User'), ‘filter' // add here 'class' => 'AuthAssignmentNameColumn', ),

    bug it's not work @Crisu83

    opened by djfly 0
  • Does not work with CPhpAuthManager

    Does not work with CPhpAuthManager

    Although the docs say the DB usage is optional it is not.

    example do not set the class in the authmanager component of the config then try to add a Role. The file gets written to application.data.auth.php as it should but then there is an exception in the AuthBehaviour like

    CException Property "CPhpAuthManager.db" is not defined.

    It seems that several of the methods are hardcoded to ONLY use the db connection ie getAncestor, getDescendant

    This effectively means that for small apps or development purposes where you may not necessarily want to add the tables to the db it is just not possible.

    opened by circulon 1
Owner
Christoffer Niska
Technical Lead at Tesseract, father of many, polyglot programmer, open source enthusiast, TypeScript Ninja.
Christoffer Niska
Slim Auth is an authorization and authentication library for the Slim Framework.

Slim Auth is an authorization and authentication library for the Slim Framework. Authentication is provided by the Zend Framework Zend\Authentication component, and authorization by the Zend Framework Zend\Permissions\Acl component.

Jeremy Kendall 246 Dec 16, 2022
GUI manager for RBAC (Role Base Access Control) Yii2. Easy to manage authorization of user

RBAC Manager for Yii 2 GUI manager for RBAC (Role Base Access Control) Yii2. Easy to manage authorization of user ?? . Documentation Important: If you

MDMunir Software 1.2k Jan 7, 2023
EvaOAuth provides a standard interface for OAuth1.0(a) / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few lines code.

EvaOAuth EvaOAuth provides a standard interface for OAuth1.0 / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few

AlloVince 256 Nov 16, 2022
EvaOAuth provides a standard interface for OAuth1.0(a) / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few lines code.

EvaOAuth EvaOAuth provides a standard interface for OAuth1.0 / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few

AlloVince 261 Jan 17, 2022
Files Course Laravel Micro Auth and Authorization

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

EspecializaTi 8 Oct 22, 2022
A Native PHP MVC With Auth. If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo.

If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo. Auth system is implemented. Works with bootstrap 5. Composer with autoload are implemented too for future composer require.

null 2 Jun 6, 2022
Multi Auth and admin auth in Laravel Project

Laravel Multi Auth For Complete Documentation, visit Here This package is just create admin side (multi auth), which is totaly isolated from your norm

Bitfumes 435 Dec 31, 2022
CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

Cake Development Corporation 24 Sep 23, 2022
Easy, native Laravel user authorization.

An easy, native role / permission management system for Laravel. Index Installation Migration Customization Model Customization Usage Checking Permiss

DirectoryTree 5 Dec 14, 2022
Symfony bundle which provides OAuth 2.0 authorization/resource server capabilities

Symfony bundle which provides OAuth 2.0 authorization/resource server capabilities. The authorization and resource server actors are implemented using the thephpleague/oauth2-server library.

Trikoder 253 Dec 21, 2022
Light-weight role-based permissions system for Laravel 6+ built in Auth system.

Kodeine/Laravel-ACL Laravel ACL adds role based permissions to built in Auth System of Laravel 8.0+. ACL middleware protects routes and even crud cont

Kodeine 781 Dec 15, 2022
A framework agnostic authentication & authorization system.

Sentinel Sentinel is a PHP 7.3+ framework agnostic fully-featured authentication & authorization system. It also provides additional features such as

Cartalyst 1.4k Dec 30, 2022
Simple JWT Auth support for Laravel PHP Framework

Laravel JWT Simple JWT Auth for Laravel PHP Framework using Firebase JWT under the hood. Installation Standard Composer package installation: composer

Ricardo Čerljenko 34 Nov 21, 2022
Simple PASETO Auth support for Laravel PHP Framework

Laravel PASETO Simple PASETO Auth for Laravel PHP Framework using paragonie/paseto under the hood. Installation Standard Composer package installation

Ricardo Čerljenko 9 Jan 11, 2022
A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready

A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready.

Damiano Petrungaro 58 Aug 10, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC in PHP .

PHP-Casbin Documentation | Tutorials | Extensions Breaking News: Laravel-authz is now available, an authorization library for the Laravel framework. P

PHP-Casbin 1.1k Dec 14, 2022
Authentication, authorization and access control for PHP

Jasny Auth Authentication, authorization and access control for PHP. Features Multiple authorization strategies, like groups (for acl) and levels. Aut

Arnold Daniels 105 Dec 12, 2022
Declarative style of authorization and validation in laravel.

Laravel Hey Man Readability Counts. In fact, Readability is the primary value of your code !!! ?? Heyman continues where the other role-permission pac

Iman 860 Jan 1, 2023
Minimalistic token-based authorization for Laravel API endpoints.

Bearer Minimalistic token-based authorization for Laravel API endpoints. Installation You can install the package via Composer: composer require ryang

Ryan Chandler 74 Jun 17, 2022