【从零开始搭建Yii2后台管理系统】三、搭建数据库,实现后台系统登录
在上一篇文章中,已实现网站的初步访问,下一步进行网站的完善和改造。
1.创建数据库
CREATE DATABASE IF NOT EXISTS `moonadmin` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; USE `moonadmin`; -- -- 创建管理员用户表 `administrator` -- CREATE TABLE `administrator` ( `id` int(11) NOT NULL COMMENT '编号', `username` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户名', `realname` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '姓名', `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '电子邮箱', `avatar` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '头像', `status` int(11) NOT NULL DEFAULT '10' COMMENT '状态', `role` smallint(6) NOT NULL DEFAULT '10' COMMENT '角色等级', `password_hash` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '密码', `auth_key` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '授权key', `password_reset_token` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '密码重置token', `access_token` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '访问token', `expire_at` int(11) DEFAULT NULL COMMENT '过期时间', `logged_at` int(11) DEFAULT NULL COMMENT '最后登陆时间', `last_ip` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '最后登陆IP', `created_at` int(11) DEFAULT NULL COMMENT '创建时间', `updated_at` int(11) DEFAULT NULL COMMENT '最后修改时间' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- 插入数据记录 `administrator` -- INSERT INTO `administrator` (`id`, `username`, `realname`, `email`, `avatar`, `status`, `role`, `password_hash`, `auth_key`, `password_reset_token`, `access_token`, `expire_at`, `logged_at`, `last_ip`, `created_at`, `updated_at`) VALUES (1, 'admin', '管理员', '3289925508@qq.com', '1', 10, 10, '$2y$13$nQxbIXwitRsIns32bUkZre2dIRgmPd/aKap45RHpQuxiEtp5hrdwS', 'pG7TRyTIXlEbcenpi34TzmMYS2zDsMTF', NULL, NULL, 1506008463, 1701951866, '127.0.0.1', 1505998873, 1701951866);
common/config/main-local.php
'db' => [ 'class' => \yii\db\Connection::class, //修改数据库、用户名、密码 'dsn' => 'mysql:host=localhost;dbname=moonadmin', 'username' => 'root', 'password' => '123456', 'charset' => 'utf8mb4', ],
2.修改MVC文件
common/models/Administrator
<?php namespace common\models; use common\enums\StatusEnum; use Yii; /** * This is the model class for table "administrator". * * @property int $id 编号 * @property string|null $username 用户名 * @property string|null $realname 姓名 * @property string $email 电子邮箱 * @property string|null $avatar 头像 * @property int $status 状态 * @property int $role 角色等级 * @property string $password_hash 密码 * @property string $auth_key 授权key * @property string|null $password_reset_token 密码重置token * @property string|null $access_token 访问token * @property int|null $expire_at 过期时间 * @property int|null $logged_at 最后登陆时间 * @property string|null $last_ip 最后登陆IP * @property int|null $created_at 创建时间 * @property int|null $updated_at 最后修改时间 */ class Administrator extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface { /** * {@inheritdoc} */ public static function tableName() { return 'administrator'; } /** * {@inheritdoc} */ public function rules() { return [ [['email', 'password_hash', 'auth_key','realname'], 'required'], [['status', 'role', 'expire_at', 'logged_at', 'created_at', 'updated_at'], 'integer'], [['username'], 'string', 'max' => 32], [['realname', 'email', 'password_hash', 'auth_key', 'password_reset_token', 'access_token'], 'string', 'max' => 191], [['avatar'], 'string', 'max' => 100], [['last_ip'], 'string', 'max' => 20], [['email'], 'unique'], [['username'], 'unique'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => '编号', 'username' => '用户名', 'realname' => '姓名', 'email' => '电子邮箱', 'avatar' => '头像', 'status' => '状态', 'role' => '角色等级', 'password_hash' => '密码', 'auth_key' => '授权key', 'password_reset_token' => '密码重置token', 'access_token' => '访问token', 'expire_at' => '过期时间', 'logged_at' => '最后登陆时间', 'last_ip' => '最后登陆IP', 'created_at' => '创建时间', 'updated_at' => '最后修改时间', ]; } public function beforeSave($insert) { if(parent::beforeSave($insert)) { if($insert) { $this->created_at = time(); $this->updated_at = time(); } else { $this->updated_at = time(); } return true; } else { return false; } } /** * 以下从user模型中拷贝过来修改 */ /** * @inheritdoc */ public static function findIdentity($id) { return static::findOne(['id' => $id]); } /** * @inheritdoc */ public static function findIdentityByAccessToken($token, $type = null) { //if ($type == '') //throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.'); //return static::findOne(['access_token'=>$token , 'status' => self::STATUS_ACTIVE],>; return static::find() ->where(['access_token'=>$token , 'status' => StatusEnum::ENABLED]) ->andWhere(['>','expire_at',time()]) ->one(); } /** * Finds user by username * * @param string $username * @return static|null */ public static function findByUsername($username) { return static::findOne(['username' => $username, 'status' => StatusEnum::ENABLED]); } /** * Finds user by password reset token * * @param string $token password reset token * @return static|null */ public static function findByPasswordResetToken($token) { if (!static::isPasswordResetTokenValid($token)) { return null; } return static::findOne([ 'password_reset_token' => $token, ]); } /** * Finds out if password reset token is valid * * @param string $token password reset token * @return boolean */ public static function isPasswordResetTokenValid($token) { if (empty($token)) { return false; } $timestamp = (int) substr($token, strrpos($token, '_') + 1); $expire = Yii::$app->params['user.passwordResetTokenExpire']; return $timestamp + $expire >= time(); } /** * @inheritdoc */ public function getId() { return $this->getPrimaryKey(); } /** * @inheritdoc */ public function getAuthKey() { return $this->auth_key; } /** * @inheritdoc */ public function validateAuthKey($authKey) { return $this->getAuthKey() === $authKey; } /** * Validates password * * @param string $password password to validate * @return boolean if password provided is valid for current user */ public function validatePassword($password) { return Yii::$app->security->validatePassword($password, $this->password_hash); } /** * Generates password hash from password and sets it to the model * * @param string $password */ public function setPassword($password) { $this->password_hash = Yii::$app->security->generatePasswordHash($password); } /** * Generates "remember me" authentication key */ public function generateAuthKey() { $this->auth_key = Yii::$app->security->generateRandomString(); } /** * Generates new password reset token */ public function generatePasswordResetToken() { $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time(); } /** * Removes password reset token */ public function removePasswordResetToken() { $this->password_reset_token = null; } public function generateAccessToken() { $this->access_token = Yii::$app->security->generateRandomString(); return $this->access_token; } }
common/enums/StatusEnum
<?php namespace common\enums; /** * 状态枚举 * * Class StatusEnum * @package common\enums */ class StatusEnum { const ENABLED = 10; const DISABLED = 0; const DELETED = -1; /** * @var array */ public static $statusString = [ self::ENABLED => '正常', self::DISABLED => '禁用', self::DELETED => '删除', ]; }
common/models/AdminLoginForm
<?php namespace common\models; use Yii; use yii\base\Model; /** * Login form */ class AdminLoginForm extends Model { public $username; public $password; public $rememberMe = true; private $_user; /** * @inheritdoc */ public function rules() { return [ // username and password are both required [['username', 'password'], 'required'], // rememberMe must be a boolean value ['rememberMe', 'boolean'], // password is validated by validatePassword() ['password', 'validatePassword'], ]; } public function attributeLabels() { return [ 'username'=>'用户名', 'password'=>'密码', 'rememberMe'=>'记住密码', ]; } /** * Validates the password. * This method serves as the inline validation for password. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, '用户名或密码错误.'); } } } /** * Logs in a user using the provided username and password. * * @return boolean whether the user is logged in successfully */ public function login() { if ($this->validate()) { return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0); } else { return false; } } /** * Finds user by [[username]] * * @return User|null */ protected function getUser() { if ($this->_user === null) { $this->_user = Administrator::findByUsername($this->username); } return $this->_user; } }
backend/controllers/SiteController
添加引用
use common\models\AdminLoginForm;
修改actionLogin()方法
/** * Login action. * * @return string|Response */ public function actionLogin() { if (!Yii::$app->user->isGuest) { return $this->goHome(); } $this->layout = 'blank'; $model = new AdminLoginForm(); if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->goBack(); } $model->password = ''; return $this->render('login', [ 'model' => $model, ]); }
3.更改配置文件
backend/config/main.php
'user' => [ 'identityClass' => 'common\models\Administrator', 'enableAutoLogin' => true, 'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true], ],
4.实现登录
管理员用户名admin 密码12345678