91 lines
2.3 KiB
PHP
91 lines
2.3 KiB
PHP
<?php
|
|
namespace app\common\service;
|
|
|
|
use app\common\model\User;
|
|
use app\common\model\UserToken;
|
|
use app\common\model\AdminUser;
|
|
use app\common\model\AdminToken;
|
|
use Carbon\Carbon;
|
|
|
|
class AuthService
|
|
{
|
|
public static function issueUserToken(User $user): string
|
|
{
|
|
$ttl = intval(getenv('USER_TOKEN_TTL') ?: 604800);
|
|
$token = generateToken();
|
|
$hash = hashToken($token);
|
|
|
|
UserToken::create([
|
|
'user_id' => $user->id,
|
|
'token_hash' => $hash,
|
|
'expired_at' => $ttl > 0 ? Carbon::now()->addSeconds($ttl) : null,
|
|
]);
|
|
|
|
return $token;
|
|
}
|
|
|
|
public static function getUserByToken(?string $token): ?User
|
|
{
|
|
if (!$token) {
|
|
return null;
|
|
}
|
|
$hash = hashToken($token);
|
|
$row = UserToken::where('token_hash', $hash)->first();
|
|
if (!$row) {
|
|
return null;
|
|
}
|
|
if ($row->expired_at && $row->expired_at->lt(Carbon::now())) {
|
|
return null;
|
|
}
|
|
return User::find($row->user_id);
|
|
}
|
|
|
|
public static function revokeUserToken(?string $token): void
|
|
{
|
|
if (!$token) {
|
|
return;
|
|
}
|
|
UserToken::where('token_hash', hashToken($token))->delete();
|
|
}
|
|
|
|
public static function issueAdminToken(AdminUser $admin): string
|
|
{
|
|
$ttl = intval(getenv('ADMIN_TOKEN_TTL') ?: 86400);
|
|
$token = generateToken();
|
|
$hash = hashToken($token);
|
|
|
|
AdminToken::create([
|
|
'admin_id' => $admin->id,
|
|
'token_hash' => $hash,
|
|
'expired_at' => $ttl > 0 ? Carbon::now()->addSeconds($ttl) : null,
|
|
]);
|
|
|
|
return $token;
|
|
}
|
|
|
|
public static function getAdminByToken(?string $token): ?AdminUser
|
|
{
|
|
if (!$token) {
|
|
return null;
|
|
}
|
|
$hash = hashToken($token);
|
|
$row = AdminToken::where('token_hash', $hash)->first();
|
|
if (!$row) {
|
|
return null;
|
|
}
|
|
if ($row->expired_at && $row->expired_at->lt(Carbon::now())) {
|
|
return null;
|
|
}
|
|
return AdminUser::find($row->admin_id);
|
|
}
|
|
|
|
public static function revokeAdminToken(?string $token): void
|
|
{
|
|
if (!$token) {
|
|
return;
|
|
}
|
|
AdminToken::where('token_hash', hashToken($token))->delete();
|
|
}
|
|
}
|
|
|