Home Backend Development PHP Tutorial About the implementation of the method of handling front and back login in Yii

About the implementation of the method of handling front and back login in Yii

Jun 19, 2018 am 11:51 AM
yii

This article mainly introduces the new method of handling front-end and back-end login in Yii, and specifically analyzes the new ideas and related implementation techniques of front-end and back-end login in Yii. Friends in need can refer to the example of this article

Describes the new method of handling front and back logins in Yii. I would like to share it with you for your reference. The details are as follows:

Because I am currently working on a project that involves front and backend login issues, I handle the backend as a module. I see many people put two entry files index.php and admin.php, and then point to the frontend and backend respectively. Although this method is very good, it can completely separate the front and backend, but I always feel that this method is a bit far-fetched. What is the difference between this and the two applications? It is better to make two apps using one framework. And the official Yii background usage method is also to use Module. But Moudle's method has a very troublesome problem, that is, when using Cwebuser to log in, there will be a problem of logging in and logging out at the same time in the front and backend, which is obviously unreasonable. I struggled for a long time before I found the method that will be introduced below. Of course, many of them were based on other people's methods and I made slight changes. My initial approach was to set up an isadmin session when logging in to the background, and then log out of the session when logging in to the front desk. This could only tell whether it was a front desk login or a background login, but it couldn't log in both the front and backend, that is, front desk login. Log out after logging into the background, and log out after logging into the front desk. The fundamental reason for this is that we use the same Cwebuser instance and cannot set up front and backend sessions at the same time. To solve this problem, we must use different Cwebuser instances to log in to the front and backend. The following is my approach. First, look at the configuration of the front-end user (Cwebuser) in protected->config->main.php:

'user'=>array(
  'class'=>'WebUser',//这个WebUser是继承CwebUser,稍后给出它的代码
  'stateKeyPrefix'=>'member',//这个是设置前台session的前缀
  'allowAutoLogin'=>true,//这里设置允许cookie保存登录信息,一边下次自动登录
),
Copy after login

In your case When using Gii to generate an admin (backend module name) module, an AdminModule.php file will be generated under module->admin. This class inherits the CWebModule class. The code for this file is given below. The key point is this File, I hope you will study it carefully:

<?php
class AdminModule extends CWebModule
{
  public function init()
  {
    // this method is called when the module is being created
    // you may place code here to customize the module or the application
    parent::init();//这步是调用main.php里的配置文件
    // import the module-level models and componen
    $this->setImport(array(
      &#39;admin.models.*&#39;,
      &#39;admin.components.*&#39;,
    ));
    //这里重写父类里的组件
    //如有需要还可以参考API添加相应组件
    Yii::app()->setComponents(array(
        &#39;errorHandler&#39;=>array(
            &#39;class&#39;=>&#39;CErrorHandler&#39;,
            &#39;errorAction&#39;=>&#39;admin/default/error&#39;,
        ),
        &#39;admin&#39;=>array(
            &#39;class&#39;=>&#39;AdminWebUser&#39;,//后台登录类实例
            &#39;stateKeyPrefix&#39;=>&#39;admin&#39;,//后台session前缀
            &#39;loginUrl&#39;=>Yii::app()->createUrl(&#39;admin/default/login&#39;),
        ),
    ), false);
    //下面这两行我一直没搞定啥意思,貌似CWebModule里也没generatorPaths属性和findGenerators()方法
    //$this->generatorPaths[]=&#39;admin.generators&#39;;
    //$this->controllerMap=$this->findGenerators();
  }
  public function beforeControllerAction($controller, $action)
  {
    if(parent::beforeControllerAction($controller, $action))
    {
      $route=$controller->id.&#39;/&#39;.$action->id;
      if(!$this->allowIp(Yii::app()->request->userHostAddress) && $route!==&#39;default/error&#39;)
        throw new CHttpException(403,"You are not allowed to access this page.");
      $publicPages=array(
        &#39;default/login&#39;,
        &#39;default/error&#39;,
      );
      if(Yii::app()->admin->isGuest && !in_array($route,$publicPages))
        Yii::app()->admin->loginRequired();
      else
        return true;
    }
    return false;
  }
  protected function allowIp($ip)
  {
    if(empty($this->ipFilters))
      return true;
    foreach($this->ipFilters as $filter)
    {
      if($filter===&#39;*&#39; || $filter===$ip || (($pos=strpos($filter,&#39;*&#39;))!==false && !strncmp($ip,$filter,$pos)))
        return true;
    }
    return false;
  }
}
?>
Copy after login

The init() method of AdminModule is to configure another login instance for the backend, so that the front and backend can use different CWebUser, and Set the background session prefix to distinguish it from the front session (they are stored in the $_SESSION array, you can print it out to see).

In this way, the front and back logins have been separated, but if you log out at this time, you will find that the front and backends have logged out together. So I found the logout() method and found that it has a parameter $destroySession=true. It turns out that if you just logout(), all sessions will be logged out. If you add a false parameter, only the current login instance will be logged out. session, which is why it is necessary to set the front and back session prefixes. Let’s see how the logout method with the false parameter is set to log out the session:

/**
* Clears all user identity information from persistent storage.
 * This will remove the data stored via {@link setState}.
 */
public function clearStates()
{
  $keys=array_keys($_SESSION);
  $prefix=$this->getStateKeyPrefix();
  $n=strlen($prefix);
  foreach($keys as $key)
  {
    if(!strncmp($key,$prefix,$n))
      unset($_SESSION[$key]);
  }
}
Copy after login

Did you see that you use the matching prefix to log out?

At this point, we can separate the front and back logins and exits. This makes it more like an application, right? Hehe...

I almost forgot to explain:

Yii::app()->user //前台访问用户信息方法
Yii::app()->admin //后台访问用户信息方法
Copy after login

If you don’t understand, take a closer look at the configuration of the front and back CWebUser just now.

Attachment 1: WebUser.php code:

<?php
class WebUser extends CWebUser
{
  public function __get($name)
  {
    if ($this->hasState(&#39;__userInfo&#39;)) {
      $user=$this->getState(&#39;__userInfo&#39;,array());
      if (isset($user[$name])) {
        return $user[$name];
      }
    }
    return parent::__get($name);
  }
  public function login($identity, $duration) {
    $this->setState(&#39;__userInfo&#39;, $identity->getUser());
    parent::login($identity, $duration);
  }
}
?>
Copy after login

Attachment 2: AdminWebUser.php code

<?php
class AdminWebUser extends CWebUser
{
  public function __get($name)
  {
    if ($this->hasState(&#39;__adminInfo&#39;)) {
      $user=$this->getState(&#39;__adminInfo&#39;,array());
      if (isset($user[$name])) {
        return $user[$name];
      }
    }
    return parent::__get($name);
  }
  public function login($identity, $duration) {
    $this->setState(&#39;__adminInfo&#39;, $identity->getUser());
    parent::login($identity, $duration);
  }
}
?>
Copy after login

Attachment 3: Front-end UserIdentity.php code

<?php
/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
  /**
   * Authenticates a user.
   * The example implementation makes sure if the username and password
   * are both &#39;demo&#39;.
   * In practical applications, this should be changed to authenticate
   * against some persistent user identity storage (e.g. database).
   * @return boolean whether authentication succeeds.
   */
  public $user;
  public $_id;
  public $username;
  public function authenticate()
  {
    $this->errorCode=self::ERROR_PASSWORD_INVALID;
    $user=User::model()->find(&#39;username=:username&#39;,array(&#39;:username&#39;=>$this->username));
     if ($user)
    {
      $encrypted_passwd=trim($user->password);
      $inputpassword = trim(md5($this->password));
      if($inputpassword===$encrypted_passwd)
      {
        $this->errorCode=self::ERROR_NONE;
        $this->setUser($user);
        $this->_id=$user->id;
        $this->username=$user->username;
        //if(isset(Yii::app()->user->thisisadmin))
          // unset (Yii::app()->user->thisisadmin);
      }
      else
      {
        $this->errorCode=self::ERROR_PASSWORD_INVALID;
      }
    }
    else
    {
      $this->errorCode=self::ERROR_USERNAME_INVALID;
    }
    unset($user);
    return !$this->errorCode;
  }
  public function getUser()
  {
    return $this->user;
  }
  public function getId()
  {
    return $this->_id;
  }
  public function getUserName()
  {
    return $this->username;
  }
  public function setUser(CActiveRecord $user)
  {
    $this->user=$user->attributes;
  }
}
Copy after login

Attachment 4: Backend UserIdentity.php code

<?php
/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
  /**
   * Authenticates a user.
   * The example implementation makes sure if the username and password
   * are both &#39;demo&#39;.
   * In practical applications, this should be changed to authenticate
   * against some persistent user identity storage (e.g. database).
   * @return boolean whether authentication succeeds.
   */
  public $admin;
  public $_id;
  public $username;
  public function authenticate()
  {
    $this->errorCode=self::ERROR_PASSWORD_INVALID;
    $user=Staff::model()->find(&#39;username=:username&#39;,array(&#39;:username&#39;=>$this->username));
     if ($user)
    {
      $encrypted_passwd=trim($user->password);
      $inputpassword = trim(md5($this->password));
      if($inputpassword===$encrypted_passwd)
      {
        $this->errorCode=self::ERROR_NONE;
        $this->setUser($user);
        $this->_id=$user->id;
        $this->username=$user->username;
        // Yii::app()->user->setState("thisisadmin", "true");
      }
      else
      {
        $this->errorCode=self::ERROR_PASSWORD_INVALID;
      }
    }
    else
    {
      $this->errorCode=self::ERROR_USERNAME_INVALID;
    }
    unset($user);
    return !$this->errorCode;
  }
  public function getUser()
  {
    return $this->admin;
  }
  public function getId()
  {
    return $this->_id;
  }
  public function getUserName()
  {
    return $this->username;
  }
  public function setUser(CActiveRecord $user)
  {
    $this->admin=$user->attributes;
  }
}
Copy after login

##The above is the entire content of this article, I hope it will be helpful to everyone’s learning. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

About using join and joinwith for multi-table association queries in Yii2

About using Yii2 WeChat backend Developed analysis

#

The above is the detailed content of About the implementation of the method of handling front and back login in Yii. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Yii3 framework in php? How to use Yii3 framework in php? May 31, 2023 pm 10:42 PM

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

How to use PHP framework Yii to develop a highly available cloud backup system How to use PHP framework Yii to develop a highly available cloud backup system Jun 27, 2023 am 09:04 AM

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Jun 19, 2023 am 08:09 AM

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

Data query in Yii framework: access data efficiently Data query in Yii framework: access data efficiently Jun 21, 2023 am 11:22 AM

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

Symfony vs Yii2: Which framework is better for developing large-scale web applications? Symfony vs Yii2: Which framework is better for developing large-scale web applications? Jun 19, 2023 am 10:57 AM

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

How to convert yii objects into arrays or directly output to json format How to convert yii objects into arrays or directly output to json format Jan 08, 2021 am 10:13 AM

Yii framework: This article introduces Yii's method of converting objects into arrays or directly outputting them into json format. It has certain reference value and I hope it can help you.

Yii2 Programming Guide: How to run Cron service Yii2 Programming Guide: How to run Cron service Sep 01, 2023 pm 11:21 PM

If you're asking "What is Yii?" check out my previous tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and outlines what's new in Yii 2.0, released in October 2014. Hmm> In this Programming with Yii2 series, I will guide readers in using the Yii2PHP framework. In today's tutorial, I will share with you how to leverage Yii's console functionality to run cron jobs. In the past, I've used wget - a web-accessible URL - in a cron job to run my background tasks. This raises security concerns and has some performance issues. While I discussed some ways to mitigate the risk in our Security for Startup series, I had hoped to transition to console-driven commands

Form builder in Yii framework: building complex forms Form builder in Yii framework: building complex forms Jun 21, 2023 am 10:09 AM

With the rapid development of the Internet, Web applications have increasingly become an indispensable part of people's lives. Forms are one of the indispensable elements in web applications. They are used to collect user data so that web applications can better serve users. The Yii framework is a fast, efficient, and flexible PHP framework that can help developers develop web applications more quickly. The form builder (FormBuilder) in the Yii framework allows developers to easily build complex forms, giving web applications better

See all articles