当前位置:首页 > PHP > Yii2 > 正文内容

【从零开始搭建Yii2后台管理系统】三、搭建数据库,实现后台系统登录

佳航网络工作室2年前 (2024-01-13)Yii2879

上一篇文章中,已实现网站的初步访问,下一步进行网站的完善和改造。


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

Snipaste_2024-01-15_15-29-27.jpg

Snipaste_2024-01-15_15-29-59.jpg


扫描二维码推送至手机访问。

版权声明:本文由佳航网络发布,如需转载请注明出处。

本文链接:https://jiahang.work/?id=14

分享给朋友:

“【从零开始搭建Yii2后台管理系统】三、搭建数据库,实现后台系统登录” 的相关文章

YII2.0 高级模板增加api [ 2.0 版本 ]

第一步进入高级模板根目录,复制backend改名为apicp backend/ api -r第二步复制api初始化模板cp -a environments/dev/frontend environments/dev/api cp ...

如何安装Yii2?

如何安装Yii2?

安装 Yii你可以通过两种方式安装 Yii:使用 Composer 或下载一个归档文件。 推荐使用前者,这样只需执行一条简单的命令就可以安装新的扩展或更新 Yii 了。标准安装完Yii之后,框架和一个项目模板两者都下载并安装好了。 一个项目模板是实现了一些基本特性的一个 可行的Y...

【从零开始搭建Yii2后台管理系统】四、引入前台UI文件,实现界面的美化

在上一篇文章中,我们已经实现了网站后台的管理员账号登录,下一步我们引入UI文件,美化界面主题。...

Yii2 中如何彻底禁用掉自带的 Yii、JQuery 和 Bootstrap 脚本 [ 2.0 版本 ]

▪ 环境基于 Yii2 高级模板▪ 前言默认情况下,Yii2 会自动加载 Yii、JQuery 和 Bootstrap 等脚本和样式,但有时项目中可能并不需要这些库,或者使用其他版本;下面介绍如何去掉这些库脚本和样式。▪ 去除 Yii.js 相关脚本编辑 frontend\asset\AppAsse...

Yii2.0 多语言设置(高级版配置方法) [ 2.0 版本 ]

Yii2.0 多语言设置(高级版配置方法) [ 2.0 版本 ]

1.设置默认语言:在main.php配置文件加上:'language'=>'zh_CN';2.多语言切换 (我这边是在site控制器里面操作的所以用的'/site/language')html代码 :<a href="&...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。