Git Product home page Git Product logo

yii-auth's Introduction

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

yii-auth's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii-auth's Issues

Minor bug: translation-issue

I discovered a minor bug. On several places the type of an authorisation-item is translated into its proper name (by means of the AuthController->getItemTypeText function). When this is done, and the result is used in a link (as is done in some grid-views troughout the module), it will render some dead-end links in a translated module. It then links to a controller based on the translation, which of course doesn't exist.
The solution I myself came up with was to add an extra function to authController, to use in the links:

public function getItemTypeController($type)
{
    switch ($type)
    {
        case CAuthItem::TYPE_OPERATION:
            $controller = 'operation';
            break;

        case CAuthItem::TYPE_TASK:
            $controller = 'task';
            break;

        case CAuthItem::TYPE_ROLE:
            $controller = 'role';
            break;

        default:
            throw new CException('Auth item type "' . $type . '" is valid.');
    }

    return $controller;
}

bizrule

It seems there's no bizrule management. Did I miss it ?

Bug with LanguageSelector

In ../views/main.php
if you include a LanguageSelector
... $this->widget('application.components.widgets.LanguageSelector');

When you try www.....?r=auth
you have the error
Error 500
AssignmentController and its behaviors do not have a method or closure named "createMultilanguageReturnUrl".

Using Yii-Auth with Foundation

Is there any way to use this extension with Zurb Foundation and foundation4giix? I appreciate that you like Bootstrap, but I don't see why your preference for a particular CSS framework should dictate where your Auth extension can be used. What would it take to divorce the presentation part of your extension from the actual, relevant authorization part?

No design

Screen Shot 2013-01-02 at 10 47 52 AM

This is what it looks like for me.
Note that I installed Bootstrap for this extension, but I don't use it anywhere in my layout files. So I'm not sure if it's supposed to work out of the box.

Unauthenticated user

Once the filter is implemented, allowing an unauthenticated user to perform certain actions is not possible.

A possible use case:

  • object.view
    • Displays information about the object
  • object.admin
    • Manage the object

Scenario: we want unauthenticated users to be able to view the object, but not to manage it.

With the code as is, this is not possible.

Solution:

  1. Create a role "unauthenticated"
  2. Assign object.view permissions to that role
  3. In config, make "unauthenticated" a default role Yii Docs
  4. Edit filters.AuthFilter (Will commit this soon)

Admin role makes no sense

In rights module admin rba role grant full access to all operations.

Why here full access is given only through user component config? Is this correct?

Missing module configuration parameter

In yii-auth / views / layouts / main.php you are refering to appLayout like:

$this->beginContent($this->module->appLayout)

but the appLayout field in AuthModule.php is missing.

If you add it, and provide a valid appLayout configuration parameter in your config file, everything works fine.

README / authManager Component

I found that I had to put the authManager component configuration like this:

        'authManager'=>array( // {{{ 
            'class'=>'CDbAuthManager',
            'behaviors' => array(
                array(
                    'class'=>'auth.components.AuthBehavior',
                    'admins' => array('admin'), // a list of users who has access to the module.
                ),
            ),

Pagination and search

In the Index view, when you have hundreds of operations it would be nice to have :

  • a search row, like in standard gridview
  • a pager / pagination, like in standard gridview

I'm new in yii and I couldn't add them without errors !

Set Admin based in ID instead of Name

I believe it would be a good idea to allow IDs instead of names to be used to set admin status via the config.

The ID column has to be specified already and by its very nature is guaranteed to be unique. Of course one can assume that the name is unique, however, depending on the implementation and origin this is not a given.

custom base controller class

I have my own custom base controller class and I don't wont this extension overrides so I had to make AuthController extending from Controller instead of CController

line 14

abstract class AuthController extends Controller

属性 "User.id" 未被定义

属性 "User.id" 未被定义,
it means User.id is undefined. I don't know how to modify.

it is below:
/var/www/html/myxk/protected/modules/auth/widgets/AuthAssignmentNameColumn.php(34): CActiveRecord->__get("id")

29 * @param integer $row the row number (zero-based).
30 * @param mixed $data the data associated with the row.
31 */
32 protected function renderDataCellContent($row, $data)
33 {
34 echo CHtml::link(CHtml::value($data, $this->nameColumn), array('view', 'id' => $data->{$this->idColumn}));
35 }
36 }

Table Prefix Not Supported

This seems to be working for me...

public $tablePrefix;

public function init()
{
$this->tablePrefix = Yii::app()->getDb()->tablePrefix;
if ($this->tablePrefix <> '') {
  $this->itemTable= $this->tablePrefix.$this->itemTable;      
  $this->itemChildTable= $this->tablePrefix.$this->itemChildTable;    
  $this->assignmentTable=$this->tablePrefix.$this->assignmentTable;
}
    parent::init();

Messages / de

Hello,

this is the messages file in German:

<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yiic message' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE, this file must be saved in UTF-8 encoding.
 *
 * @version $Id: $
 */
return array (
  'Access denied.' => 'Zugriff verweigert.',
  'Add' => 'Hinzufügen',
  'Add child' => 'Untergeordnetes Element hinzufügen',
  'Add {type}' => '{type} hinzufügen',
  'Ancestors' => 'Übergeordnete',
  'Are you sure you want to delete this item?' => '',
  'Assign' => 'Zuordnen',
  'Assign permission' => 'Berechtigung zuweisen',
  'Assigned items' => 'Zugeordnete Einträge',
  'Assignments' => 'Zuordnungen',
  'Business rule' => 'Geschäftsregel',
  'Cancel' => 'Abbrechen',
  'Create' => 'Anlegen',
  'Data' => 'Daten',
  'Descendants' => 'Untergeordnete',
  'Description' => 'Beschreibung',
  'Edit' => 'Bearbeiten',
  'Invalid request.' => 'Ungültige Anfrage.',
  'Item does not exist.' => 'Eintrag existiert nicht.',
  'Items' => 'Einträge',
  'Items assigned to this user' => 'Diesem Benutzer zugeordnete Einträge',
  'New {type}' => 'Neu {type}',
  'No assignments found.' => '',
  'No {type} found.' => '{type} nicht gefunden.',
  'Page not found.' => '',
  'Permissions' => 'Berechtigungen',
  'Permissions granted by this item' => 'Durch diesen Eintrag gewährte Berechtigungen',
  'Permissions that inherit this item' => 'Berechtigungen, die diesen Eintrag erben',
  'Remove' => 'Entfernen',
  'Revoke' => 'Zurückziehen',
  'Save' => 'Speichern',
  'Select item' => 'Eintrag auswählen',
  'System name' => 'Systemname',
  'System name cannot be changed after creation.' => '',
  'This item does not have any ancestors.' => 'Dieser Eintrag hat keine übergeordneten Einträge.',
  'This item does not have any descendants.' => 'Dieser Eintrag hat keine untergeordneten Einträge.',
  'This user does not have any assignments.' => 'Dieser Benutzer hat keine Zuordnungen.',
  'Type' => 'Typ',
  'User' => 'Benutzer',
  'View' => 'Anzeigen',
  'operation|operations' => 'Operation|Operationen',
  'role|roles' => 'Rolle|Rollen',
  'task|tasks' => 'Aufgabe|Aufgaben',
);

Regards,

Joachim

Yii-auth and yii strap

Hi,
i use Yii-auth with Yii-strap and got this error

Fatal error: Undefined class constant 'STYLE_LINK' in common/lib/vendor/crisu83/yii-auth/widgets/AuthAssignmentRevokeColumn.php on line 36

How to solve this ?

AuthAssignmentItemsColumn give administrator to all

in AuthAssignmentItemsColumn you have

if (Yii::app()->user->isAdmin)
            echo Yii::t('AuthModule.main', 'Administrator');

this will cause that if I am the administrators all the users in the lists will display "administrator" element associated. non-sense.

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.

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

Assignments needs a filter

My database has a huge number of users -- couple hundred thousand (most do not have special permissions). The current pagination based system doesn't cut it, I need filters to find the users I want.

So I made them. Please review these small diffs and add them if you like.

--- widgets/AuthAssignmentNameColumn.php.orig   2013-01-20 03:04:31.000000000 -0800
+++ widgets/AuthAssignmentNameColumn.php        2013-06-10 00:32:59.000000000 -0700
@@ -32,4 +32,12 @@
        {
                echo CHtml::link(CHtml::value($data, $this->nameColumn), array('view', 'id'=>$data->{$this->idColumn}));
        }
+
+       /**
+        * Renders the filter cell content.
+        */
+       protected function renderFilterCellContent()
+       {
+               echo CHtml::activeTextField($this->grid->filter, $this->getNameColumn(), array('id'=>false));
+       }
 }
--- views/assignment/index.php.orig     2013-01-01 12:05:32.000000000 -0800
+++ views/assignment/index.php  2013-06-10 01:05:37.000000000 -0700
@@ -11,7 +11,8 @@

 <?php $this->widget('bootstrap.widgets.TbGridView', array(
     'type' => 'striped hover',
-    'dataProvider' => $dataProvider,
+    'filter' => $model,
+    'dataProvider' => $model->search(),
        'emptyText' => Yii::t('AuthModule.main', 'No assignments found.'),
        'template'=>"{items}\n{pager}",
     'columns' => array(
--- controllers/AssignmentController.php.orig   2013-01-11 18:54:10.000000000 -0800
+++ controllers/AssignmentController.php        2013-06-10 00:56:04.000000000 -0700
@@ -17,10 +17,13 @@
         */
        public function actionIndex()
        {
-               $dataProvider = new CActiveDataProvider($this->module->userClass);
+               $model = new $this->module->userClass('search');
+               $model->unsetAttributes();  // clear any default values
+               if(isset($_GET[$this->module->userClass]))
+                       $model->attributes=$_GET[$this->module->userClass];

                $this->render('index', array(
-                       'dataProvider' => $dataProvider
+                       'model' => $model
                ));
        }

PHP error include(AuthModule.php) using filter in controller

throw new CHttpException(401, Yii::t('AuthModule.main', 'Access denied.'));

include(AuthModule.php) [function.include]: failed to open stream: No such file or directory

You can add an import

    'import'            => array(
        ...
        'application.modules.auth.AuthModule'
    ),

But I think it's an ugly solution?

Can be attributed to a bug of yii framework, as it is not clear why we need to use the import module file to use Yii:t() function

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]

Postgres schema

Please, tell me how to set database schema for this module. I can't find it :(

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

TbHtml

There's no TbHtml.php yet.

views\assignment\view.php(55):
54 beginWidget('bootstrap.widgets.TbActiveForm', array( 55 'type' => TbHtml::FORM_INLINE, 56 )); ?>

Missing menu in assignment and authitem when use with yiistrap

I miss this piece of code in auth/views/assignment/index and auth/views/authitem/index

<?php $this->widget('bootstrap.widgets.TbNav', array(
    'type' => TbHtml::NAV_TYPE_TABS,
    'items' => $this->menu,
)); ?>

If not set defaultLayout in main.php, default is used application.views.layouts.main.
When set defaultLayout to use the layout of auth.....this messes up the layout ;-)

Problem in set-up and running the auth extension

I downloaded the extension and copied the configuration. I have already set-up the auth tables. But it still doesn't work. I can't access the auth UI in http://localhost/project/index.php/auth I can't get any error.
I also tried the http://localhost/project/index.php/auth/operation/index
and http://localhost/project/index.php/auth/assignment/index.

In the AuthAssignment table I have set the user as the role admin.

This is my configuration in main.php:
/For modules/
'modules' => array(
'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' => 'username', // the name of the user name column.
// 'appLayout' => 'application.views.layouts.main', // the layout used by the module.
'defaultLayout' => 'application.views.layouts.main', // the layout used by the module.
'viewDir' => null, // the path to view files to use with this module.
),
//..

 // application components

'components' => array(
//..
'authManager' => array(
'class'=>'CDbAuthManager',
'connectionID'=>'db',
// /* Renaming tables*/
'assignmentTable' => 'AuthAssignment',
'itemTable' => 'AuthItem',
'itemChildTable' => 'AuthItemChild',
//'defaultRoles'=>array('dataConsumer'),
'showErrors'=>true,
'behaviors' => array(
'auth' => array(
'class' => 'auth.components.AuthBehavior',
),
),
),
'user' => array(
'class' => 'auth.components.AuthWebUser',
// 'admins' => array('admin', 'foo', 'bar'), // users with full access
'admins' => array('admin')
),
//..
Can you shed some light on here? Thanks!

order assignments view

is it possible to order the main assignments view with assigned items on top and filter by usernames?

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'))

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?

AuthWebUser and its behaviors do not have a method or closure named "updateSession".

I am trying to replace the "Rights" module with the Yii-Auth module. I also have the Yii-User module installed (with a version ID of UserModule.php 132 2011-10-30 10:45:01Z mishamx). I've done the configuration just as you've stated in your directions. However, when I attempt to login, I get an error message that states: AuthWebUser and its behaviors do not have a method or closure named "updateSession".

"updateSession" is called in the user model's afterSave.

Any ideas on how to deal with this? I know that in the past we had to substitute RWebUser for WebUser, but your directions for Yii-Auth don't include that.

README Filter Reference

In the README, the reference for when using a filter should pont to the new location of the filter at 'auth.filters.AuthFilter'

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.

bad url for submodule

use the great auth as a submodule
i found need remove all '/auth/' in menu of /webroot/protected/modules/be/modules/auth/views/layouts/main.php
and chtml::link in line 44
/webroot/protected/modules/be/modules/auth/widgets/AuthItemDescriptionColumn.php

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.