警匪 2012-02-18 19:50:00 7658次浏览 15条回复 6 1 0

之前找了好多资料,都是把登录和注册分开两个model来写,登录做成LoginForm,注册用 User,但是我一直想只用一个User,都表现出来,所以自己写了一个,看着还比较顺眼,而且我也没搜到相关文章。

  1. 建立数据库表 user,字段:user_id email password salt nike_name last_login create
  2. 用 gii 生成了叫作 User 的controller和model
  3. 在userController 中 代码:
<?php
class UserController extends Controller
{
    /*public function accessRules() {
        return array('allow',  // allow all users to perform 'list' and 'show' actions
            'actions' => array('register', 'login', 'logout', 'captcha'),
            'users' => array('*'),
        );
    }*/
    
    public function actions() {
        return array(
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
                'minLength' => 4,
                'maxLength' => 4,
                'testLimit' => 99999
            )
        );
    }

    /**
    * This is the default 'index' action that is invoked
    * when an action is not explicitly requested by users.
    */
    public function actionIndex()
    {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        $this->render('index');
    }

    public function actionRegister()
    {
        $model = new User('register');
        if(isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            $model->validate();
            //$model->getErrors();
            if($model->save()) {
                $this->redirect(array('user/login'));
            }
        }
        $this->render('register', array('model' => $model));
    }

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model = new User('login');

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['User']))
		{
			$model->attributes = $_POST['User'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login', array('model' => $model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}[/code]4. user模型中代码 models/User.php:[code]<?php

/**
 * This is the model class for table "{{user}}".
 *
 * The followings are the available columns in table '{{user}}':
 * @property integer $user_id
 * @property string $email
 * @property string $password
 * @property string $nick_name
 * @property integer $last_login
 * @property integer $create
 */
class User extends CActiveRecord
{
        //注册
        public $passwordConfirm;
        public $verifyCode;
        //登录
        public $remember;
        
        private $_identity;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{user}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('email, password, verifyCode', 'required'),
                        array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
                        array('passwordConfirm, nick_name', 'required', 'on' => 'register'),
                        array('email, nick_name', 'unique', 'on' => 'register'),
                        array('passwordConfirm', 'compare', 'compareAttribute' => 'password', 'on' => 'register'),
			array('email', 'length', 'min' => '5', 'max' => 255, 'on' => 'register'),
			array('password', 'length', 'min' => '4', 'max' => 18, 'on' => 'register'),
                        array('remember', 'boolean', 'on' => 'login'),
                        array('password', 'authenticate', 'on' => 'login'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			//array('user_id, email, password, nick_name, last_login, create', 'safe', 'on'=>'search'),
		);
	}
        
        protected function beforeSave() {
                if($this->isNewRecord) {
                        $this->salt = $this->verifyCode;
                        $this->password = md5($this->salt . $this->password);
                        $this->create = time();
                }
                
                return parent::beforeSave();
        }
        
        public function authenticate()
        {
                if(!$this->hasErrors()) {
                        $this->_identity = new UserIdentity($this->email, $this->password);
                        
                        if($this->_identity->authenticate() !== UserIdentity::ERROR_NONE) {
                                $this->addError('password', '密码错误');
                        }
                }
        }

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'email' => 'Email',
			'password' => '密码',
                        'passwordConfirm' => '确认密码',
			'nick_name' => '昵称',
                        'verifyCode' => '验证码'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;

		$criteria->compare('user_id', $this->user_id);
		$criteria->compare('email', $this->email, true);
		$criteria->compare('nick_name', $this->nick_name, true);

		return new CActiveDataProvider($this, array(
			'criteria' => $criteria,
		));
	}
        
        public function validatePassword($password)
        {
                if($this->hasPassword($password, $this->salt) === $this->password) {
                        return true;
                }
                else {
                        return false;
                }
        }
        
        public function hasPassword($password, $salt)
        {
                return md5($salt . $password);
        }
        
        public function login()
        {
                if($this->_identity === null) {
                        $this->_identity = new UserIdentity($this->email, $this->password);
                        $this->_identity->authenticate();
                }
                
                if($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
                        $duration = $this->remember ? 3600 * 24 * 30 : 0; // 30天
                        Yii::app()->user->login($this->_identity, $duration);
                        Yii::app()->user->setReturnUrl(array('/site'));
                        return true;
                } else {
                        return false;
                }
        }
}
觉得很赞
  • 回复于 2012-02-18 19:51 举报
    1. components/UserIdentity.php 代码:
    <?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
    {
        private $_id;
        private $_email;
    
    
        const ERROR_EMAIL_INVALID = 1;
    
        /**
    	 * Authenticates a user.
    	 * The example implementation makes sure if the username and password
    	 * are both 'demo'.
    	 * 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()
    	{
                    $email = strtolower($this->username);
                    $user = User::model()->find('LOWER(email)=?', array($email));
                    
                    if($user === null) {
                            $this->errorCode = self::ERROR_EMAIL_INVALID;
                    } else if(!$user->validatePassword($this->password)){
                            $this->errorCode = self::ERROR_PASSWORD_INVALID;
                    } else {
                            $this->_id = $user->user_id;
                            $this->_email = $user->email;
                            $this->errorCode = self::ERROR_NONE;
                    }
    
                    return $this->errorCode;
    	}
            
            // Get User ID
            public function getId()
            {
                    return $this->_id;
            }
            
            public function getEmail()
            {
                    return $this->_email;
            }
    }
    
    1. views/user/register.php
    <?php
    $this->pageTitle = Yii::app()->name . ' - 用户注册';
    $this->breadcrumbs = array('用户注册')
    ?>
    <h1>注册</h1>
    <div class="form">
    <?php
    echo CHtml::beginForm();
    ?>
    <div class="row">
        <?php echo CHtml::activeLabelEx($model, 'email'); ?>
        <?php echo CHtml::activeTextField($model, 'email', array('size' => 30, 'maxlength' => 100)); ?>
        <?php echo CHtml::error($model, 'email'); ?>
    </div>
    <div class="row">
        <?php echo CHtml::activeLabelEx($model, 'password'); ?>
        <?php echo CHtml::activePasswordField($model, 'password', array('size' => 30, 'maxlength' => 100))?>
        <?php echo CHtml::error($model, 'password'); ?>
    </div>
    <div class="row">
        <?php echo CHtml::activeLabelEx($model, 'passwordConfirm'); ?>
        <?php echo CHtml::activePasswordField($model, 'passwordConfirm', array('size' => 30, 'maxlength' => 100))?>
        <?php echo CHtml::error($model, 'passwordConfirm'); ?>
    </div>
    <div class="row">
        <?php echo CHtml::activeLabelEx($model, 'nick_name'); ?>
        <?php echo CHtml::activeTextField($model, 'nick_name', array('size' => 30, 'maxlength' => 100))?>
        <?php echo CHtml::error($model, 'nick_name'); ?>
    </div>
    <div class="row">
        <?php $this->widget('CCaptcha'); ?>
        <?php echo CHtml::activeLabelEx($model, 'verifyCode'); ?>
        <?php echo CHtml::activeTextField($model, 'verifyCode', array('size' => 8, 'maxlength' => 10))?>
    </div>
    <div class="row">
        <?php echo CHtml::submitButton('注册', array('name' => 'submit'))?>
    </div>
    <?php echo CHtml::endForm(); ?>
    </div>
    
    1. views/user/login.php
    <?php
    $this->pageTitle=Yii::app()->name . ' - Login';
    $this->breadcrumbs=array(
        'Login',
    );
    ?>
    
    <h1>Login</h1>
    
    <p>Please fill out the following form with your login credentials:</p>
    
    <div class="form">
    <?php $form=$this->beginWidget('CActiveForm', array(
    	'id'=>'login-form',
    	'enableClientValidation'=>true,
    	'clientOptions'=>array(
    		'validateOnSubmit'=>true,
    	),
    )); ?>
    
    	<p class="note">Fields with <span class="required">*</span> are required.</p>
    
    	<div class="row">
    		<?php echo $form->labelEx($model,'email'); ?>
    		<?php echo $form->textField($model,'email'); ?>
    		<?php echo $form->error($model,'email'); ?>
    	</div>
    
    	<div class="row">
    		<?php echo $form->labelEx($model, 'password'); ?>
    		<?php echo $form->passwordField($model, 'password'); ?>
    		<?php echo $form->error($model, 'password'); ?>
    		<p class="hint">
    			Hint: You may login with <tt>demo/demo</tt> or <tt>admin/admin</tt>.
    		</p>
    	</div>
            
    	<div class="row">
    		<?php $this->widget('CCaptcha'); ?>
    		<?php echo $form->textField($model, 'verifyCode'); ?>
    		<?php echo $form->error($model, 'verifyCode'); ?>
    		<p class="hint">
    			Hint: You may login with <tt>demo/demo</tt> or <tt>admin/admin</tt>.
    		</p>
    	</div>
    
    	<div class="row rememberMe">
    		<?php echo $form->checkBox($model, 'remember'); ?>
    		<?php echo $form->label($model, 'remember'); ?>
    		<?php echo $form->error($model, 'remember'); ?>
    	</div>
    
    	<div class="row buttons">
    		<?php echo CHtml::submitButton('Login'); ?> <?php echo CHTML::link('注册', array('user/register'))?>
    	</div>
    
    <?php $this->endWidget(); ?>
    </div><!-- form -->
    
  • 回复于 2012-02-19 09:12 举报

    谢谢分享,拿走了

  • 回复于 2012-02-20 09:49 举报

    谢谢分享,用用看

  • 回复于 2012-02-20 09:57 举报

    谢谢分享!

  • 回复于 2012-02-20 14:43 举报

    谢谢分享 先试试看

  • 回复于 2012-04-15 13:27 举报

    有ajax验证吗

  • 回复于 2012-04-15 13:30 举报

    有ajax验证过程吗

  • 回复于 2012-04-15 13:31 举报

    有ajax验证吗

  • 回复于 2012-04-16 07:38 举报

    不错,学习学习

  • 回复于 2012-04-23 15:07 举报

    谢谢分享。
    有个疑问,views/user/register.php和views/user/login.php都是一行行敲的吗?还是CRUD创建的?

  • 回复于 2012-04-28 10:30 举报

    我全部拿来了,为什么印证码不显示呢

  • 回复于 2012-05-28 10:40 举报

    这是你自己写的么?怎么看都是和教程上的代码一样样啊...

  • 回复于 2012-05-29 18:32 举报

    我怎么改成用用户名和密码登陆就出问题呢。。。。。。求解

  • 回复于 2015-10-05 10:06 举报

    感謝需要這種參考!

  • 回复于 2016-03-12 08:53 举报

    可以可以,拿走了

您需要登录后才可以回复。登录 | 立即注册