yii2.0使用migrate创建后台登陆

转载自:

http://blog.csdn.net/maclechan/article/details/45960601


(注:高级应用)

重新创建一张数据表来完成后台登陆验证

为了大家看得明白,直接贴代码

一、使用Migration创建表admin

console\migrations\m130524_201442_init.php

  1. use yii\db\Schema;  
  2. use yii\db\Migration;  
  3. class m130524_201442_init extends Migration  
  4. {  
  5.     const TBL_NAME = '{{%admin}}';  
  6.     public function safeUp()  
  7.     {  
  8.         $tableOptions = null;  
  9.         if ($this->db->driverName === 'mysql') {  
  10.             // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci  
  11.             $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';  
  12.         }  
  13.         $this->createTable(self::TBL_NAME, [  
  14.             'id' => Schema::TYPE_PK,  
  15.             'username' => Schema::TYPE_STRING . ' NOT NULL',  
  16.             'auth_key' => Schema::TYPE_STRING . '(32) NOT NULL',    
  17.             'password_hash' => Schema::TYPE_STRING . ' NOT NULL'//密码  
  18.             'password_reset_token' => Schema::TYPE_STRING,  
  19.             'email' => Schema::TYPE_STRING . ' NOT NULL',  
  20.             'role' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10',  
  21.             'status' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10',  
  22.             'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',  
  23.             'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',  
  24.         ], $tableOptions);  
  25.           
  26.         $this->createIndex('username', self::TBL_NAME, ['username'],true);  
  27.         $this->createIndex('email', self::TBL_NAME, ['email'],true);  
  28.     }  
  29.     public function safeDown()  
  30.     {  
  31.         $this->dropTable(self::TBL_NAME);  
  32.     }  
  33. }  

使用命令行来创建admin数据库

1、win7下使用命令:

在项目根目下,右键选择User composer here(前提是安装了全局的composer),

yii migrate

即创建数据表 admin成功


2,linux下命令一样(此处略)


二、使用gii创建模型

此处略,很简单的步聚。

注:把admin模型创在 backend/models下面 (放哪里看个人喜好)

代码如下

  1. namespace backend\models;  
  2.   
  3. use Yii;  
  4. use yii\base\NotSupportedException;  
  5. use yii\behaviors\TimestampBehavior;  
  6. use yii\db\ActiveRecord;  
  7. use yii\web\IdentityInterface;  
  8.   
  9. /** 
  10.  * This is the model class for table "{{%admin}}". 
  11.  * 
  12.  * @property integer $id 
  13.  * @property string $username 
  14.  * @property string $auth_key 
  15.  * @property string $password_hash 
  16.  * @property string $password_reset_token 
  17.  * @property string $email 
  18.  * @property integer $role 
  19.  * @property integer $status 
  20.  * @property integer $created_at 
  21.  * @property integer $updated_at 
  22.  */  
  23. class AgAdmin extends ActiveRecord implements IdentityInterface  
  24. {  
  25.     const STATUS_DELETED = 0;  
  26.     const STATUS_ACTIVE = 10;  
  27.     const ROLE_USER = 10;  
  28.     const AUTH_KEY = '123456';  
  29.   
  30.     /** 
  31.      * @inheritdoc 
  32.      */  
  33.     public static function tableName()  
  34.     {  
  35.         return '{{%admin}}';  
  36.     }  
  37.   
  38.     /** 
  39.      * @inheritdoc 
  40.      */  
  41.     public function behaviors()  
  42.     {  
  43.         return [  
  44.             TimestampBehavior::className(),  
  45.         ];  
  46.     }  
  47.   
  48.     /** 
  49.      * @inheritdoc 
  50.      */  
  51.     public function rules()  
  52.     {  
  53.         return [  
  54.             [['username''email',], 'required'],  
  55.             [['username''email'], 'string''max' => 255],  
  56.             [['username'], 'unique'],  
  57.             [['username'], 'match''pattern'=>'/^[a-z]\w*$/i'],  
  58.             [['email'], 'unique'],  
  59.             [['email'], 'email'],  
  60.             ['status''default''value' => self::STATUS_ACTIVE],  
  61.             ['status''in''range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],  
  62.             ['role''default''value' => self::ROLE_USER],  
  63.             ['auth_key''default''value' => self::AUTH_KEY],  
  64.             ['role''in''range' => [self::ROLE_USER]],  
  65.         ];  
  66.     }  
  67.   
  68.     /** 
  69.      * @inheritdoc 
  70.      */  
  71.     public static function findIdentity($id)  
  72.     {  
  73.         return static::findOne(['id' => $id'status' => self::STATUS_ACTIVE]);  
  74.     }  
  75.   
  76.     /** 
  77.      * @inheritdoc 
  78.      */  
  79.     public static function findIdentityByAccessToken($token$type = null)  
  80.     {  
  81.         return static::findOne(['access_token' => $token]);  
  82.         //throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');  
  83.     }  
  84.   
  85.     /** 
  86.      * Finds user by username 
  87.      * 
  88.      * @param string $username 
  89.      * @return static|null 
  90.      */  
  91.     public static function findByUsername($username)  
  92.     {  
  93.         return static::findOne(['username' => $username'status' => self::STATUS_ACTIVE]);  
  94.     }  
  95.   
  96.     /** 
  97.      * Finds user by password reset token 
  98.      * 
  99.      * @param string $token password reset token 
  100.      * @return static|null 
  101.      */  
  102.     public static function findByPasswordResetToken($token)  
  103.     {  
  104.         if (!static::isPasswordResetTokenValid($token)) {  
  105.             return null;  
  106.         }  
  107.   
  108.         return static::findOne([  
  109.             'password_reset_token' => $token,  
  110.             'status' => self::STATUS_ACTIVE,  
  111.         ]);  
  112.     }  
  113.   
  114.     /** 
  115.      * Finds out if password reset token is valid 
  116.      * 
  117.      * @param string $token password reset token 
  118.      * @return boolean 
  119.      */  
  120.     public static function isPasswordResetTokenValid($token)  
  121.     {  
  122.         if (empty($token)) {  
  123.             return false;  
  124.         }  
  125.         $expire = Yii::$app->params['user.passwordResetTokenExpire'];  
  126.         $parts = explode('_'$token);  
  127.         $timestamp = (int) end($parts);  
  128.         return $timestamp + $expire >= time();  
  129.     }  
  130.   
  131.     /** 
  132.      * @inheritdoc 
  133.      */  
  134.     public function getId()  
  135.     {  
  136.         return $this->getPrimaryKey();  
  137.     }  
  138.   
  139.     /** 
  140.      * @inheritdoc 
  141.      */  
  142.     public function getAuthKey()  
  143.     {  
  144.         return $this->auth_key;  
  145.     }  
  146.   
  147.     /** 
  148.      * @inheritdoc 
  149.      */  
  150.     public function validateAuthKey($authKey)  
  151.     {  
  152.         return $this->getAuthKey() === $authKey;  
  153.     }  
  154.   
  155.     /** 
  156.      * Validates password 
  157.      * 
  158.      * @param string $password password to validate 
  159.      * @return boolean if password provided is valid for current user 
  160.      */  
  161.     public function validatePassword($password)  
  162.     {  
  163.         return Yii::$app->security->validatePassword($password$this->password_hash);  
  164.     }  
  165.   
  166.     /** 
  167.      * Generates password hash from password and sets it to the model 
  168.      * 
  169.      * @param string $password 
  170.      */  
  171.     public function setPassword($password)  
  172.     {  
  173.         $this->password_hash = Yii::$app->security->generatePasswordHash($password);  
  174.     }  
  175.   
  176.     /** 
  177.      * Generates "remember me" authentication key 
  178.      */  
  179.     public function generateAuthKey()  
  180.     {  
  181.         $this->auth_key = Yii::$app->security->generateRandomString();  
  182.     }  
  183.   
  184.     /** 
  185.      * Generates new password reset token 
  186.      */  
  187.     public function generatePasswordResetToken()  
  188.     {  
  189.         $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();  
  190.     }  
  191.   
  192.     /** 
  193.      * Removes password reset token 
  194.      */  
  195.     public function removePasswordResetToken()  
  196.     {  
  197.         $this->password_reset_token = null;  
  198.     }  
  199. }  

三、使用migrate 为后如初使化一个登陆帐号

1、console\controllers创建InitController.php

  1. /** 
  2.  * 
  3.  * @author chan <maclechan@qq.com> 
  4.  */  
  5. namespace console\controllers;  
  6. use backend\models\Admin ;  
  7. class InitController extends \yii\console\Controller  
  8. {  
  9.     /** 
  10.      * Create init user 
  11.      */  
  12.     public function actionAdmin()  
  13.     {  
  14.         echo "创建一个新用户 ...\n";                  // 提示当前操作  
  15.         $username = $this->prompt('User Name:');        // 接收用户名  
  16.         $email = $this->prompt('Email:');               // 接收Email  
  17.         $password = $this->prompt('Password:');         // 接收密码  
  18.         $model = new AgAdmin();                            // 创建一个新用户  
  19.         $model->username = $username;                   // 完成赋值  
  20.         $model->email = $email;  
  21.         $model->password = $password;  
  22.         if (!$model->save())                            // 保存新的用户  
  23.         {  
  24.             foreach ($model->getErrors() as $error)     // 如果保存失败,说明有错误,那就输出错误信息。  
  25.             {  
  26.                 foreach ($error as $e)  
  27.                 {  
  28.                     echo "$e\n";  
  29.                 }  
  30.             }  
  31.             return 1;                                   // 命令行返回1表示有异常  
  32.         }  
  33.         return 0;                                       // 返回0表示一切OK  
  34.     }  
  35. }  

2、使用命令:

在项目根目下,右键选择User composer here(前提是安装了全局的composer),

yii init/admin


到此,打开数据表看下,己经有了数据。


四、后台登陆验证

1、backend\controllers\SiteController.php 里actionLogin方法不用变

2、把common\models\LoginForm.php复制到backend\models只要把LoginForm.php里面的方法getUser()修改一个单词即可,如下

  1. public function getUser()  
  2.     {  
  3.         if ($this->_user === false) {  
  4.             $this->_user = Admin::findByUsername($this->username);  
  5.         }  
  6.   
  7.         return $this->_user;  
  8.     }  

3、backend\config\main.php 只要修改
  1. 'user' => [  
  2.             'identityClass' => 'backend\models\Admin',  
  3.             'enableAutoLogin' => true,  
  4.         ],  

此外,在作修改时,请注意下命令空不要搞乱了。

到此,结束。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值