| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362 |
- <?php
- namespace common\models\backend;
- use backend\models\AdminRole;
- use common\enums\StatusEnum;
- use common\helpers\Auth;
- use common\models\base\BaseActiveRecord;
- use common\models\base\User;
- use common\models\mall\Mall;
- use common\models\rbac\AuthAssignment;
- use Exception;
- use Yii;
- use yii\web\IdentityInterface;
- use yii\base\Model;
- /**
- * This is the model class for table "{{%admin}}".
- *
- * @property int $id ID
- * @property string $account 用户名
- * @property string $username 用户名
- * @property string $password 密码
- * @property string $auth_key
- * @property int $mall_id
- * @property int $mch_id
- * @property int $store_id
- * @property string $access_token
- * @property int $admin_type 管理员类型1超级管理员2管理员3操作员
- * @property int $mall_num
- * @property int $remark
- * @property int $is_default 是否删除
- * @property int $expired_at 过期时间
- * @property int $created_at 创建时间
- * @property int $updated_at 更新时间
- * @property int $status 状态
- * @property int $source 来源类型:0:默认;1:注册
- * @property int $view_times 商城浏览时长
- * @property int $addons_view_times 应用浏览时长
- * @property int $reference_id 推荐人id
- *
- */
- class Admin extends User
- {
- const ADMIN_TYPE_SUPER = 1; // 超级管理员
- const ADMIN_TYPE_AGENT = 2; // 管理员(代理商新增商城等操作)
- const ADMIN_TYPE_OPERATE = 3; // 操作员(登录至商城)
- /**
- * {@inheritdoc}
- */
- public static function tableName()
- {
- return '{{%admin}}';
- }
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- [['username', 'account','password', 'admin_type'], 'required'],
- [['admin_type','mall_id','mch_id', 'is_default', 'mall_num', 'expired_at', 'created_at','status', 'updated_at','store_id','source','view_times','addons_view_times','reference_id','mobile'], 'integer'],
- [['password', 'auth_key','access_token','account','remark'], 'string'],
- [['username'], 'string', 'max' => 50],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'username' => '用户名',
- 'password' => '密码',
- 'mall_id' => '商城id',
- 'mch_id' => '商户id',
- 'store_id' => '门店id',
- 'auth_key' => '',
- 'access_token' => '',
- 'admin_type' => '管理员类型',
- 'mall_num' => '商城数量',
- 'is_default' => '是否默认',
- 'expired_at' => '过期时间',
- 'created_at' => '创建时间',
- 'updated_at' => '更新时间',
- 'status' => '更新时间',
- 'source' => '来源类型:0:默认;1:注册',
- 'view_times' => '商城浏览时长',
- 'addons_view_times' => '应用浏览时长',
- 'reference_id' => '推荐人id',
- 'mobile' => '手机号',
- ];
- }
- /**YII登录机制实现接口 */
- public static function findIdentity($id)
- {
- return static::findOne($id);
- }
- public static function findIdentityByAccessToken($token, $type = null)
- {
- return static::findOne(['access_token' => $token]);
- }
- public function getId()
- {
- return $this->id;
- }
- public function getAuthKey()
- {
- return $this->auth_key;
- }
- public function validateAuthKey($authKey)
- {
- return $this->getAuthKey() === $authKey;
- }
- public function validatePassword($password)
- {
- return Yii::$app->security->validatePassword($password, $this->password);
- }
- /**YII登录机制实现接口 */
- /**
- * 关联授权角色
- *
- * @return \yii\db\ActiveQuery
- */
- public function getAssignment()
- {
- return $this->hasOne(AuthAssignment::class, ['user_id' => 'id'])
- ->where(['app_id' => Yii::$app->id]);
- }
- public function getMall()
- {
- return $this->hasMany(Mall::class, ['admin_id' => 'id']);
- }
- /**
- * 管理员登录
- * @Author bing
- * @DateTime 2021-08-12 19:12:55
- * @return void
- * @copyright: Copyright (c) 2020 广东七件事集团
- */
- public static function login($params)
- {
- try {
- $username = $params['username'] ?? '';
- $password = $params['password'] ?? '';
- $where = ['status' => StatusEnum::ENABLED, 'username' => $username];
- if (!empty($params['new_mall_id'])) {
- $where['mall_id'] = $params['new_mall_id'];
- }
- $admin = Admin::findOne($where);
- if($admin['expired_at']>0&&$admin['expired_at']<=time()) throw new Exception('您的账号已过期');
- if(empty($admin)) throw new Exception('登录账号不存在');
- $admin_type = $admin->admin_type;
- $mall_id = $admin['mall_id'] ?? 0;
- if(
- in_array($admin_type,[self::ADMIN_TYPE_SUPER,self::ADMIN_TYPE_AGENT]) && $params['login_type']!=Yii::$app->params['login_type'] ||
- in_array($admin_type,[self::ADMIN_TYPE_OPERATE]) && $params['login_type']==Yii::$app->params['login_type']
- ) {
- throw new Exception('登录网址错误');
- }
- // 密码校验
- if (!$admin || !$admin->validatePassword($password)) throw new Exception('登录账号或密码错误');
- // 管理员类型处理
- switch ($admin_type) {
- case self::ADMIN_TYPE_SUPER:
- $redirect_url = 'admin/mall/wraparound';
- break;
- case self::ADMIN_TYPE_AGENT:
- $redirect_url = 'admin/mall/wraparound';
- if ($admin->expired_at !== 0 && time() > $admin->expired_at) throw new \Exception('账户已过期!请联系管理员');
- break;
- case self::ADMIN_TYPE_OPERATE:
- $redirect_url = 'mall/overview/index';
- //$mall = Mall::findOne($mall_id);
- $mall = Mall::getOne([['id' => $mall_id]],true);
- Yii::$app->session->set('mall', $mall);
- if (empty($mall)) throw new \Exception('未找到商城');
- if ($mall['expired_at'] != 0 && $mall['expired_at'] < time()) {
- $phone = Yii::$app->services->setting->platform->get('system.contact_tel');
- $msg = sprintf('商城已过期,请联系客服进行续费(或联系客服电话:%s)', $phone);
- throw new \Exception($msg);
- }
- break;
- default:
- throw new \Exception('未知账号类型');
- }
- // 执行登录
- $config_params = Yii::$app->params;
- $mall_login_remember_time = $config_params['mall_login_remember_time'] ?? 86400 * 30;
- $mall_login_no_remember_time = $config_params['mall_login_no_remember_time'] ?? 3600 * 8;
- if (Yii::$app->user->login($admin, $params['is_remember'] == 'true' ? $mall_login_remember_time : $mall_login_no_remember_time)) {
- if($admin_type == self::ADMIN_TYPE_OPERATE){
- $auths = Auth::getAuth();
- if($auths && !in_array($redirect_url,$auths)){
- $auths = array_values(array_filter($auths));
- $cond = [['pid' => 0], ['<>','status',StatusEnum::DELETE]];
- $cond[] = ['is_addon' => 0, 'cate_id' => 2];
- $menus = Menu::getMenus($cond, [], true,'id, url');
- $menusMap = array_column($menus,'id', 'url');
- $menus = array_column($menus,'url');
- $intersect = array_intersect($auths,$menus);
- $intersect = array_values($intersect);
- $redirect_url = $intersect ? $intersect[0] : $redirect_url;
- // 兼容例如 mall/diy的url
- if ($intersect && isset($menusMap[$intersect[0]]) && count(explode('/', $redirect_url)) < 3) {
- $childMenus = Menu::getMenus([
- ['pid' => $menusMap[$intersect[0]]],
- ['<>','status',StatusEnum::DELETE],
- ['is_addon' => 0, 'cate_id' => 2]
- ], [], true,'url');
- $childMenus = array_column($childMenus,'url');
- $intersect = array_values(array_intersect($auths, $childMenus));
- $intersect && $redirect_url = $intersect[0];
- }
- }
- }
- return compact('redirect_url');
- } else {
- throw new \Exception('登录失败');
- }
- } catch (Exception $e) {
- self::setStaticError($e->getMessage());
- return false;
- }
- }
- /**
- * 添加管理员
- * @param array $params
- * @return bool|Admin
- */
- public static function setData(array $params)
- {
- $tr = \Yii::$app->db->beginTransaction();
- try {
- if (!empty($params['id'])) {
- $where = ['id' => $params['id'], ['status' => StatusEnum::ENABLED]];
- if (isset($params['mall_id'])) $where[] = ['mall_id' => $params['mall_id']];
- $model = self::findOne($where);
- if (empty($model)) throw new Exception('服务不存在或已删除');
- } else {
- $model = new self();
- $model->loadDefaultValues();
- $model->auth_key = Yii::$app->security->generateRandomString();
- }
- if(!empty($params['password'])){
- $params['password'] = Yii::$app->security->generatePasswordHash($params['password']);
- $params['auth_key'] = Yii::$app->security->generateRandomString();
- }else{
- unset($params['password']);
- }
- if(!empty($params['expired_at'])) $params['expired_at'] = strtotime($params['expired_at']);
- if (!$model->load($params, '') || !$model->save()) throw new \PHPUnit\Util\Exception($model->getErrorMessage());
- if(!empty($params['role_id'])){
- $res = AdminRole::setData(['id' => $params['admin_role_id'], 'role_id' => $params['role_id'], 'admin_id' => $model->id]);
- if ($res === false) throw new Exception(AdminRole::getStaticError());
- }
- if(!empty($params['admin_type'])&&$params['admin_type']==1){
- $res = AdminRole::findOne(['admin_id' => $model->id]);
- if(!empty($res))$res->delete();
- }
- $tr->commit();
- return $model;
- } catch (Exception $e) {
- $tr->rollBack();
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- /**
- * 检测参数数据
- * @Author: 广东七件事 zal
- * @Date: 2020-04-08
- * @Time: 19:49
- * @param $arr
- * @param $data
- * @throws \Exception
- */
- private static function checkData($arr, $data)
- {
- foreach ($arr as $key => $item) {
- if (!isset($data[$key])) {
- throw new \Exception('请传参数' . $key . '->' . $item);
- }
- }
- }
- public static function isSuperAdmin($id)
- {
- $res = self::findOne($id);
- if (empty($res)) return false;
- if ($res->admin_type == self::ADMIN_TYPE_SUPER) return true;
- return false;
- }
- public static function del($params){
- $tr = \Yii::$app->db->beginTransaction();
- try {
- $model = self::findOne($params);
- $model->status = StatusEnum::DELETE;
- if($model->admin_type=='1'&& $model->username=='admin') throw new Exception('超级管理员不允许删除');
- $res = $model->save();
- if ($res === false) throw new Exception(self::getStaticError());
- $res = AdminRole::deleteAll(['admin_id'=>$params['id']]);
- if ($res === false) throw new Exception(AdminRole::getStaticError());
- $tr->commit();
- return $model;
- }catch (Exception $e){
- $tr->rollBack();
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- /**
- * mall_id获取默认商城管理员
- *
- * @param integer $mall_id
- * @return self|null
- */
- public static function getDefaultByMallId(int $mall_id)
- {
- return static::find()
- ->where(['mall_id' => $mall_id, 'is_default' => 1])
- ->one();
- }
- /**
- * 设置新密码
- *
- * @param string $password
- * @return boolean
- */
- public function setNewPassword(string $password)
- {
- $this->password = Yii::$app->security->generatePasswordHash($password);
- return $this->save();
- }
- }
|