|
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Services\Auth;
|
|
|
|
|
|
|
|
|
|
use App\Models\User;
|
|
|
|
|
use App\Services\RedisClient;
|
|
|
|
|
use App\Utils\Tools;
|
|
|
|
|
use App\Utils\Cookie;
|
|
|
|
|
use App\Services\Config;
|
|
|
|
|
use App\Services\LoginSessionRevocationService;
|
|
|
|
|
|
|
|
|
|
class Redis extends Base
|
|
|
|
|
{
|
|
|
|
|
private $client;
|
|
|
|
|
|
|
|
|
|
public function __construct()
|
|
|
|
|
{
|
|
|
|
|
$client = new RedisClient();
|
|
|
|
|
$this->client = $client;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function getClient()
|
|
|
|
|
{
|
|
|
|
|
return $this->client;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function login($uid, $time)
|
|
|
|
|
{
|
|
|
|
|
$user = User::find($uid);
|
|
|
|
|
if ($user === null) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$sid = Tools::genSID();
|
|
|
|
|
Cookie::set([
|
|
|
|
|
'sid' => $sid
|
|
|
|
|
], $time+time());
|
|
|
|
|
$value = LoginSessionRevocationService::encodeRedisSession(
|
|
|
|
|
$uid,
|
|
|
|
|
LoginSessionRevocationService::currentVersion($user)
|
|
|
|
|
);
|
|
|
|
|
$this->client->setex($sid, $time, $value);
|
|
|
|
|
$this->client->setex($sid."ip", $time, $_SERVER["REMOTE_ADDR"]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function logout()
|
|
|
|
|
{
|
|
|
|
|
$sid = Cookie::get('sid');
|
|
|
|
|
if ($sid !== '') {
|
|
|
|
|
$this->client->del($sid);
|
|
|
|
|
$this->client->del($sid."ip");
|
|
|
|
|
}
|
|
|
|
|
Cookie::set(['sid' => null], time() - 3600);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function getUser()
|
|
|
|
|
{
|
|
|
|
|
$sid = Cookie::get('sid');
|
|
|
|
|
$value = $this->client->get($sid);
|
|
|
|
|
|
|
|
|
|
$session = LoginSessionRevocationService::decodeRedisSession($value);
|
|
|
|
|
if ($session === null) {
|
|
|
|
|
$user = new User();
|
|
|
|
|
$user->isLogin = false;
|
|
|
|
|
return $user;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$ip = $this->client->get($sid."ip");
|
|
|
|
|
if ($ip != $_SERVER["REMOTE_ADDR"] && Config::get('enable_login_bind_ip')=='true') {
|
|
|
|
|
$user = new User();
|
|
|
|
|
$user->isLogin = false;
|
|
|
|
|
return $user;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$uid = $session['uid'];
|
|
|
|
|
$user = User::find($uid);
|
|
|
|
|
if ($user == null) {
|
|
|
|
|
$user = new User();
|
|
|
|
|
$user->isLogin = false;
|
|
|
|
|
return $user;
|
|
|
|
|
}
|
|
|
|
|
if (!LoginSessionRevocationService::snapshotMatches(
|
|
|
|
|
$session['version'],
|
|
|
|
|
LoginSessionRevocationService::currentVersion($user)
|
|
|
|
|
)) {
|
|
|
|
|
$this->client->del($sid);
|
|
|
|
|
$this->client->del($sid."ip");
|
|
|
|
|
$user->isLogin = false;
|
|
|
|
|
return $user;
|
|
|
|
|
}
|
|
|
|
|
$user->isLogin = true;
|
|
|
|
|
return $user;
|
|
|
|
|
}
|
|
|
|
|
}
|