kevin_zhangl 3 лет назад
Родитель
Сommit
68e46487b7

+ 13 - 1
backendEle/src/utils/index.js

@@ -34,6 +34,18 @@ module.exports = {
         cssSourceMap: true
     },
 
+    trial: {
+        env: require('./trial.env'),
+        index: path.resolve(__dirname, '../dist/trial/index.html'),
+        assetsRoot: path.resolve(__dirname, '../dist/trial'),
+        assetsSubDirectory: 'static',
+        assetsPublicPath: '/',
+        productionSourceMap: true,
+        productionGzip: false,
+        productionGzipExtensions: ['js', 'css'],
+        bundleAnalyzerReport: process.env.npm_config_report,
+    },
+
     build: {
         // Template for index.html
         index: path.resolve(__dirname, '../dist/index.html'),
@@ -59,4 +71,4 @@ module.exports = {
         // Set to `true` or `false` to always turn it on or off
         bundleAnalyzerReport: process.env.npm_config_report
     }
-}
+}

+ 13 - 43
common/models/BaUser.php

@@ -2,15 +2,14 @@
 
 namespace common\models;
 
+use common\components\ActiveRecord;
 use common\helpers\Cache;
-use common\helpers\Tool;
-use common\helpers\user\Info;
 use Yii;
 use yii\helpers\Json;
 use common\libs\logging\operate\valueType\Config as ValueTypeConfig;
 
 /**
- * This is the model class for table "{{%USER}}".
+ * This is the model class for table "{{%BA_USER}}".
  *
  * @property string $ID
  * @property string $USER_NAME 帐号
@@ -95,7 +94,7 @@ use common\libs\logging\operate\valueType\Config as ValueTypeConfig;
  * @property int $IS_STUDIO 是否是工作室
  * @property string $EMAIL 邮箱
  */
-class BaUser extends \common\components\ActiveRecord
+class BaUser extends ActiveRecord
 {
     /**
      * @inheritdoc
@@ -221,7 +220,7 @@ class BaUser extends \common\components\ActiveRecord
 
     public function getUserInfo()
     {
-        return $this->hasOne(UserInfo::class, ['USER_ID' => 'ID']);
+        return $this->hasOne(BaUserInfo::class, ['USER_ID' => 'ID']);
     }
 
     /**
@@ -287,44 +286,6 @@ class BaUser extends \common\components\ActiveRecord
         return time() < $eTime ? true : false;
     }
 
-    // 获取用户报单PV总和
-    public static function sumDevPvByUserId($userId) {
-        $decOrderPv = DecOrder::find()
-        ->select('SUM(DEC_PV) AS PV_SUM')
-        ->where('TO_USER_ID=:TO_USER_ID  AND IS_DEL=0', 
-            ['TO_USER_ID'=>$userId]
-        )
-        ->asArray()
-        ->one();
-        $decOrderPv = isset($decOrderPv['PV_SUM']) ? $decOrderPv['PV_SUM'] : 0;
-        $orderDecPv = OrderDec::find()
-        ->select('SUM(PAY_PV) AS PV_SUM')
-        ->where('USER_ID=:USER_ID  AND IS_DELETE=0', 
-            [
-                'USER_ID'=>$userId, 
-                
-            ]
-        )
-        ->asArray()
-        ->one();
-        $orderDecPv = isset($orderDecPv['PV_SUM']) ? $orderDecPv['PV_SUM'] : 0;
-        // 还得加上用户在老系统中的所有报单PV之和
-        $originPv = OriginDecPv::find()
-        ->select('SUM(DEC_PV) AS PV_SUM')
-        ->where('USER_ID=:USER_ID', 
-            [
-                'USER_ID'=>$userId, 
-                
-            ]
-        )
-        ->asArray()
-        ->one();
-        $originPv = isset($originPv['PV_SUM']) ? $originPv['PV_SUM'] : 0;
-        $total = $orderDecPv + $decOrderPv + $originPv;
-
-        return $total;
-    }
-
     /**
      * 获取会员的部分信息并对敏感信息加密
      * @param $userId
@@ -514,4 +475,13 @@ class BaUser extends \common\components\ActiveRecord
         ];
     }
 
+    /**
+     * Finds user by username
+     *
+     * @param string $username
+     * @return static|null
+     */
+    public static function findByUsername($username) {
+        return static::findOne(['USER_NAME' => $username]);
+    }
 }

+ 8 - 0
frontendApi/config/main.php

@@ -43,6 +43,14 @@ return [
             'class' => 'frontendApi\modules\v1\components\UserAuth',
             'identityClass' => 'frontendApi\modules\v1\models\User',
             'enableAutoLogin' => false,
+            'idParam' => '__user'
+        ],
+        'brand' => [
+            'class' => 'frontendApi\modules\v1\components\BrandAuth',
+            'identityClass' => 'frontendApi\modules\v1\models\brand\User',
+            'enableAutoLogin' => false,
+            'idParam' => '__brand',
+            'identityCookie' => ['name' => '_brand_identity', 'httpOnly' => true],
         ],
         'log' => [
             'traceLevel' => YII_DEBUG ? 3 : 0,

+ 1 - 0
frontendApi/config/urlManagerRules.php

@@ -55,6 +55,7 @@ return [
             'GET my-index' => 'my-index',
             'GET period-bonus' => 'period-bonus',
             'GET bonus-num' => 'bonus-num',
+            'GET ba-index' => 'ba-index',
         ],
     ],
     [

+ 399 - 0
frontendApi/modules/v1/components/BrandAuth.php

@@ -0,0 +1,399 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: leo
+ * Date: 2018/2/28
+ * Time: 上午10:31
+ */
+
+namespace frontendApi\modules\v1\components;
+
+use common\components\Redis;
+use common\components\Request;
+use common\helpers\Date;
+use common\helpers\Form;
+use common\helpers\http\BackendToFrontendApi;
+use common\models\BaUserInfo;
+use common\models\Message;
+use common\models\UserToken;
+use Yii;
+use yii\db\ActiveRecordInterface;
+use yii\web\HttpException;
+use yii\web\IdentityInterface;
+use yii\web\User;
+
+class BrandAuth extends User {
+    private $_userId = null;
+    private $_apiIdentity = null;
+    private $_token = null;
+    private $_userInfo = null;
+    private $_device = null;
+    private static $_isQuicklyLogin = false;
+
+    /**
+     * 初始化设备信息
+     * @throws \yii\base\InvalidConfigException
+     */
+    public function init() {
+        parent::init();
+        $this->_device = Yii::$app->request->getDevice();
+    }
+
+    /**
+     * 首次以用户名和密码的方式登录
+     * @param IdentityInterface $identity
+     * @return bool
+     * @throws HttpException
+     */
+    public function loginWithUAndP(IdentityInterface $identity) {
+        if ($this->beforeLogin($identity, false, 0)) {
+            $id = $identity->getId();
+            $ip = Yii::$app->getRequest()->getUserIP();
+
+            $this->_userId = $identity['ID'];
+            $this->_apiIdentity = $identity;
+            $this->_userInfo = [
+                'id' => $identity['ID'],
+                'userName' => $identity['USER_NAME'],
+                'accessTokenUpdatedAt' => Date::nowTime(),
+                'ip' => $ip,
+            ];
+
+            BaUserInfo::updateAll(['LAST_LOGIN_IP' => $ip, 'LAST_LOGIN_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID'=>$identity['ID']]);
+            $userToken = UserToken::findOne(['USER_ID' => $identity['ID']]);
+            if (!$userToken) {
+                $userToken = new UserToken();
+                $userToken->USER_ID = $identity['ID'];
+                $userToken->CREATED_AT = Date::nowTime();
+                if (!$userToken->save()) {
+                    throw new HttpException(500, Form::formatErrorsForApi($userToken->getErrors()), 500);
+                }
+            }
+
+            $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'access');
+            $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'refresh');
+
+            $this->afterLogin($identity, false, 0);
+        }
+
+        return !$this->getIsGuest();
+    }
+
+    /**
+     * 登录成功之后
+     * @param IdentityInterface $identity
+     * @param bool $cookieBased
+     * @param int $duration
+     * @throws \yii\base\Exception
+     */
+    public function afterLogin($identity, $cookieBased, $duration) {
+        // 拉取站内信
+        Message::pullMsgByUser($identity['ID']);
+        parent::afterLogin($identity, $cookieBased, $duration);
+    }
+
+    /**
+     * 已AccessToken方式登录(即平时直接访问)
+     * @param string $token
+     * @param null $type
+     * @return null|IdentityInterface
+     */
+    public function loginByAccessToken($token, $type = null) {
+        /* @var $class IdentityInterface */
+        $class = $this->identityClass;
+        $userId = $this->_userId = $class::findIdentityByAccessToken($token, $type);
+        if ($userId) {
+            $this->_userInfo = [
+                'id' => $userId,
+                'userName' => Yii::$app->tokenRedis->hget($token, 'USER_NAME'),
+                'accessTokenUpdatedAt' => Yii::$app->tokenRedis->hget($token, 'TOKEN_UPDATED_AT'),
+                'ip' => Yii::$app->getRequest()->getUserIP(),
+            ];
+            return $userId;
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * 从后台登录前台
+     * @param $userId
+     * @return null
+     * @throws HttpException
+     */
+    public function loginByBackend($userId) {
+        if (BaUserInfo::find()->where(['USER_ID' => $userId])->exists()) {
+            $userToken = UserToken::findOne(['USER_ID' => $userId]);
+            if (!$userToken) {
+                $userToken = new UserToken();
+                $userToken->USER_ID = $userId;
+                $userToken->CREATED_AT = Date::nowTime();
+                if (!$userToken->save()) {
+                    return null;
+                }
+            }
+            self::$_isQuicklyLogin = true;
+            $accessTokenResult = $this->updateToken($userToken, $appType = 'pc', $typeToken = 'access', $userId);
+            $refreshTokenResult = $this->updateToken($userToken, $appType = 'pc', $typeToken = 'refresh', $userId);
+            if ($accessTokenResult && $refreshTokenResult) {
+                return $this->getToken();
+            } else {
+                return null;
+            }
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * 用refreshToken生成新的accessToken和refreshToken
+     * @param $refreshToken
+     * @return bool
+     * @throws HttpException
+     */
+    public function refreshToken($refreshToken) {
+        if (!$refreshToken) {
+            return false;
+        }
+        $userId = Yii::$app->tokenRedis->hget($refreshToken, 'ID');
+        if (!$userId) {
+            return false;
+        }
+        $userToken = UserToken::findOne(['USER_ID' => $userId]);
+        $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'access', $userId);
+        $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'refresh', $userId);
+        return true;
+    }
+
+    /**
+     * 用refreshToken生成新的accessToken
+     * @param $refreshToken
+     * @return bool
+     * @throws HttpException
+     */
+    public function refreshAccessToken($refreshToken) {
+        if (!$refreshToken) {
+            return false;
+        }
+        $userId = Yii::$app->tokenRedis->hget($refreshToken, 'ID');
+        if (!$userId) {
+            return false;
+        }
+        $userToken = UserToken::findOne(['USER_ID' => $userId]);
+        return $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'access', $userId);
+    }
+
+    /**
+     * 用refreshToken生成新的refreshToken
+     * @param $refreshToken
+     * @return bool
+     * @throws HttpException
+     */
+    public function refreshRefreshToken($refreshToken) {
+        if (!$refreshToken) {
+            return false;
+        }
+        $userId = Yii::$app->tokenRedis->hget($refreshToken, 'ID');
+        if (!$userId) {
+            return false;
+        }
+        $userToken = UserToken::findOne(['USER_ID' => $userId]);
+        return $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'refresh', $userId);
+    }
+
+    /**
+     * 更新token 的具体方法
+     * @param ActiveRecordInterface $userTokenModel
+     * @param string $appType (pc|app)
+     * @param string $typeToken
+     * @param $userId
+     * @return bool
+     * @throws HttpException
+     */
+    public function updateToken(ActiveRecordInterface $userTokenModel, $appType = Request::DEVICE_PC, $typeToken = 'access', $userId = 0) {
+        $tokenField = strtoupper($appType . '_' . $typeToken . '_TOKEN');
+        $updateField = '';
+        $expiresIn = 0;
+        if ($appType === Request::DEVICE_PC) {
+            if ($typeToken === 'access') {
+                $updateField = 'PAT_UPDATED_AT';
+                $expiresIn = Yii::$app->params['frontAccessTokenExpiresIn'];
+            } elseif ($typeToken === 'refresh') {
+                $updateField = 'PRT_UPDATED_AT';
+                $expiresIn = Yii::$app->params['frontRefreshTokenExpiresIn'];
+            } else {
+                throw new HttpException(500, 'token字段错误', 500);
+            }
+        } elseif ($appType === Request::DEVICE_APP) {
+            if ($typeToken === 'access') {
+                $updateField = 'AAT_UPDATED_AT';
+                $expiresIn = Yii::$app->params['frontAccessTokenExpiresIn'];
+            } elseif ($typeToken === 'refresh') {
+                $updateField = 'ART_UPDATED_AT';
+                $expiresIn = Yii::$app->params['frontRefreshTokenExpiresIn'];
+            } else {
+                throw new HttpException(500, 'token字段错误', 500);
+            }
+        }
+        // 老token
+        $oldToken = $userTokenModel->$tokenField;
+        // 生成 access_token
+        /* @var $identityClass IdentityInterface */
+        $identityClass = $this->identityClass;
+        $generateTokenMethodName = 'generate' . ucfirst($typeToken) . 'Token';
+        //$token = $identityClass::generateAccessToken();
+        $token = call_user_func([$identityClass, $generateTokenMethodName], $appType);
+        $userTokenModel->$tokenField = $token;
+        $userTokenModel->$updateField = Date::nowTime();
+        if (!$userTokenModel->save()) {
+            throw new HttpException(500, 'token更新失败', 500);
+        }
+        // 查找TOKEN中是否有同一用户产生的垃圾token,有的话就清除
+        Yii::$app->tokenRedis->del($oldToken);
+
+        $identity = $this->_apiIdentity;
+        if (!$this->_apiIdentity) {
+            if (!$userId) {
+                throw new HttpException(500, 'userId不能为空', 500);
+            }
+            $identity = $identityClass::findIdentity($userId);
+        }
+        // 把 accessToken 当做key存入redis中内容为会员的ID和用户名
+        Yii::$app->tokenRedis->hset($token, 'ID', $identity['ID']);
+        Yii::$app->tokenRedis->hset($token, 'USER_NAME', $identity['USER_NAME']);
+        Yii::$app->tokenRedis->hset($token, 'TOKEN_UPDATED_AT', $userTokenModel->$updateField);
+        Yii::$app->tokenRedis->expire($token, $expiresIn);
+
+        // 标记为快速登录的会员
+        if (self::$_isQuicklyLogin) {
+            Yii::$app->redis->setex(Redis::key(\frontendApi\modules\v1\models\User::CACHE_IS_QUICKLY_LOGIN . $token), Yii::$app->params['frontAccessTokenExpiresIn'], 1);
+        }
+
+        $this->_token = array_merge($this->_token ? $this->_token : [], [
+            $typeToken . 'Token' => $token,
+            $typeToken . 'TokenExpiresIn' => $expiresIn,
+            $typeToken . 'TokenUpdateAt' => $userTokenModel->$updateField,
+        ]);
+
+        return true;
+    }
+
+    /**
+     * 获取管理员ID
+     * @return int|null|string
+     */
+    public function getId() {
+        return $this->_userId;
+    }
+
+    /**
+     * 获取token
+     * @return null
+     */
+    public function getToken() {
+        return $this->_token;
+    }
+
+    /**
+     * 获取管理员信息
+     * @return null
+     */
+    public function getUserInfo() {
+        return $this->_userInfo;
+    }
+
+    /**
+     * 获取身份信息
+     * @param bool $autoRenew
+     * @return null|IdentityInterface
+     */
+    public function getIdentity($autoRenew = true) {
+        if ($this->_apiIdentity) {
+            return $this->_apiIdentity;
+        } else {
+            if ($this->_userId) {
+                /* @var $class IdentityInterface */
+                $class = $this->identityClass;
+                return $class::findOne(['ID' => $this->_userId]);
+            } else {
+                return null;
+            }
+        }
+    }
+
+    /**
+     * 获取权限
+     * @return mixed
+     */
+    public function getUserPermission() {
+        return [];
+    }
+
+    /**
+     * 校验权限
+     * @param $controller
+     * @param string $action
+     * @return bool
+     */
+    public function validateUserAction($controller, $action = '') {
+        $isRecharge = \common\models\BaUser::getEnCodeInfo($this->_userId)['IS_RECHARGE'];
+        if($controller=='finance' &&  $action=='recharge' &&  $isRecharge==0){
+            return false;
+        }
+        return true;
+//        $userInfo = $this->_userInfo;
+//        if($userInfo['roleId'] === Yii::$app->params['superAdminRoleId']){
+//            return true;
+//        }
+//        // 查看控制器是否在白名单中,如果在白名单中则直接返回true
+//        $noCheckActions = Yii::$app->params['noCheckPermissionActions'];
+//        if(in_array($controller.'/'.$action, $noCheckActions)){
+//            return true;
+//        }
+//        return true;
+    }
+
+    /**
+     * 查看是否有该控制器的权限
+     * @param $controller
+     * @return bool
+     */
+    public function validateUserController($controller) {
+        $isAtlas = \common\models\BaUser::getEnCodeInfo($this->_userId)['IS_ATLAS'];
+        if($controller=='atlas' &&  $isAtlas==0){
+            return false;
+        }
+        return true;
+//        if($userInfo['roleId'] === Yii::$app->params['superAdminRoleId']){
+//            return true;
+//        }
+//        $result = true;
+//        // 查看控制器是否在白名单中,如果在白名单中则直接返回true
+//        $noCheckActions = Yii::$app->params['noCheckPermissionActions'];
+//        foreach($noCheckActions as $action){
+//            if(preg_match('/^'.$controller.'\//', $action)){
+//                $result = true;
+//                break;
+//            }
+//        }
+//
+//        return $result;
+    }
+
+    /**
+     * 校验后台登录前台时所带的参数是否正确
+     * @return bool
+     */
+    public function validateBackendAuth() {
+        $data = [];
+        $getData = \Yii::$app->getRequest()->get();
+        $postData = \Yii::$app->getRequest()->post();
+        $route = '/' . Yii::$app->controller->module->id . '/' . Yii::$app->controller->id . '/' . Yii::$app->controller->action->id;
+        if (isset($getData[$route])) unset($getData[$route]);
+        if (!empty($getData)) $data = array_merge($data, $getData);
+        if (!empty($postData)) $data = array_merge($data, $postData);
+        return (isset($data['signature']) && isset($data['timestamp']) && BackendToFrontendApi::checkSignature($data['signature'], $data));
+    }
+
+
+}

+ 63 - 0
frontendApi/modules/v1/controllers/DashboardController.php

@@ -171,4 +171,67 @@ class DashboardController extends BaseController
         $chartData = ChartData::instance();
         return static::notice($chartData->userBonusData(\Yii::$app->user->id));
     }
+
+    /**
+     * 控制台首页
+     * @return mixed
+     * @throws \yii\base\Exception
+     * @throws \yii\db\Exception
+     * @throws \yii\web\HttpException
+     */
+    public function actionBaIndex(){
+        $nowTime = Date::nowTime();
+        $news = ArticleCategory::find()->select('ID,CATE_NAME')->orderBy('SORT ASC')->asArray()->all();
+        $where = ' CID=:CID AND STATUS=1';
+        foreach ($news as &$value){
+            $params = [
+                ':CID'=>$value['ID'],
+            ];
+            $value['LISTS'] = Article::find()->select('ID,TITLE,CID,CREATED_AT')->where($where,$params)->orderBy('CREATED_AT DESC')->limit(6)->asArray()->all();
+        }
+
+        //期数显示
+        $period = Period::instance();
+        $periodNum = $period->getNowPeriodNum();
+        //
+        $curYM = Period::find()->select("CALC_YEAR,CALC_MONTH")->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM'=>$periodNum])->asArray()->one();
+
+        $plist = Period::find()->select("PERIOD_NUM")->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH', [':CALC_YEAR'=>$curYM['CALC_YEAR'],':CALC_MONTH'=>$curYM['CALC_MONTH']])->orderBy('PERIOD_NUM ASC')->asArray()->all();
+
+        $wkrd = '';
+        foreach ($plist as $k=>$v) {
+            if($v['PERIOD_NUM'] == $periodNum){
+                $wkrd = $k + 1;
+                break;
+            }
+        }
+        if ($wkrd == 1) {
+            $wkrd .= 'st';
+        } else {
+            $wkrd .= 'nd';
+        }
+
+        $monthArray = [
+            1 => 'Jan',
+            2 => 'Feb',
+            3 => 'Mar',
+            4 => 'Apr',
+            5 => 'May',
+            6 => 'Jun',
+            7 => 'Jul',
+            8 => 'Aug',
+            9 => 'Sep',
+            10 => 'Oct',
+            11 => 'Nov',
+            12 => 'Dec',
+        ];
+
+
+        return static::notice([
+            'nowTime' => $nowTime,
+            'slides'=> Ad::findUseSlaves()->select('ID,IMAGE,LID,TITLE,CONTENT,TYPE')->where('LID=:LID AND STATUS=1', [':LID'=>'7EFF6260A16C3CC7E053693418AC03E4'])->orderBy('SORT ASC')->asArray()->all(),
+            'news'=>$news,
+            'periodNum'=>$periodNum . ' ,' . $wkrd . ' PC of '. $monthArray[$curYM['CALC_MONTH']],
+        ]);
+    }
 }

+ 12 - 3
frontendApi/modules/v1/controllers/OauthController.php

@@ -9,6 +9,7 @@ namespace frontendApi\modules\v1\controllers;
 
 use common\helpers\Cache;
 use common\helpers\Form;
+use common\models\BaUser;
 use common\models\forms\UserForm;
 use common\models\UserInfo;
 use common\models\UserToken;
@@ -66,8 +67,16 @@ class OauthController extends BaseController
      * @throws HttpException
      */
     public function actionInfo(){
-        User::updateBaseInfoToRedis(\Yii::$app->user->id);
-        return static::notice(User::getEnCodeInfo(\Yii::$app->user->id));
+        $isGuest = Yii::$app->getUser()->isGuest;
+        if (!$isGuest) {
+            User::updateBaseInfoToRedis(\Yii::$app->user->id);
+            $result = User::getEnCodeInfo(\Yii::$app->user->id);
+        } else {
+            BaUser::updateBaseInfoToRedis(\Yii::$app->user->id);
+            $result = BaUser::getEnCodeInfo(\Yii::$app->user->id);
+        }
+
+        return static::notice($result);
     }
 
     /**
@@ -106,7 +115,7 @@ class OauthController extends BaseController
             $model->scenario = 'login';
         }
         if ($model->load(Yii::$app->request->post(), '') && $model->login()) {
-            $token = Yii::$app->getUser()->getToken();
+            $token = !Yii::$app->getUser()->isGuest ? Yii::$app->getUser()->getToken() : Yii::$app->brand->getToken();
             return static::notice($token);
         } else {
             $firstError = $model->getFirstError('LoginForm');

+ 13 - 11
frontendApi/modules/v1/controllers/SiteController.php

@@ -12,6 +12,7 @@ use common\helpers\snowflake\PageSnowFake;
 use common\models\Ad;
 use common\models\AdLocation;
 use common\models\ArticleCategory;
+use common\models\BaUser;
 use common\models\DecOrder;
 use common\models\DecRole;
 use Yii;
@@ -119,15 +120,14 @@ class SiteController extends BaseController
         $daysDiff = Yii::$app->params['daysDiff'];
         // 钱包
         $shopWalletType = Yii::$app->params['shopWalletType'];
-        // 会员类型
-        $whetherBA = $this->_whetherBA();
+
         return [
             'decLevels' => $decLevels,
             'empLevels' => $empLevels,
             'menu' => $menu,
             'daysDiff' => $daysDiff,
             'shopWalletType' => $shopWalletType,
-            'whetherBA' => $whetherBA,
+            'whetherBA' => $this->_whetherBA(),
         ];
     }
 
@@ -135,6 +135,10 @@ class SiteController extends BaseController
         $menuResult = [];
         foreach($parentArray as $key => $parentMenu){
             if($key !== 'article'){
+                if ($this->_whetherBA() && $parentMenu['name'] == 'Dashboard') {
+                    $parentMenu['routePath'] = 'dashboard/ba-index';
+                }
+
                 // 菜单是否显示
                 if(isset($parentMenu['show']) && !$parentMenu['show']){
                     continue;
@@ -191,16 +195,14 @@ class SiteController extends BaseController
      * 是否BA会员: 未转正 && 在BA用户表有存在
      */
     private function _whetherBA() {
-
-        return true;
         // 是否正式会员
-//        if (User::find()->where('ID = :USER_ID', [':USER_ID' => \Yii::$app->user->id])->exists()) {
-//            return false;
-//        }
+        if (User::find()->where('ID = :USER_ID', [':USER_ID' => \Yii::$app->user->id])->exists()) {
+            return false;
+        }
         // 是否BA会员
-//        if (BAUser::find()->where('ID = :USER_ID"', [':USER_ID' => \Yii::$app->user->id])->exists()) {
-//            return true;
-//        }
+        if (BaUser::find()->where(['ID' => \Yii::$app->user->id])->exists()) {
+            return true;
+        }
         return false;
     }
 

+ 47 - 12
frontendApi/modules/v1/models/LoginForm.php

@@ -4,11 +4,15 @@ namespace frontendApi\modules\v1\models;
 use common\components\Model;
 use common\helpers\Date;
 use common\libs\LoginIpChecker;
+use common\models\BaUser;
+use common\models\BaUserInfo;
 use common\models\UserInfo;
+use ReflectionProperty;
 use Yii;
 use yii\base\Exception;
 use yii\captcha\Captcha;
 use common\libs\logging\login\UserLogin as UserLoginLogger;
+use \frontendApi\modules\v1\models\brand\User as Brand;
 
 /**
  * Login form
@@ -22,6 +26,7 @@ class LoginForm extends Model
 
     private $_user;
     private $_userInfo;
+    private $_whetherBA;
 
     const ERROR_IS_MODIFY_PASSWORD = 'ERROR_IS_MODIFY_PASSWORD';
 
@@ -76,9 +81,16 @@ class LoginForm extends Model
      * @throws \Exception
      */
     private function _updateFailTimes($transaction,$returnResult){
-        UserInfo::updateAllCounters([
-            'FAIL_NUMS' => 1,
-        ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        if (!$this->_whetherBA) {
+            UserInfo::updateAllCounters([
+                'FAIL_NUMS' => 1,
+            ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        } else {
+            BaUserInfo::updateAllCounters([
+                'FAIL_NUMS' => 1,
+            ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        }
+
         $transaction->commit();
 
         $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
@@ -96,9 +108,15 @@ class LoginForm extends Model
         $cacheKey = sprintf(self::FRONTEND_LOGIN_FAIL_TIMES, $this->userName);
         Yii::$app->tokenRedis->del($cacheKey);
 
-        UserInfo::updateAllCounters([
-            'LOGIN_NUMS' => 1,
-        ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        if (!$this->_whetherBA) {
+            UserInfo::updateAllCounters([
+                'LOGIN_NUMS' => 1,
+            ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        } else {
+            BaUserInfo::updateAllCounters([
+                'LOGIN_NUMS' => 1,
+            ], 'USER_NAME=:USER_NAME', ['USER_NAME' => $this->userName]);
+        }
     }
 
     /**
@@ -158,9 +176,17 @@ class LoginForm extends Model
                 $update = [
                     'BONUS_APP_CLIENT_ID' => $clientId,
                 ];
-                if (!User::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
-                    $this->_updateFailTimes($transaction, 'Member APP device information update failed'); // 会员APP设备信息更新失败
-                    throw new Exception('Member APP device information update failed'); // 会员APP设备信息更新失败
+
+                if (!$this->_whetherBA) {
+                    if (!User::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
+                        $this->_updateFailTimes($transaction, 'Member APP device information update failed'); // 会员APP设备信息更新失败
+                        throw new Exception('Member APP device information update failed'); // 会员APP设备信息更新失败
+                    }
+                } else {
+                    if (!BaUser::updateAll($update, 'ID=:ID', ['ID' => $this->_user['ID']])) {
+                        $this->_updateFailTimes($transaction, 'Member APP device information update failed'); // 会员APP设备信息更新失败
+                        throw new Exception('Member APP device information update failed'); // 会员APP设备信息更新失败
+                    }
                 }
             }
 
@@ -173,11 +199,14 @@ class LoginForm extends Model
             // 把用户的登录时间存在操作时间里
             Yii::$app->tokenRedis->hset('user:timeOut', $this->_userInfo['USER_ID'], time());
 
-            return Yii::$app->user->loginWithUAndP($this->_user);
+            if (!$this->_whetherBA) {
+                return Yii::$app->user->loginWithUAndP($this->_user);
+            } else {
+                return Yii::$app->brand->loginWithUAndP($this->_user);
+            }
         }catch(\Exception $e){
             $transaction->rollBack();
-            $this->setError($e->getMessage());
-            //AdminLoginLogger::fail($this->_user, $e->getMessage());
+            $this->setError($e->getFile() . '  ' . $e->getLine() . '  ' . $e->getMessage());
             return false;
         }
     }
@@ -191,6 +220,12 @@ class LoginForm extends Model
         if ($this->_user === null) {
             $this->_user = User::findByUsername($this->userName);
             $this->_userInfo = UserInfo::findOne(['USER_NAME' =>$this->userName]);
+            if (!$this->_user || !$this->_userInfo) {
+                $this->_user = Brand::findByUsername($this->userName);
+                $this->_userInfo = BaUserInfo::findOne(['USER_NAME' => $this->userName]);
+                // 是否BA会员
+                $this->_whetherBA = $this->_user && $this->_userInfo;
+            }
         }
         return $this->_user;
     }

+ 229 - 0
frontendApi/modules/v1/models/brand/User.php

@@ -0,0 +1,229 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: leo
+ * Date: 2018/2/24
+ * Time: 下午1:02
+ */
+
+namespace frontendApi\modules\v1\models\brand;
+
+use common\components\Redis;
+use common\helpers\Date;
+use common\models\BaUser;
+use common\models\UserToken;
+use Yii;
+use yii\web\IdentityInterface;
+
+class User extends BaUser implements IdentityInterface {
+    const CACHE_IS_QUICKLY_LOGIN = 'quickly:user:';
+
+    /**
+     * @param mixed $token
+     * @param null $type
+     * @return null|IdentityInterface|static
+     */
+    public static function findIdentityByAccessToken($token, $type = null) {
+        // 从redis中把 token 找到
+        return Yii::$app->tokenRedis->hget($token, 'ID');
+//        if($userId){
+//            return static::findOne(['ID' => $userId]);
+//        }
+//        return null;
+    }
+
+    public function fields() {
+        $fields = parent::fields();
+
+        // 删除一些包含敏感信息的字段
+        unset($fields['PASSWORD_HASH'], $fields['PAY_PASSWORD']);
+
+        return $fields;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function behaviors() {
+        return [
+            'yii\behaviors\TimestampBehavior',
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public static function findIdentity($id) {
+        return static::findOne(['ID' => $id]);
+    }
+
+    /**
+     * Finds user by username
+     *
+     * @param string $username
+     * @return static|null
+     */
+    public static function findByUsername($username) {
+        return static::findOne(['USER_NAME' => $username]);
+    }
+
+    /**
+     * 通过用户名获取信息并带着token表内容
+     * @param $username
+     * @return array
+     */
+    public static function findByUsernameWithToken($username) {
+        return static::find()->select(static::tableName() . '.*,T.ACCESS_TOKEN,T.REFRESH_TOKEN,T.CREATED_AT,T.UPDATED_AT')->join('LEFT JOIN', UserToken::tableName() . ' AS T', static::tableName() . '.ID=T.USER_ID')->where(static::tableName() . '.USER_NAME=:USER_NAME', ['USER_NAME' => $username])->asArray()->one();
+    }
+
+    /**
+     * 静态方法校验两个密码
+     * @param $password
+     * @param $validatePassword
+     * @return bool
+     */
+    public static function validatePasswordStatic($password, $validatePassword) {
+        return Yii::$app->security->validatePassword($password, $validatePassword);
+    }
+
+    /**
+     * 生成PCAccessToken
+     * @param $appType (pc|app)
+     * @return string
+     * @throws \yii\base\Exception
+     */
+    public static function generateAccessToken($appType) {
+        $appTypeUper = strtoupper($appType);
+        // 从redis的AccessTokenIncr中自增一个值
+        $incrValue = Yii::$app->tokenRedis->incr($appTypeUper . 'AccessTokenIncr');
+        // upa(user_pc_access)
+        return md5('u' . $appType[0] . 'a_' . Yii::$app->security->generateRandomString(8) . Date::nowTime() . $incrValue);
+    }
+
+    /**
+     * 生成PCRefreshToken
+     * @param $appType (pc|app)
+     * @return string
+     * @throws \yii\base\Exception
+     */
+    public static function generateRefreshToken($appType) {
+        $appTypeUper = strtoupper($appType);
+        // 从redis的AccessTokenIncr中自增一个值
+        $incrValue = Yii::$app->tokenRedis->incr($appTypeUper . 'RefreshTokenIncr');
+        // upr(user_pc_access)
+        return md5('u' . $appType[0] . 'r_' . Yii::$app->security->generateRandomString(8) . Date::nowTime() . $incrValue);
+    }
+
+    /**
+     * 通过重设密码 token 找到用户
+     * @param $token
+     * @return null|static
+     */
+    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 bool
+     */
+    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 bool if password provided is valid for current user
+     */
+    public function validatePassword($password) {
+        //return password_verify($password, $this->PASSWORD_HASH);
+        return Yii::$app->security->validatePassword($password, $this->PASSWORD_HASH);
+    }
+
+    /**
+     * Generates password hash from password and sets it to the model
+     * @param $password
+     * @throws \yii\base\Exception
+     */
+    public function setPassword($password) {
+        $this->PASSWORD_HASH = Yii::$app->security->generatePasswordHash($password);
+    }
+
+    /**
+     * Generates "remember me" authentication key
+     * @throws \yii\base\Exception
+     */
+    public function generateAuthKey() {
+        $this->AUTH_KEY = Yii::$app->security->generateRandomString();
+    }
+
+    /**
+     * Generates new password reset token
+     * @throws \yii\base\Exception
+     */
+    public function generatePasswordResetToken() {
+        $this->PASSWORD_RESET_TOKEN = Yii::$app->security->generateRandomString() . '_' . Date::nowTime();
+    }
+
+    /**
+     * Removes password reset token
+     */
+    public function removePasswordResetToken() {
+        $this->PASSWORD_RESET_TOKEN = null;
+    }
+
+
+    /**
+     * 简单的缓存信息,此信息是在登录时缓存的
+     * @return mixed
+     */
+    public static function isQuicklyLogin() {
+        $authHeader = Yii::$app->request->getHeaders()->get('Authorization');
+        if ($authHeader !== null && preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
+            $token = ($matches && isset($matches[1])) ? $matches[1] : null;
+            if ($token) {
+                $key = Redis::key(self::CACHE_IS_QUICKLY_LOGIN . $token);
+                $value = (int)Yii::$app->redis->get($key);
+                return $value;
+            }
+        }
+        return 0;
+    }
+}

+ 16 - 0
frontendEle/src/router/index.js

@@ -37,6 +37,22 @@ export const constantRouterMap = [
       },
     }]
   },
+  {
+    path: '/dashboard/ba-index',
+    component: layout,
+    redirect: '/dashboard/ba-index',
+    children: [{
+      path: '/dashboard/ba-index',
+      component: _import('dashboard/ba-index'),
+      name: 'dashboard_ba_index',
+      meta: {
+        title: 'Dashboard',//控制台
+        breadcrumb: [
+          {title: 'Dashboard', path: '/dashboard/ba-index'},//首页
+        ],
+      },
+    }]
+  },
   {
         path: '/shop',
         component: layout,

+ 242 - 0
frontendEle/src/views/dashboard/ba-index.vue

@@ -0,0 +1,242 @@
+<template>
+  <div v-loading="loading">
+    <div>
+      <div class="welcome" :style="getEmpBg()">
+        <h1>Welcome,{{userName}} <!--欢迎您-->
+
+        <b v-if="verified==='0'" class="text-danger">You do not have real name authentication, please log in the member system to complete the member information and upload ID card.</b><!--您未实名认证,请登录商城系统完善会员资料并上传身份证-->
+        </h1>
+        <el-row :gutter="0" class="wel-info">
+          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12">
+            <el-row :gutter="10">
+              <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="12">Current System Time:{{nowDateTime}}</el-col> <!--当前系统时间-->
+              <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="12">Current Pay Cycle:{{periodNum}}</el-col><!--当前业绩期-->
+            </el-row>
+          </el-col>
+        </el-row>
+      </div>
+      <div style="display: none;">
+        <el-button type="success" @click="go('/user/ba-index')">Personal Information</el-button><!--个人资料-->
+      </div>
+    </div>
+    <el-carousel trigger="click" :height="bannerHeight+'px'">
+      <el-carousel-item v-for="(item,key) in slides" :key="key">
+        <template v-if="item.TYPE==='1'">
+          <router-link :to="`/shop/ba-index`" target="_self" class="islide">
+            <img ref="bannerHeight" :src="imageArticle(item.IMAGE)" alt="" @load="imgLoad">
+          </router-link>
+        </template>
+        <template v-else>
+          <router-link :to="`/article/detail/${item.CONTENT}`" target="_blank" class="islide">
+            <img ref="bannerHeight" :src="imageArticle(item.IMAGE)" alt="" @load="imgLoad">
+          </router-link>
+        </template>
+      </el-carousel-item>
+    </el-carousel>
+
+    <el-row :gutter="10" class="news-c">
+      <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" v-for="(item,key) in news" :key="key">
+        <el-card class="box-card">
+          <div slot="header" class="clearfix">
+            <span>{{item.CATE_NAME}}</span>
+            <el-button type="text" class="box-card-more">
+              <router-link :to="`/article/list/${item.ID}`">more+</router-link>
+            </el-button>
+          </div>
+          <div v-for="(o,k) in item.LISTS" :key="k" class="text item" v-if="item.LISTS.length>0">
+            <router-link :to="`/article/detail/${o.ID}`" :title="o.TITLE">{{sub_str(o.TITLE)}}</router-link>
+            <span>{{tool.formatDate(o.CREATED_AT,false)}}</span>
+          </div>
+          <div v-if="item.LISTS.length==0">No content</div><!--暂无内容-->
+        </el-card>
+      </el-col>
+    </el-row>
+  </div>
+</template>
+
+<script>
+import network from '@/utils/network'
+import tool from '@/utils/tool'
+import baseInfo from '@/utils/baseInfo'
+import userInfo from '@/utils/userInfo'
+import countUp from 'vue-countup-v2'
+
+export default {
+  name: 'dashboard_ba_index',
+  components: {
+    countUp
+  },
+  mounted () {
+    network.getData(`dashboard/ba-index`).then(response => {
+      this.slides = response.slides
+      this.news = response.news
+      this.periodNum = response.periodNum
+      this.loading = false
+      this.imgLoad()
+      return network.getData(`dashboard/bonus-num`)
+    })
+    if (this.verified === '0') {
+    // '您未实名认证,请登录商城系统完善会员资料并上传身份证', '请注意'
+      this.$confirm('You do not have real name authentication, please log in the member system to complete the member information and upload ID card.', 'Please pay attention', {
+        confirmButtonText: 'Confirm', // 确定
+        type: 'warning'
+      }).then(() => {
+      }).catch(() => {
+
+      })
+    }
+    this.calcTime()
+    window.addEventListener('resize', () => {
+      this.imgLoad()
+    }, false)
+  },
+  data () {
+    return {
+      loading: true,
+      tool: tool,
+      nowTime: tool.getTimestamp(),
+      userName: userInfo.userName(),
+      verified: userInfo.baseData().VERIFIED,
+      slides: [],
+      news: [],
+      periodNum: '',
+      bannerHeight: ''
+    }
+  },
+  computed: {
+    nowDateTime: function () {
+      return tool.formatDate(this.nowTime)
+    }
+  },
+  methods: {
+    getEmpIco () {
+      return require('@/assets/emp-ico-1.png')
+    },
+    getEmpBg () {
+      return 'backgroundImage:url(' + require('@/assets/emp-bg-1.png') + ')'
+    },
+    sub_str (str, len = 15) {
+      if (str) return str.slice(0, len)
+    },
+    calcTime () {
+      let obj = this
+      setInterval(function () {
+        obj.nowTime += 1
+      }, 1000)
+    },
+    go: function (url) {
+      this.$router.push(url)
+    },
+    imgLoad () {
+      let _this = this
+      if (_this.$refs.bannerHeight) {
+        _this.$nextTick(function () {
+          _this.bannerHeight = _this.$refs.bannerHeight[0].height
+        })
+      }
+    },
+    imageArticle (imageUrl) {
+      return tool.getArImage(imageUrl, '/files/')
+    }
+  }
+}
+</script>
+
+<style scoped>
+  h1 {
+    margin-top: 0
+  }
+
+  .welcome {
+    padding-bottom: 10px;
+    background-repeat: no-repeat;
+    background-position: right top;
+  }
+
+  .wel-info {
+    line-height: 36px;
+  }
+
+  .wel-info img {
+    vertical-align: middle;
+  }
+
+  .news-c .el-col .box-card {
+    margin-top: 10px;
+  }
+
+  .news-c .el-col:nth-child(3n+1) .box-card {
+    border-bottom: 4px solid #f34d14;
+  }
+
+  .news-c .el-col:nth-child(3n+2) .box-card {
+    border-bottom: 4px solid #27a2d3;
+  }
+
+  .news-c .el-col:nth-child(3n+3) .box-card {
+    border-bottom: 4px solid #1bbc61;
+  }
+
+  .box-card-more {
+    float: right;
+    padding: 3px 10px;
+    border: 1px solid #ddd;
+    border-radius: 10px;
+  }
+
+  .box-card-more a {
+    color: #666;
+  }
+
+  .box-card-more:hover {
+    border-color: #409EFF;
+  }
+
+  .box-card .item {
+    position: relative;
+    line-height: 30px;
+    padding-left: 10px;
+  }
+
+  .box-card .item:before {
+    content: '';
+    display: block;
+    width: 4px;
+    height: 4px;
+    background: #f60;
+    position: absolute;
+    left: 0px;
+    top: 14px;
+  }
+
+  .box-card .item:after {
+    content: '';
+    display: table;
+    clear: both;
+  }
+
+  .box-card .item a {
+    color: #333;
+    float: left;
+  }
+
+  .box-card .item a:hover {
+    color: #f60;
+  }
+
+  .box-card .item span {
+    float: right;
+    color: #999;
+    font-size: 12px;
+  }
+
+  .islide {
+    display: block;
+    text-align: center;
+  }
+
+  .islide img {
+    max-width: 100%;
+    max-height: 330px;
+  }
+</style>

+ 6 - 1
frontendEle/src/views/login/index.vue

@@ -64,6 +64,7 @@ export default {
       pageId: '',
       captchaUrl: '',
       isLoginVerify: false,
+      baseInfo: baseInfo,
     }
   },
   beforeCreate () {
@@ -129,7 +130,11 @@ export default {
         if (response > 0) {
           store.state.baseInfo.messageUnreadNum = response
         }
-        this.$router.push('dashboard/index')
+        if (!this.baseInfo.whetherBA()) {
+          this.$router.push('dashboard/index')
+        } else {
+          this.$router.push('dashboard/ba-index')
+        }
       }).catch(error => {
         console.log(error);
         this.refreshLoginVerifyStatus();