Skip to main content

Yii Authentication and Authorization Login logout Access control filter and User Types

Authentication and Authorization

check if a user is logged in or not via CWebUser::isGuest
check if the user can perform specific operations by calling CWebUser::checkAccess

 The main work in defining an identity class is the implementation of the IUserIdentity::authenticate method
 class UserIdentity extends CUserIdentity
{
    private $_id;
    public function authenticate()
    {
        $record=User::model()->findByAttributes(array('username'=>$this->username));
        if($record===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if($record->password!==crypt($this->password,$record->password))
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
        {
            $this->_id=$record->id;
            $this->setState('title', $record->title);
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
    }

    public function getId()
    {
        return $this->_id;
    }
}

Any information that we store in a state (by calling CBaseUserIdentity::setState) will be passed to CWebUser,
 which in turn will store them in a persistent storage, such as session.

In our example, we stored the user title information via $this->setState('title', $record->title);.
Once we complete our login process, we can obtain the title information of the current user by simply using Yii::app()->user->title.



Login and Logout 

// Login a user with the provided username and password.
$identity=new UserIdentity($username,$password);
if($identity->authenticate())
    Yii::app()->user->login($identity);
else
    echo $identity->errorMessage;
......
// Logout the current user
Yii::app()->user->logout();

Whether or not a user has been authenticated can easily be checked throughout the application by using Yii::app()->user->isGuest.


Cookie-based Login
we can set the allowAutoLogin property of the user component to be true and pass a duration parameter to the CWebUser::login method.
 // Keep the user logged in for 7 days.
// Make sure allowAutoLogin is set true for the user component**
Yii::app()->user->login($identity,3600*24*7);

These states will be read from the cookie and made accessible via Yii::app()->user.



Access Control Filter

Checks if the current user can perform the requested controller action.
Based on user's name, client IP address and request types and provided as a filter named as "accessControl".
To control the access to actions in a controller, we install the access control filter by overriding CController::filters.
class PostController extends CController
{
    ......
    public function filters()
    {
        return array(
            'accessControl',
        );
    }
}

The detailed authorization rules used by the filter are specified by overriding CController::accessRules in the controller class.
class PostController extends CController
{
    ......
    public function accessRules()
    {
        return array(
            array('deny',
                'actions'=>array('create', 'edit'),
                'users'=>array('?'),
            ),
            array('allow',
                'actions'=>array('delete'),
                'roles'=>array('admin'),
            ),
            array('deny',
                'actions'=>array('delete'),
                'users'=>array('*'),
            ),
        );
    }
}



An access rule can match the following context parameters:

actions: specifies which actions this rule matches. This should be an array of action IDs. The comparison is case-insensitive.
controllers: specifies which controllers this rule matches. This should be an array of controller IDs. The comparison is case-insensitive.
users: specifies which users this rule matches. The current user's name is used for matching. The comparison is case-insensitive. Three special characters can be used here:
*: any user, including both anonymous and authenticated users.
?: anonymous users.
@: authenticated users.
roles: specifies which roles that this rule matches. This makes use of the role-based access control feature to be described in the next subsection. In particular, the rule is applied if CWebUser::checkAccess returns true for one of the roles. Note, you should mainly use roles in an allow rule because by definition, a role represents a permission to do something. Also note, although we use the term roles here, its value can actually be any auth item, including roles, tasks and operations.
ips: specifies which client IP addresses this rule matches.
verbs: specifies which request types (e.g. GET, POST) this rule matches. The comparison is case-insensitive.
expression: specifies a PHP expression whose value indicates whether this rule matches. In the expression, you can use variable $user which refers to Yii::app()->user.



Yii users types
*: any user, including both anonymous and authenticated users.
?: anonymous users.
@: authenticated users.

Comments

Popular posts from this blog

Ten output devices, advantages and disadvantages, inter-site back-up mechanism, Expert systems for medical diagnosis,information systems security

(i)Printer Printer enables us to produce information output on paper. It is one of the most popular computer output devices we often use to get information on paper - called hard copy. Advantage They produce high quality paper output for presentation at a speedy rate. It is also possible to share the printer among different users in a network. Disadvantage The cost for maintenance of the printer equipment as well printing ink is cumulatively high. (ii) Plotters These devices are used to produce graphical outputs on paper. They have automated pens that make line drawings on paper Advantage They can produce neat drawings on a piece of paper based on user commands. In Computer Aided Design (CAD) they are used to produce paper prototypes that aid in design of the final system. Disadvantage They are more expensive than printers. Further, the command based interface is difficult to use. (iii)Monitor It is...

simple basic object oriented java code for employee salary calculation

import java.io.*; import java.util.Scanner; public class Employees {     Scanner scan=new Scanner(System.in);     String Fname;   int EmpID;  int DOB; double Allowance;   double Salary;     public void getDetails(){   System.out.println("Enter the first name");   Fname=scan.next();   System.out.println("Enter the ID number");   EmpID=scan.nextInt();   System.out.println("Enter the date of birth");   DOB=scan.nextInt();   System.out.println("Enter the salary");   Salary=scan.nextDouble();   Allowance=0.6*Salary;     }    public void printReport(){    System.out.println(Fname+"\t"+EmpID+"\t"+calGross()+"\t"+calPayee()+"\t"+calNetIncome());    }    public double calGross(){        return Salary + Allowance;    }    public double calPayee(){     ...

Start Wamp server on windows automatically permanently

For those that have completely refused to use linux platforms for development, you might find this useful. As with all (aspiring) web developers, it’s always important to test your projects locally before putting it out there for the entire web community to see. One must-have developer tool for this purpose is WAMPServer. We’ve all wished it’s automatically up and running when we need it. These easy steps will help you automate WAMPServer to run on system start-up. For those unfamiliar with WAMPServer, it is a development package that lets you run web development projects locally. WAMP stands for Windows, Apache, MySQL, PHP/Perl/Python. It’s basically four programs packaged to work as one. WAMP basically turns any Windows PC into a localized web server. The Linux counterpart is called LAMP, obviously. Once WAMPServer is installed in your PC, you’ll be able to test your web projects before putting it into the live environment. But I always found it a hassle to manually s...