You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.3 KiB
PHTML

3 years ago
<?php
/**
* 需登录的功能必须继承该类
*/
namespace app\index\controller;
use app\common\controller\JsonReturn;
use think\facade\Request;
use think\facade\Cache;
use app\common\model\User;
use app\common\model\UserToken;
use app\common\model\UserRelation;
use app\common\exception\ServiceException;
class AuthBase extends Home
{
protected $user;
protected function initialize()
{
// 必须先执行父类的加载方法
parent::initialize();
$token = Request::post('token', '', 'trim');
if (empty($token)) {
throw new ServiceException('请先登录!');
}
$token_info = UserToken::where('token', $token)->find();
if (empty($token_info)) {
throw new ServiceException('请先登录!');
}
if ($token_info->expire <= time()) {
throw new ServiceException('token已失效请重新登录');
}
$this->user = $this->getUserInfo($token_info);
}
/**
* 获取用户信息和好友列表
* @param $token_info UserToken token信息
* @return array|mixed|\PDOStatement|string|\think\Model|null
*/
protected function getUserInfo($token_info)
{
$info = Cache::get($token_info->token);
if (!$info) {
$info = User::where('id', $token_info->uid)->with(['userRelation' => function($query) {
$query->where('status', UserRelation::STATUS_ACTIVE);
}])->find();
Cache::set($token_info->token, $info);
}
return $info;
}
/**
* 获取好友列表信息
* @param string $field string 要查询的字段
* @return array|mixed
*/
protected function getFriendList()
{
$list = Cache::get('user_friend_' . $this->user->id);
if (!$list) {
$user_relation = $this->user->userRelation;
// 考虑到会出现缓存穿透的情况,如果返回为空也记录进缓存
if ($user_relation) {
$friend = array_column($user_relation->toArray(), 'friend_id');
$list = User::whereIn('id', $friend)->select()->toArray();
} else {
$list = $user_relation;
}
Cache::set('user_friend_' . $this->user->id, $list, 3600);
}
return $list;
}
}