Просмотр исходного кода

为 AdminController 添加表单验证

shizhongqi 1 год назад
Родитель
Сommit
e3e90b758c

+ 87 - 77
app-ghs/controllers/AdminController.php

@@ -8,16 +8,22 @@ use bizHd\wx\classes\WxOpenClass;
 use bizGhs\admin\classes\AdminClass;
 use bizGhs\admin\services\AdminService;
 use common\components\dict;
-use common\components\noticeUtil;
-use common\components\stringUtil;
 use common\components\util;
+use ghs\models\Admin\AddForm;
+use ghs\models\Admin\BindAutoLoginForm;
+use ghs\models\Admin\ConfirmPasswordForm;
+use ghs\models\Admin\MiniFullInfoForm;
+use ghs\models\Admin\MiniMobileForm;
+use ghs\models\Admin\ModifyPasswordForm;
+use ghs\models\Admin\PasswordForm;
+use ghs\models\Admin\ReplaceClientIdForm;
+use ghs\models\Admin\UpdateAdminForm;
 use Yii;
 use yii\helpers\Json;
 use bizHd\user\classes\UserClass;
 
 class AdminController extends BaseController
 {
-
     public $guestAccess = ['recent-shop', 'mini-full-info', 'mini-mobile', 'login-detail'];
 
     //清空登录信息 ssh 20240428
@@ -40,18 +46,23 @@ class AdminController extends BaseController
     //修改个人信息 ssh 20230505
     public function actionUpdateAdmin()
     {
-        $post = Yii::$app->request->post();
-        $ghsOpenId = $post['ghsOpenId'] ?? '';
-        $name = $post['name'] ?? '';
+        $model = new UpdateAdminForm();
+        $model->load(Yii::$app->request->post(), '');
+        
+        if (!$model->validateForm()) {
+            return;
+        }
+        
         $admin = $this->admin;
-        $admin->ghsOpenId = $ghsOpenId;
-        if (!empty($name)) {
-            $admin->name = $name;
+        $admin->ghsOpenId = $model->ghsOpenId;
+        if (!empty($model->name)) {
+            $admin->name = $model->name;
         }
         $admin->save();
-        if (!empty($name)) {
+        
+        if (!empty($model->name)) {
             $adminId = $this->adminId;
-            ShopAdminClass::updateByCondition(['adminId' => $adminId], ['name' => $name]);
+            ShopAdminClass::updateByCondition(['adminId' => $adminId], ['name' => $model->name]);
         }
         util::complete();
     }
@@ -59,21 +70,23 @@ class AdminController extends BaseController
     //绑定帐号自动登录 ssh 20210121
     public function actionBindAutoLogin()
     {
-        $post = Yii::$app->request->post();
-        $iv = isset($post['iv']) ? $post['iv'] : '';
-        $encryptedData = isset($post['encryptedData']) ? $post['encryptedData'] : '';
+        $model = new BindAutoLoginForm();
+        $model->load(Yii::$app->request->post(), '');
+        
+        if (!$model->validateForm()) {
+            return;
+        }
+        
         $merchant = WxOpenClass::getGhsWxInfo();
         $appId = $merchant['miniAppId'];
-        $miniOpenId = $post['miniOpenId'];
-        if (empty($miniOpenId)) {
-            util::fail('绑定失败');
-        }
+        $miniOpenId = $model->miniOpenId;
+        
         $cacheKey = 'GHS_SHOP_MINI_SESSION_KEY_' . $miniOpenId;
         $sessionKey = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
         $wxMiniSecret = Yii::getAlias("@vendor/weixinMiniSecret");
         require_once($wxMiniSecret . '/wxBizDataCrypt.php');
         $pc = new \WXBizDataCrypt($appId, $sessionKey);
-        $errCode = $pc->decryptData($encryptedData, $iv, $result);
+        $errCode = $pc->decryptData($model->encryptedData, $model->iv, $result);
         if ($errCode != 0) {
             Yii::info($result . ' ' . $errCode);
             util::fail('绑定失败了');
@@ -96,12 +109,15 @@ class AdminController extends BaseController
     //修改保存安卓clientId
     public function actionReplaceClientId()
     {
-        $get = Yii::$app->request->get();
-        $id = $get['id'] ?? '';
-        if (empty($id)) {
+        $model = new ReplaceClientIdForm();
+        $model->load(Yii::$app->request->get(), '');
+        
+        if (!$model->validateForm()) {
             util::success(['returnStatus' => 'FAILURE']);
+            return;
         }
-        $this->admin->clientId = $id;
+        
+        $this->admin->clientId = $model->id;
         $this->admin->save();
         //noticeUtil::push("保存客户端ID:" . $id, '15280215347');
         util::complete();
@@ -110,14 +126,15 @@ class AdminController extends BaseController
     //修改密码 ssh 20220106
     public function actionModifyPassword()
     {
-        $get = Yii::$app->request->get();
-        $password = $get['password'] ?? '';
-        if (empty($password)) {
-            util::fail('请填写密码');
+        $model = new ModifyPasswordForm();
+        $model->load(Yii::$app->request->get(), '');
+        
+        if (!$model->validateForm()) {
+            return;
         }
-        stringUtil::passwordCheck($password);
+        
         $adminId = $this->adminId;
-        $password = password_hash($password, PASSWORD_BCRYPT);
+        $password = password_hash($model->password, PASSWORD_BCRYPT);
         AdminClass::updateById($adminId, ['password' => $password]);
         util::complete('操作成功');
     }
@@ -140,8 +157,15 @@ class AdminController extends BaseController
     //添加员工 ssh 2019.12.8
     public function actionAdd()
     {
-        $post = Yii::$app->request->post();
-        $post['sjId'] = $this->sjId;
+        $model = new AddForm();
+        $model->load(Yii::$app->request->post(), '');
+        $model->sjId = $this->sjId;
+        
+        if (!$model->validateForm()) {
+            return;
+        }
+        
+        $post = $model->attributes;
         $admin = AdminService::addAdmin($post);
         $id = $admin['id'];
         $info = AdminService::getDetail($id);
@@ -171,54 +195,32 @@ class AdminController extends BaseController
     //密码修改
     public function actionPassword()
     {
-        $post = Yii::$app->request->post();
-        $old = isset($post['old']) ? $post['old'] : '';
-        $new = isset($post['new']) ? $post['new'] : '';
-        $confirm = isset($post['confirm']) ? $post['confirm'] : '';
-        if (empty($new)) {
-            util::fail('请输入新密码');
-        }
-        if ($new != $confirm) {
-            util::fail('二次密码不一致');
+        $model = new PasswordForm();
+        $model->load(Yii::$app->request->post(), '');
+        $model->setAdmin($this->admin);
+        
+        if (!$model->validateForm()) {
+            return;
         }
-        $admin = $this->admin->attributes;
+        
         $adminId = $this->adminId;
-        if (!empty($admin['password'])) {
-            if (empty($old)) {
-                util::fail('请填写旧密码');
-            }
-            if (password_verify($old, $admin['password']) == false) {
-                util::fail('旧密码错误');
-            }
-        }
-        AdminService::updateById($adminId, ['password' => password_hash($new, PASSWORD_BCRYPT)]);
+        AdminService::updateById($adminId, ['password' => password_hash($model->new, PASSWORD_BCRYPT)]);
         util::complete('修改成功');
     }
 
     //支付密码修改
     public function actionConfirmPassword()
     {
-        $post = Yii::$app->request->post();
-        $old = isset($post['old']) ? $post['old'] : '';
-        $new = isset($post['new']) ? $post['new'] : '';
-        $confirm = isset($post['confirm']) ? $post['confirm'] : '';
-        if (empty($new)) {
-            util::fail('请输入新密码');
-        }
-        if ($new != $confirm) {
-            util::fail('二次密码不一致');
+        $model = new ConfirmPasswordForm();
+        $model->load(Yii::$app->request->post(), '');
+        $model->setAdmin($this->admin);
+        
+        if (!$model->validateForm()) {
+            return;
         }
-        $admin = $this->admin->attributes;
+        
         $adminId = $this->adminId;
-        if (!empty($admin['payPassword'])) {
-            if (empty($old)) {
-                util::fail('请填写旧密码');
-            }
-            if (password_verify($old, $admin['payPassword']) == false) {
-                util::fail('旧密码错误');
-            }
-        }
-        AdminService::updateById($adminId, ['payPassword' => password_hash($new, PASSWORD_BCRYPT)]);
+        AdminService::updateById($adminId, ['payPassword' => password_hash($model->new, PASSWORD_BCRYPT)]);
         util::complete('修改成功');
     }
 
@@ -232,9 +234,13 @@ class AdminController extends BaseController
     //小程序用户完整信息 ssh 2019.12.12
     public function actionMiniFullInfo()
     {
-        $post = Yii::$app->request->post();
-        $iv = isset($post['iv']) ? $post['iv'] : '';
-        $encryptedData = isset($post['encryptedData']) ? $post['encryptedData'] : '';
+        $model = new MiniFullInfoForm();
+        $model->load(Yii::$app->request->post(), '');
+        
+        if (!$model->validateForm()) {
+            return;
+        }
+        
         $merchant = WxOpenClass::getGhsWxInfo();
         $appId = $merchant['miniAppId'];
         $admin = $this->admin;
@@ -252,7 +258,7 @@ class AdminController extends BaseController
         $wxMiniSecret = Yii::getAlias("@vendor/weixinMiniSecret");
         require_once($wxMiniSecret . '/wxBizDataCrypt.php');
         $pc = new \WXBizDataCrypt($appId, $sessionKey);
-        $errCode = $pc->decryptData($encryptedData, $iv, $result);
+        $errCode = $pc->decryptData($model->encryptedData, $model->iv, $result);
         if ($errCode != 0) {
             Yii::info($result . ' ' . $errCode);
             util::fail('获取用户信息失败');
@@ -272,9 +278,13 @@ class AdminController extends BaseController
     //小程序用户手机号
     public function actionMiniMobile()
     {
-        $post = Yii::$app->request->post();
-        $iv = $post['iv'];
-        $encryptedData = $post['encryptedData'];
+        $model = new MiniMobileForm();
+        $model->load(Yii::$app->request->post(), '');
+        
+        if (!$model->validateForm()) {
+            return;
+        }
+        
         $merchant = WxOpenClass::getGhsWxInfo();
         $appId = $merchant['miniAppId'];
         $admin = $this->admin->attributes;
@@ -291,7 +301,7 @@ class AdminController extends BaseController
         require_once($wxMiniSecret . '/wxBizDataCrypt.php');
 
         $pc = new \WXBizDataCrypt($appId, $sessionKey);
-        $errCode = $pc->decryptData($encryptedData, $iv, $result);
+        $errCode = $pc->decryptData($model->encryptedData, $model->iv, $result);
         if ($errCode != 0) {
             util::fail('解密失败');
         }

+ 85 - 0
app-ghs/models/Admin/AddForm.php

@@ -0,0 +1,85 @@
+<?php
+
+namespace ghs\models\Admin;
+
+/**
+ * 添加员工表单模型
+ */
+class AddForm extends BaseForm
+{
+    /**
+     * @var string 用户名
+     */
+    public $username;
+    
+    /**
+     * @var string 密码
+     */
+    public $password;
+    
+    /**
+     * @var string 姓名
+     */
+    public $name;
+    
+    /**
+     * @var string 手机号
+     */
+    public $mobile;
+    
+    /**
+     * @var int 角色ID
+     */
+    public $roleId;
+    
+    /**
+     * @var int 商家ID
+     */
+    public $sjId;
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['username', 'password', 'name', 'mobile', 'roleId'], 'required', 'message' => '{attribute}不能为空'],
+            [['username', 'name'], 'string', 'max' => 50],
+            [['password'], 'string', 'min' => 6, 'max' => 20],
+            [['mobile'], 'match', 'pattern' => '/^1[3-9]\d{9}$/', 'message' => '手机号格式不正确'],
+            [['roleId', 'sjId'], 'integer'],
+            [['username'], 'validateUsername'],
+        ];
+    }
+
+    /**
+     * 验证用户名是否已存在
+     * 
+     * @param string $attribute 属性名
+     * @param array $params 参数
+     */
+    public function validateUsername($attribute, $params)
+    {
+        if (!$this->hasErrors()) {
+            $exists = \bizGhs\admin\classes\AdminClass::getByCondition(['username' => $this->$attribute]);
+            if ($exists) {
+                $this->addError($attribute, '用户名已存在');
+            }
+        }
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'username' => '用户名',
+            'password' => '密码',
+            'name' => '姓名',
+            'mobile' => '手机号',
+            'roleId' => '角色',
+            'sjId' => '商家ID',
+        ];
+    }
+} 

+ 28 - 0
app-ghs/models/Admin/BaseForm.php

@@ -0,0 +1,28 @@
+<?php
+
+namespace ghs\models\Admin;
+
+use yii\base\Model;
+use common\components\util;
+
+/**
+ * 管理员表单基类
+ */
+class BaseForm extends Model
+{
+    /**
+     * 验证表单数据并返回结果
+     * 
+     * @return bool 验证是否通过
+     */
+    public function validateForm()
+    {
+        if (!$this->validate()) {
+            $errors = $this->getFirstErrors();
+            $message = reset($errors);
+            util::fail($message);
+            return false;
+        }
+        return true;
+    }
+} 

+ 61 - 0
app-ghs/models/Admin/BindAutoLoginForm.php

@@ -0,0 +1,61 @@
+<?php
+
+namespace ghs\models\Admin;
+
+/**
+ * 绑定帐号自动登录表单模型
+ */
+class BindAutoLoginForm extends BaseForm
+{
+    /**
+     * @var string 加密数据
+     */
+    public $encryptedData;
+    
+    /**
+     * @var string 加密向量
+     */
+    public $iv;
+    
+    /**
+     * @var string 小程序OpenID
+     */
+    public $miniOpenId;
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['encryptedData', 'iv', 'miniOpenId'], 'required'],
+            [['encryptedData', 'iv', 'miniOpenId'], 'string'],
+            [['miniOpenId'], 'validateMiniOpenId'],
+        ];
+    }
+
+    /**
+     * 验证小程序OpenID
+     * 
+     * @param string $attribute 属性名
+     * @param array $params 参数
+     */
+    public function validateMiniOpenId($attribute, $params)
+    {
+        if (!$this->hasErrors() && empty($this->$attribute)) {
+            $this->addError($attribute, '绑定失败');
+        }
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'encryptedData' => '加密数据',
+            'iv' => '加密向量',
+            'miniOpenId' => '小程序OpenID',
+        ];
+    }
+} 

+ 82 - 0
app-ghs/models/Admin/ConfirmPasswordForm.php

@@ -0,0 +1,82 @@
+<?php
+
+namespace ghs\models\Admin;
+
+/**
+ * 支付密码修改表单模型
+ */
+class ConfirmPasswordForm extends BaseForm
+{
+    /**
+     * @var string 旧密码
+     */
+    public $old;
+    
+    /**
+     * @var string 新密码
+     */
+    public $new;
+    
+    /**
+     * @var string 确认密码
+     */
+    public $confirm;
+    
+    /**
+     * @var \bizGhs\admin\models\Admin 当前管理员模型
+     */
+    private $_admin;
+
+    /**
+     * 设置管理员模型
+     * 
+     * @param \bizGhs\admin\models\Admin $admin 管理员模型
+     */
+    public function setAdmin($admin)
+    {
+        $this->_admin = $admin;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['new', 'confirm'], 'required', 'message' => '请输入{attribute}'],
+            [['old'], 'required', 'message' => '请填写旧密码', 'when' => function($model) {
+                return !empty($this->_admin->payPassword);
+            }],
+            [['old'], 'validateOldPassword'],
+            [['new'], 'string', 'min' => 6, 'max' => 20],
+            [['confirm'], 'compare', 'compareAttribute' => 'new', 'message' => '二次密码不一致'],
+        ];
+    }
+
+    /**
+     * 验证旧密码
+     * 
+     * @param string $attribute 属性名
+     * @param array $params 参数
+     */
+    public function validateOldPassword($attribute, $params)
+    {
+        if (!$this->hasErrors() && !empty($this->_admin->payPassword)) {
+            if (!password_verify($this->$attribute, $this->_admin->payPassword)) {
+                $this->addError($attribute, '旧密码错误');
+            }
+        }
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'old' => '旧密码',
+            'new' => '新密码',
+            'confirm' => '确认密码',
+        ];
+    }
+} 

+ 41 - 0
app-ghs/models/Admin/MiniFullInfoForm.php

@@ -0,0 +1,41 @@
+<?php
+
+namespace ghs\models\Admin;
+
+/**
+ * 小程序用户完整信息表单模型
+ */
+class MiniFullInfoForm extends BaseForm
+{
+    /**
+     * @var string 加密数据
+     */
+    public $encryptedData;
+    
+    /**
+     * @var string 加密向量
+     */
+    public $iv;
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['encryptedData', 'iv'], 'required'],
+            [['encryptedData', 'iv'], 'string'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'encryptedData' => '加密数据',
+            'iv' => '加密向量',
+        ];
+    }
+} 

+ 41 - 0
app-ghs/models/Admin/MiniMobileForm.php

@@ -0,0 +1,41 @@
+<?php
+
+namespace ghs\models\Admin;
+
+/**
+ * 小程序用户手机号表单模型
+ */
+class MiniMobileForm extends BaseForm
+{
+    /**
+     * @var string 加密数据
+     */
+    public $encryptedData;
+    
+    /**
+     * @var string 加密向量
+     */
+    public $iv;
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['encryptedData', 'iv'], 'required'],
+            [['encryptedData', 'iv'], 'string'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'encryptedData' => '加密数据',
+            'iv' => '加密向量',
+        ];
+    }
+} 

+ 55 - 0
app-ghs/models/Admin/ModifyPasswordForm.php

@@ -0,0 +1,55 @@
+<?php
+
+namespace ghs\models\Admin;
+
+use common\components\stringUtil;
+
+/**
+ * 修改密码表单模型
+ */
+class ModifyPasswordForm extends BaseForm
+{
+    /**
+     * @var string 密码
+     */
+    public $password;
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['password'], 'required', 'message' => '请填写密码'],
+            [['password'], 'string', 'min' => 6, 'max' => 20],
+            [['password'], 'validatePassword'],
+        ];
+    }
+
+    /**
+     * 自定义密码验证规则
+     * 
+     * @param string $attribute 属性名
+     * @param array $params 参数
+     */
+    public function validatePassword($attribute, $params)
+    {
+        if (!$this->hasErrors()) {
+            try {
+                stringUtil::passwordCheck($this->$attribute);
+            } catch (\Exception $e) {
+                $this->addError($attribute, $e->getMessage());
+            }
+        }
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'password' => '密码',
+        ];
+    }
+} 

+ 82 - 0
app-ghs/models/Admin/PasswordForm.php

@@ -0,0 +1,82 @@
+<?php
+
+namespace ghs\models\Admin;
+
+/**
+ * 密码修改表单模型
+ */
+class PasswordForm extends BaseForm
+{
+    /**
+     * @var string 旧密码
+     */
+    public $old;
+    
+    /**
+     * @var string 新密码
+     */
+    public $new;
+    
+    /**
+     * @var string 确认密码
+     */
+    public $confirm;
+    
+    /**
+     * @var \bizGhs\admin\models\Admin 当前管理员模型
+     */
+    private $_admin;
+
+    /**
+     * 设置管理员模型
+     * 
+     * @param \bizGhs\admin\models\Admin $admin 管理员模型
+     */
+    public function setAdmin($admin)
+    {
+        $this->_admin = $admin;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['new', 'confirm'], 'required', 'message' => '请输入{attribute}'],
+            [['old'], 'required', 'message' => '请填写旧密码', 'when' => function($model) {
+                return !empty($this->_admin->password);
+            }],
+            [['old'], 'validateOldPassword'],
+            [['new'], 'string', 'min' => 6, 'max' => 20],
+            [['confirm'], 'compare', 'compareAttribute' => 'new', 'message' => '二次密码不一致'],
+        ];
+    }
+
+    /**
+     * 验证旧密码
+     * 
+     * @param string $attribute 属性名
+     * @param array $params 参数
+     */
+    public function validateOldPassword($attribute, $params)
+    {
+        if (!$this->hasErrors() && !empty($this->_admin->password)) {
+            if (!password_verify($this->$attribute, $this->_admin->password)) {
+                $this->addError($attribute, '旧密码错误');
+            }
+        }
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'old' => '旧密码',
+            'new' => '新密码',
+            'confirm' => '确认密码',
+        ];
+    }
+} 

+ 35 - 0
app-ghs/models/Admin/ReplaceClientIdForm.php

@@ -0,0 +1,35 @@
+<?php
+
+namespace ghs\models\Admin;
+
+/**
+ * 修改保存安卓clientId表单模型
+ */
+class ReplaceClientIdForm extends BaseForm
+{
+    /**
+     * @var string 客户端ID
+     */
+    public $id;
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['id'], 'required', 'message' => '客户端ID不能为空'],
+            [['id'], 'string'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'id' => '客户端ID',
+        ];
+    }
+} 

+ 42 - 0
app-ghs/models/Admin/UpdateAdminForm.php

@@ -0,0 +1,42 @@
+<?php
+
+namespace ghs\models\Admin;
+
+/**
+ * 更新管理员信息表单模型
+ */
+class UpdateAdminForm extends BaseForm
+{
+    /**
+     * @var string 微信小程序OpenID
+     */
+    public $ghsOpenId;
+    
+    /**
+     * @var string 管理员姓名
+     */
+    public $name;
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['ghsOpenId'], 'string', 'max' => 64],
+            [['name'], 'string', 'max' => 50],
+            [['name'], 'trim'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'ghsOpenId' => '微信小程序OpenID',
+            'name' => '管理员姓名',
+        ];
+    }
+} 

+ 1 - 1
composer.json

@@ -14,7 +14,7 @@
     },
     "minimum-stability": "dev",
     "require": {
-        "php": ">=5.4.0",
+        "php": ">=7.0",
         "yiisoft/yii2": "2.0.29",
         "yiisoft/yii2-bootstrap": "~2.0.6",
         "yiisoft/yii2-swiftmailer": "~2.0.6",