search
HomeBackend DevelopmentPHP TutorialAbout the implementation of the method of handling front and back login in 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保存登录信息,一边下次自动登录
),

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;
  }
}
?>

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]);
  }
}

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 //后台访问用户信息方法

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);
  }
}
?>

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);
  }
}
?>

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;
  }
}

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;
  }
}

##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
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
如何使用PHP框架Yii开发一个高可用的云备份系统如何使用PHP框架Yii开发一个高可用的云备份系统Jun 27, 2023 am 09:04 AM

随着云计算技术的不断发展,数据的备份已经成为了每个企业必须要做的事情。在这样的背景下,开发一款高可用的云备份系统尤为重要。而PHP框架Yii是一款功能强大的框架,可以帮助开发者快速构建高性能的Web应用程序。下面将介绍如何使用Yii框架开发一款高可用的云备份系统。设计数据库模型在Yii框架中,数据库模型是非常重要的一部分。因为数据备份系统需要用到很多的表和关

Yii2 vs Phalcon:哪个框架更适合开发显卡渲染应用?Yii2 vs Phalcon:哪个框架更适合开发显卡渲染应用?Jun 19, 2023 am 08:09 AM

在当前信息时代,大数据、人工智能、云计算等技术已经成为了各大企业关注的热点。在这些技术中,显卡渲染技术作为一种高性能图形处理技术,受到了越来越多的关注。显卡渲染技术被广泛应用于游戏开发、影视特效、工程建模等领域。而对于开发者来说,选择一个适合自己项目的框架,是一个非常重要的决策。在当前的语言中,PHP是一种颇具活力的语言,一些优秀的PHP框架如Yii2、Ph

php如何使用Yii3框架?php如何使用Yii3框架?May 31, 2023 pm 10:42 PM

随着互联网的不断发展,Web应用程序开发的需求也越来越高。对于开发人员而言,开发应用程序需要一个稳定、高效、强大的框架,这样可以提高开发效率。Yii是一款领先的高性能PHP框架,它提供了丰富的特性和良好的性能。Yii3是Yii框架的下一代版本,它在Yii2的基础上进一步优化了性能和代码质量。在这篇文章中,我们将介绍如何使用Yii3框架来开发PHP应用程序。

Yii框架中的数据查询:高效地访问数据Yii框架中的数据查询:高效地访问数据Jun 21, 2023 am 11:22 AM

Yii框架是一个开源的PHPWeb应用程序框架,提供了众多的工具和组件,简化了Web应用程序开发的流程,其中数据查询是其中一个重要的组件之一。在Yii框架中,我们可以使用类似SQL的语法来访问数据库,从而高效地查询和操作数据。Yii框架的查询构建器主要包括以下几种类型:ActiveRecord查询、QueryBuilder查询、命令查询和原始SQL查询

Symfony vs Yii2:哪个框架更适合开发大型Web应用?Symfony vs Yii2:哪个框架更适合开发大型Web应用?Jun 19, 2023 am 10:57 AM

随着Web应用需求的不断增长,开发者们在选择开发框架方面也越来越有选择的余地。Symfony和Yii2是两个备受欢迎的PHP框架,它们都具有强大的功能和性能,但在面对需要开发大型Web应用时,哪个框架更适合呢?接下来我们将对Symphony和Yii2进行比较分析,以帮助你更好地进行选择。基本概述Symphony是一个由PHP编写的开源Web应用框架,它是建立

yii如何将对象转化为数组或直接输出为json格式yii如何将对象转化为数组或直接输出为json格式Jan 08, 2021 am 10:13 AM

yii框架:本文为大家介绍了yii将对象转化为数组或直接输出为json格式的方法,具有一定的参考价值,希望能够帮助到大家。

Yii2编程指南:运行Cron服务的方法Yii2编程指南:运行Cron服务的方法Sep 01, 2023 pm 11:21 PM

如果您问“Yii是什么?”查看我之前的教程:Yii框架简介,其中回顾了Yii的优点,并概述了2014年10月发布的Yii2.0的新增功能。嗯>在这个使用Yii2编程系列中,我将指导读者使用Yii2PHP框架。在今天的教程中,我将与您分享如何利用Yii的控制台功能来运行cron作业。过去,我在cron作业中使用了wget—可通过Web访问的URL来运行我的后台任务。这引发了安全问题并存在一些性能问题。虽然我在我们的启动系列安全性专题中讨论了一些减轻风险的方法,但我曾希望过渡到控制台驱动的命令

PHP开发:使用 Yii2 和 GrapeJS 实现后台 CMS 和 前端可视化编辑PHP开发:使用 Yii2 和 GrapeJS 实现后台 CMS 和 前端可视化编辑Jun 15, 2023 pm 11:48 PM

在现代软件开发中,构建一个强大的内容管理系统(CMS)并不是一项容易的任务。不仅需要开发人员具备丰富的技能以及经验,还需要使用最先进的技术和工具来使其功能与性能达到最优化。本文介绍了如何使用Yii2和GrapeJS,两个流行的开源软件来实现后台CMS和前端可视化编辑。Yii2是一个流行的PHPWeb框架,它提供了丰富的工具和组件来快速构

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.