3

我在 yii 中创建了登录功能,但我需要开发它以同时使用电子邮件或用户 ID。在下面,您将通过电子邮件代码检查登录,它在完美模式下工作,对开发有帮助吗?

组件/UserIdentity.php

<?php

/** Ahmad Samilo
 * 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
{

     // Need to store the user's ID:
     private $_id;
     public $password;
     public $status;
     public $session;

    /**
     * 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()
    {
        $user = Users::model()->findByAttributes(array('email'=>$this->username));


            /// set number of faild login
             $session=new CHttpSession;
             $session->open();

           Yii::app()->session['number']= Yii::app()->session['number']+1;
           $session=Yii::app()->session['number'];
              /// end 




        if ($user===null) { // No user found!
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        } else if ($user->password !== SHA1($this->password) ) { // Invalid password!
            $this->errorCode=self::ERROR_PASSWORD_INVALID;







        } else { // Okay!



             $this->errorCode=self::ERROR_NONE;
            // Store the role in a session:
             $this->setState('status', $user->active);

             $this->setState('id', $user->user_id);
            $this->_id = $user->user_id;
        }
        return !$this->errorCode;
    }

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


}

查看/login.php

<?php
/* @var $this SiteController */
/* @var $model LoginForm */
/* @var $form CActiveForm  */

$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'=>false,
    ),
)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>

<?php



foreach(Yii::app()->user->getFlashes() as $key=>$message){

    echo "<div class='info'>";
     echo '<div class="flash-' . $key . '">' . $message . "</div>\n";

     echo "</div>";
}


?>


<?php


//// Get Session 
$session=new CHttpSession();
$session->open();
$count= Yii::app()->session['number'];


/// End Get Session 

//// Send Email to user notify him about that with help guide 
           function send_mail($to,$from,$subject,$msg){
        // message
        $message = '
        <html>
        <head>
          <title>Activation </title>
        </head>
        <body dir="rtl">
        <p align="right">'
        . $msg .
        '</p>
        <br>

        </p>
        </body>
        </html>
        ';

        // To send HTML mail, the Content-type header must be set
        $headers  = 'MIME-Version: 1.0' . "\n";
        $headers .= 'Content-type: text/html; charset=windows-1256' . "\n";

        // Additional heade rs
        $headers .= "From: ".$from . "\n";
        //$headers .= 'Bcc: info@illaftrain.co.uk' . "\n";

        // Mail it
        return mail($to, '=?windows-1256?B?'.base64_encode($subject).'?=', $message, $headers);
    }

//////

$email=$model->email;


$subject="تنبيه تكرار تسجيل الدخول الخاطئ ";

$url=Yii::app()->request->serverName;
$message=" 

text here 

";

 send_mail($email,'noreply@domain.net',$subject,$message);


//// End mail Function 





//// End Send mail 


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



    </div>


    <div class="row buttons">
        <?php echo CHtml::submitButton('Login'); ?>
    </div>


    <?php if($count>3) :?>
    <?php if(CCaptcha::checkRequirements()): ?>
        <?php echo $form->labelEx($model,'verifyCode'); ?>
        <div>
        <?php $this->widget('CCaptcha'); ?>
        <?php echo $form->textField($model,'verifyCode'); ?>
        </div>
    <div class="row">
        <div class="hint">Please enter the letters as they are shown in the image above.
        <br/>Letters are not case-sensitive.</div>
        <?php echo $form->error($model,'verifyCode'); ?>
    </div>
    <?php endif; ?>
    <?php endif; ?>









<?php $this->endWidget(); ?>

模型/LoginForm.php

<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class LoginForm extends CFormModel
{
    public $email;
    public $password;
    public $login;
    public $verifyCode;


    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
public function rules()
{
    return array(
        array('email, password', 'required'),
        array('email', 'email'),
        array('password', 'authenticate'),
            // verifyCode needs to be entered correctly
            array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),

);

}

    /**
     * Declares attribute labels.
     */
    public function attributeLabels()
    {
        return array(
            'email'=>'Email Address',
            'user_id'=>'User ID',
        );
    }

    /**
     * Authenticates the password.
     * This is the 'authenticate' validator as declared in rules().
     */
    public function authenticate($attribute,$params)
    {
        if(!$this->hasErrors())  // we only want to authenticate when no input errors
        {
            $identity=new UserIdentity($this->email,$this->password);
            $identity->authenticate();
            switch($identity->errorCode)
            {
                case UserIdentity::ERROR_NONE:
                    Yii::app()->user->login($identity);

                    break;
                case UserIdentity::ERROR_USERNAME_INVALID:
                    $this->addError('email','Email address is incorrect.');
                    break;
                default: // UserIdentity::ERROR_PASSWORD_INVALID
                    $this->addError('password','Password is incorrect.');
                    break;
            }
        }
    }


}
4

1 回答 1

4

在 UserIdentity 的身份验证功能中

代替:

$user = Users::model()->findByAttributes(array('email'=>$this->username));

做类似的事情

//If we have a @ in the username, then it should be an email
if(strpos($this->username, '@') !== false){
   $user = Users::model()->findByAttributes(array('email'=>$this->username));
}else{
   //Otherwise we search using the username
   $user = Users::model()->findByAttributes(array('username'=>$this->username));
}

注意:前提是您不允许在用户名中使用 @

于 2012-11-28T13:52:04.670 回答