>  기사  >  백엔드 개발  >  Yii 프레임워크에서 인증 코드, 로그인 및 종료 기능 구현의 예

Yii 프레임워크에서 인증 코드, 로그인 및 종료 기능 구현의 예

巴扎黑
巴扎黑원래의
2017-08-13 14:34:361249검색

이 글에서는 주로 Yii 프레임워크에서 구현한 인증 코드, 로그인, 로그아웃 기능을 소개하고, 도움이 필요한 친구들이 참고할 수 있는 구체적인 사례를 바탕으로 Yii 프레임워크를 기반으로 한 사용자 인증 로그인 및 로그아웃 작업의 관련 단계와 운영 기법을 분석합니다. it

이 글에서는 Yii 프레임워크에서 구현한 인증코드, 로그인, 로그아웃 기능을 예시를 통해 설명합니다. 자세한 내용은 다음과 같습니다.

오후 동안 고민한 끝에 마침내 작동하게 된 코드는 다음과 같습니다.

Model


<?php
class Auth extends CActiveRecord {
  public static function model($className = __CLASS__) {
    return parent::model($className);
  }
  public function tableName() {
    return &#39;{{auth}}&#39;;
  }
}

참고: 내 사용자 테이블은 auth이므로 모델은 Auth.php


<?php
class IndexForm extends CFormModel {
  public $a_account;
  public $a_password;
  public $rememberMe;
  public $verifyCode;
  public $_identity;
  public function rules() {
    return array(
      array(&#39;verifyCode&#39;, &#39;captcha&#39;, &#39;allowEmpty&#39; => !CCaptcha::checkRequirements(), &#39;message&#39;=>&#39;请输入正确的验证码&#39;),
      array(&#39;a_account&#39;, &#39;required&#39;, &#39;message&#39; => &#39;用户名必填&#39;),
      array(&#39;a_password&#39;, &#39;required&#39;, &#39;message&#39; => &#39;密码必填&#39;),
      array(&#39;a_password&#39;, &#39;authenticate&#39;),
      array(&#39;rememberMe&#39;, &#39;boolean&#39;),
    );
  }
  public function authenticate($attribute, $params) {
    if (!$this->hasErrors()) {
      $this->_identity = new UserIdentity($this->a_account, $this->a_password);
      if (!$this->_identity->authenticate()) {
        $this->addError(&#39;a_password&#39;, &#39;用户名或密码不存在&#39;);
      }
    }
  }
  public function login() {
    if ($this->_identity === null) {
      $this->_identity = new UserIdentity($this->a_account, $this->a_password);
      $this->_identity->authenticate();
    }
    if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
      $duration = $this->rememberMe ? 60*60*24*7 : 0;
      Yii::app()->user->login($this->_identity, $duration);
      return true;
    } else {
      return false;
    }
  }
  public function attributeLabels() {
    return array(
      &#39;a_account&#39;   => &#39;用户名&#39;,
      &#39;a_password&#39;   => &#39;密码&#39;,
      &#39;rememberMe&#39;  => &#39;记住登录状态&#39;,
      &#39;verifyCode&#39;  => &#39;验证码&#39;
    );
  }
}

참고: IndexForm은 LoginForm으로 작성할 수도 있지만 이미 시스템에 존재하므로 , 일반적으로 비밀번호와 사용자 이름인 사용자 테이블의 필드에 주의하세요. 제 필드는 a_account 및 a_password

Controller


<?php
class IndexController extends Controller {
  public function actions() {
    return array(
      &#39;captcha&#39; => array(
        &#39;class&#39; => &#39;CCaptchaAction&#39;,
        &#39;width&#39;=>100,
        &#39;height&#39;=>50
      )
    );
  }
  public function actionLogin() {
    if (Yii::app()->user->id) {
      echo "<p>欢迎" . Yii::app()->user->id . ",<a href=&#39;" . SITE_URL . "admin/index/logout&#39;>退出</a></p>";
    } else {
      $model = new IndexForm();
      if (isset($_POST[&#39;IndexForm&#39;])) {
        $model->attributes = $_POST[&#39;IndexForm&#39;];
        if ($model->validate() && $model->login()) {
          echo "<p>欢迎" . Yii::app()->user->id . ",<a href=&#39;" . SITE_URL . "admin/index/logout&#39;>退出</a></p>";exit;
        }
      }
      $this->render(&#39;login&#39;, array(&#39;model&#39; => $model));
    }
  }
  public function actionLogout() {
    Yii::app()->user->logout();
    $this->redirect(SITE_URL . &#39;admin/index/login&#39;);
  }
}

입니다. 참고: 첫 번째 방법은 확인 코드를 추가하는 것입니다.

view


<meta http-equiv="content-type" content="text/html;charset=utf-8">
<?php
$form = $this->beginWidget(&#39;CActiveForm&#39;, array(
  &#39;id&#39;            => &#39;login-form&#39;,
  &#39;enableClientValidation&#39;  => true,
  &#39;clientOptions&#39;       => array(
    &#39;validateOnSubmit&#39;   => true
  )
));
?>
  <p class="row">
    <?php echo $form->labelEx($model,&#39;a_account&#39;); ?>
    <?php echo $form->textField($model,&#39;a_account&#39;); ?>
    <?php echo $form->error($model,&#39;a_account&#39;); ?>
  </p>
  <p class="row">
    <?php echo $form->labelEx($model,&#39;a_password&#39;); ?>
    <?php echo $form->passwordField($model,&#39;a_password&#39;); ?>
    <?php echo $form->error($model,&#39;a_password&#39;); ?>
  </p>
  <?php if(CCaptcha::checkRequirements()) { ?>
  <p class="row">
    <?php echo $form->labelEx($model, &#39;verifyCode&#39;); ?>
    <?php $this->widget(&#39;CCaptcha&#39;); ?>
    <?php echo $form->textField($model, &#39;verifyCode&#39;); ?>
    <?php echo $form->error($model, &#39;verifyCode&#39;); ?>
  </p>
  <?php } ?>
  <p class="row rememberMe">
    <?php echo $form->checkBox($model,&#39;rememberMe&#39;); ?>
    <?php echo $form->label($model,&#39;rememberMe&#39;); ?>
    <?php echo $form->error($model,&#39;rememberMe&#39;); ?>
  </p>
  <p class="row buttons">
    <?php echo CHtml::submitButton(&#39;Submit&#39;); ?>
  </p>
<?php $this->endWidget(); ?>

또한 프로젝트


<?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 function authenticate()
  {
    /*
    $users=array(
      // username => password
      &#39;demo&#39;=>&#39;demo&#39;,
      &#39;admin&#39;=>&#39;admin&#39;,
    );
    if(!isset($users[$this->username]))
      $this->errorCode=self::ERROR_USERNAME_INVALID;
    elseif($users[$this->username]!==$this->password)
      $this->errorCode=self::ERROR_PASSWORD_INVALID;
    else
      $this->errorCode=self::ERROR_NONE;
    return !$this->errorCode;
    */
    $user_model = Auth::model()->find(&#39;a_account=:name&#39;,array(&#39;:name&#39;=>$this->username));
    if($user_model === null){
      $this -> errorCode = self::ERROR_USERNAME_INVALID;
      return false;
    } else if ($user_model->a_password !== md5($this -> password)){
      $this->errorCode=self::ERROR_PASSWORD_INVALID;
      return false;
    } else {
      $this->errorCode=self::ERROR_NONE;
      return true;
    }
  }
}
아래 보호/컴포넌트 아래의 UserIdentity.php를 수정하세요.

위 내용은 Yii 프레임워크에서 인증 코드, 로그인 및 종료 기능 구현의 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.