60], [['openid'], 'string', 'max' => 50], [['group'], 'string', 'max' => 100], [['access_token'], 'unique'], [['refresh_token'], 'unique'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'mch_id' => '商户', 'refresh_token' => '重置令牌', 'access_token' => '登录令牌', 'openid' => 'openid', 'user_id' => '会员ID', 'group' => '组别', 'status' => '状态', 'created_at' => '创建时间', 'updated_at' => '更新时间', ]; } /** * @param mixed $token * @param null $type * @return array|mixed|ActiveRecord|\yii\web\IdentityInterface|null * @throws UnauthorizedHttpException */ public static function findIdentityByAccessToken($token, $type = null) { // 判断验证token有效性是否开启 if($token){ if (Yii::$app->params['user.accessTokenValidity'] === true) { $timestamp = (int)substr($token, strrpos($token, '_') + 1); $expire = Yii::$app->params['user.accessTokenExpire']; // 验证有效期 if ($timestamp + $expire <= time()) throw new UnauthorizedHttpException('用户访问令牌已过期,请重新登录获取'); } }else{ if(!empty(Yii::$app->request->headers->get('openid'))){ $where=['openid'=>Yii::$app->request->headers->get('openid'),'status'=>StatusEnum::ENABLED]; $headers = \Yii::$app->request->headers; if(!empty($headers['x-mall-sign'])) $mall_sign = $headers['x-mall-sign']; if(!empty(\Yii::$app->request->get('mall-sign'))) $mall_sign = \Yii::$app->request->get('mall-sign'); if(!empty($mall_sign)){ $mall = Mall::getMallInfo($mall_sign); $where['mall_id'] = $mall['id']; } $user_info = UserInfo::findOne($where); if(empty($user_info))throw new UnauthorizedHttpException('此openid未授权,请重新授权'); if($user_info['user_id'] == 0) throw new UnauthorizedHttpException('此用户未授权手机号码'); } } // 优化版本到缓存读取用户信息 注意需要开启服务层的cache return Yii::$app->services->apiAccessToken->getTokenToCache($token, $type); } /** * @param $token * @param null $group * @return AccessToken|\common\models\base\User|null */ public static function findIdentityByRefreshToken($token, $group = null) { return static::findOne(['group' => $group, 'refresh_token' => $token, 'status' => StatusEnum::ENABLED]); } /** * 关联用户 * * @return \yii\db\ActiveQuery */ public function getUser() { return $this->hasOne(User::class, ['id' => 'user_id']); } /** * 关联授权角色 * * @return \yii\db\ActiveQuery */ public function getAssignment() { return $this->hasOne(AuthAssignment::class, ['user_id' => 'member_id']) ->where(['app_id' => Yii::$app->id]); } /** * @return array */ public function behaviors() { return [ [ 'class' => TimestampBehavior::class, 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'], ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'], ], ], ]; } }