1
0
mirror of https://gitee.com/koogua/course-tencent-cloud.git synced 2025-06-26 12:23:06 +08:00
xiaochong0302 c0e38d68fd 精简auth
2020-04-07 19:32:00 +08:00

90 lines
1.9 KiB
PHP

<?php
namespace App\Services\Auth;
use App\Library\Cache\Backend\Redis as RedisCache;
use App\Models\AccessToken as AccessTokenModel;
use App\Models\RefreshToken as RefreshTokenModel;
use App\Models\User as UserModel;
use App\Services\Auth as AuthService;
use Yansongda\Supports\Collection;
class Api extends AuthService
{
public function saveAuthInfo(UserModel $user)
{
$accessToken = new AccessTokenModel();
$accessToken->user_id = $user->id;
$accessToken->create();
$refreshToken = new RefreshTokenModel();
$refreshToken->user_id = $user->id;
$refreshToken->create();
$authInfo = [
'id' => $user->id,
'name' => $user->name,
];
$cache = $this->getCache();
$key = $this->getCacheKey($accessToken->id);
$cache->save($key, $authInfo, 2 * 3600);
return new Collection([
'access_token' => $accessToken->id,
'refresh_token' => $refreshToken->id,
'expiry_time' => $accessToken->expiry_time,
]);
}
public function clearAuthInfo()
{
$authToken = $this->getAuthToken();
$cache = $this->getCache();
$key = $this->getCacheKey($authToken);
$cache->delete($key);
}
public function getAuthInfo()
{
$authToken = $this->getAuthToken();
if (!$authToken) return null;
$cache = $this->getCache();
$key = $this->getCacheKey($authToken);
$authInfo = $cache->get($key);
$items = $authInfo ? $authInfo : [];
return new Collection($items);
}
protected function getAuthToken()
{
return $this->request->getHeader('Authorization');
}
protected function getCacheKey($token)
{
return "access_token:{$token}";
}
/**
* @return RedisCache
*/
protected function getCache()
{
return $this->getDI()->get('cache');
}
}