您的位置:首页 > 编程语言 > PHP开发

yii 登陆全应用

2013-12-03 15:56 330 查看
1.登陆

控制器

<?php

class LoginController extends Controller
{
public $defaultAction = 'login';

/**
* Displays the login page
*/
public function actionLogin()
{
if (Yii::app()->user->isGuest) {     //如果main文件没指定就是CWebUser  可制定为WebUser 然后在Compenont写一个类出来

$model=new UserLogin;
// collect user input data
if(isset($_POST['UserLogin']))
{
$model->attributes=$_POST['UserLogin'];
// validate user input and redirect to previous page if valid
if($model->validate()) {
$this->lastViset();
if (Yii::app()->getBaseUrl()."/index.php" === Yii::app()->user->returnUrl)
$this->redirect(Yii::app()->controller->module->returnUrl);
else
$this->redirect(Yii::app()->user->returnUrl);
}
}
// display the login form
$this->render('/user/login',array('model'=>$model));
} else
$this->redirect(Yii::app()->controller->module->returnUrl);
}

}


  

UserLogin模型类


<?php

class UserLogin extends CFormModel
{
public $username;
public $password;
public $rememberMe;

public function rules()
{
return array(
// username and password are required
array('username, password', 'required'),
// rememberMe needs to be a boolean
array('rememberMe', 'boolean'),
// password needs to be authenticated
array('password', 'authenticate'),
);
}

public function attributeLabels()
{
return array(
'rememberMe'=>UserModule::t("Remember me next time"),
'username'=>UserModule::t("username or email"),
'password'=>UserModule::t("password"),
);
}

public function authenticate($attribute,$params)
{

if(!$this->hasErrors())  // we only want to authenticate when no input errors
{
$identity=new UserIdentity($this->username,$this->password);
$identity->authenticate();
switch($identity->errorCode)
{
case UserIdentity::ERROR_NONE:
$duration=$this->rememberMe ? Yii::app()->controller->module->rememberMeTime : 0;
Yii::app()->user->login($identity,$duration);
break;
case UserIdentity::ERROR_EMAIL_INVALID:
$this->addError("username",'邮箱有误');
break;
case UserIdentity::ERROR_USERNAME_INVALID:
$this->addError("username",UserModule::t("Username is incorrect."));
break;
case UserIdentity::ERROR_STATUS_NOTACTIV:
$this->addError("status",UserModule::t("You account is not activated."));
break;
case UserIdentity::ERROR_STATUS_BAN:
$this->addError("status",UserModule::t("You account is blocked."));
break;
case UserIdentity::ERROR_PASSWORD_INVALID:
$this->addError("password",UserModule::t("Password is incorrect."));
break;
}
}
}
}


 

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;

const ERROR_EMAIL_INVALID = 3;
const ERROR_STATUS_NOTACTIV = 4;
const ERROR_STATUS_BAN = 5;

/**
* 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() {
if (strpos($this->username, "@")) {
$user = User::model()->notsafe()->findByAttributes(array('email' => $this->username));
} else {
$user = User::model()->notsafe()->findByAttributes(array('username' => $this->username));
}
if ($user === null)
if (strpos($this->username, "@")) {
$this->errorCode = 3;
} else {
$this->errorCode = self::ERROR_USERNAME_INVALID;
}
//else if(Yii::app()->getModule('user')->encrypting($this->password)!==$user->password)
else if (Yii::app()->getModule('user')->encrypting($this->password) == $user->password)
$this->errorCode = self::ERROR_PASSWORD_INVALID;
else if ($user->status == 0 && Yii::app()->getModule('user')->loginNotActiv == false)
$this->errorCode = self::ERROR_STATUS_NOTACTIV;
else if ($user->status == -1)
$this->errorCode = self::ERROR_STATUS_BAN;
else {
$this->_id = $user->id;
$this->username = $user->username;
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}

/**
* @return integer the ID of the user record
*/
public function getId() {
return $this->_id;
}

}


  

User模型类


<?php

class User extends CActiveRecord {

const STATUS_NOACTIVE = 0;
const STATUS_ACTIVE = 1;
const STATUS_BANNED = -1;

//TODO: Delete for next version (backward compatibility)
const STATUS_BANED = -1;

/**
* The followings are the available columns in table 'users':
* @var integer $id
* @var string $username
* @var string $password
* @var string $email
* @var string $activkey
* @var integer $createtime
* @var integer $lastvisit
* @var integer $superuser
* @var integer $status
* @var timestamp $create_at
* @var timestamp $lastvisit_at
*/

/**
* Returns the static model of the specified AR class.
* @return CActiveRecord 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 Yii::app()->getModule('user')->tableUsers;
}

/**
* @return array validation rules for model attributes.
*/
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.CConsoleApplication
return ((get_class(Yii::app()) == 'CConsoleApplication' || (get_class(Yii::app()) != 'CConsoleApplication' && Yii::app()->getModule('user')->isAdmin())) ? array(
array('username', 'length', 'max' => 20, 'min' => 3, 'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),
array('password', 'length', 'max' => 128, 'min' => 4, 'message' => UserModule::t("Incorrect password (minimal length 4 symbols).")),
array('email', 'email'),
array('username', 'unique', 'message' => UserModule::t("This user's name already exists.")),
array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u', 'message' => UserModule::t("Incorrect symbols (A-z0-9).")),
array('status', 'in', 'range' => array(self::STATUS_NOACTIVE, self::STATUS_ACTIVE, self::STATUS_BANNED)),
array('superuser', 'in', 'range' => array(0, 1)),
array('create_at', 'default', 'value' => date('Y-m-d H:i:s'), 'setOnEmpty' => true, 'on' => 'insert'),
array('lastvisit_at', 'default', 'value' => '0000-00-00 00:00:00', 'setOnEmpty' => true, 'on' => 'insert'),
array('username, email, superuser, status', 'required'),
array('superuser, status', 'numerical', 'integerOnly' => true),
array('id, username, password, email, activkey, create_at, lastvisit_at, superuser, status', 'safe', 'on' => 'search'),
) : ((Yii::app()->user->id == $this->id) ? array(
array('username, email', 'required'),
array('username', 'length', 'max' => 20, 'min' => 3, 'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),
array('email', 'email'),
array('username', 'unique', 'message' => UserModule::t("This user's name already exists.")),
array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u', 'message' => UserModule::t("Incorrect symbols (A-z0-9).")),
array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
) : array()));
}

/**
* @return array relational rules.
*/
public function relations() {
$relations = Yii::app()->getModule('user')->relations;
if (!isset($relations['profile']))
$relations['profile'] = array(self::HAS_ONE, 'Profile', 'user_id');
return $relations;
}

/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => UserModule::t("Id"),
'username' => UserModule::t("username"),
'password' => UserModule::t("password"),
'verifyPassword' => UserModule::t("Retype Password"),
'email' => UserModule::t("E-mail"),
'verifyCode' => UserModule::t("Verification Code"),
'activkey' => UserModule::t("activation key"),
'createtime' => UserModule::t("Registration date"),
'create_at' => UserModule::t("Registration date"),
'lastvisit_at' => UserModule::t("Last visit"),
'superuser' => UserModule::t("Superuser"),
'status' => UserModule::t("Status"),
);
}

public function scopes() {
return array(
'active' => array(
'condition' => 'status=' . self::STATUS_ACTIVE,
),
'notactive' => array(
'condition' => 'status=' . self::STATUS_NOACTIVE,
),
'banned' => array(
'condition' => 'status=' . self::STATUS_BANNED,
),
'superuser' => array(
'condition' => 'superuser=1',
),
'notsafe' => array(
'select' => 'id, username, password, email, activkey, create_at, lastvisit_at, superuser, status',
),
);
}

public function defaultScope() {
return CMap::mergeArray(Yii::app()->getModule('user')->defaultScope, array(
'alias' => 'user',
'select' => 'user.id, user.username, user.email, user.create_at, user.lastvisit_at, user.superuser, user.status',
));
}
}


 

public function scopes() {
return array(
'published'=>array( 'condition'=>'status=1', ),
'recently'=>array( 'order'=>'create_time DESC', 'limit'=>5, ),
);
}
}


$posts=Post::model()->published()->recently()->findAll();


  

public function recently($limit=5) {
$this->getDbCriteria()->mergeWith(array(
'order'=>'create_time DESC',
'limit'=>$limit, )
);
return $this;
}


$posts=Post::model()->published()->recently(3)->findAll();


  

  

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: