87 lines
3.2 KiB
PHP
87 lines
3.2 KiB
PHP
<?php
|
|
|
|
namespace App\Support;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Http\Request;
|
|
use TeleHub\WebAdmin\GuardUnavailable;
|
|
use TeleHub\WebAdmin\LoginBlocked;
|
|
use TeleHub\WebAdmin\Ticket;
|
|
|
|
final class XbAdminLogin
|
|
{
|
|
private static function begin(Request $request, $user)
|
|
{
|
|
$profile = $request->server->get('XB_INSTANCE') ?? config('site.profile');
|
|
$adminHost = $profile === 'hn' && strtolower(explode(':', (string) $request->server->get('HTTP_HOST'))[0]) === 'admin.hardnerd.net';
|
|
if ($user ? !$user->is_admin : !$adminHost) {
|
|
return null;
|
|
}
|
|
$instances = ['dpl' => 'xb-dpl', 'hn' => 'xb-hn', 'fuc-xb-test' => 'xb-fuc'];
|
|
$instance = $instances[$profile] ?? null;
|
|
if (!$instance || (!app()->environment('production') && !is_dir('/run/web-admin-login-'.$instance))) {
|
|
return null;
|
|
}
|
|
require_once '/opt/web-admin-login/current/Ticket.php';
|
|
return Ticket::begin($instance, $request->server->all());
|
|
}
|
|
|
|
private static function account($email)
|
|
{
|
|
if (!is_string($email) || $email === '' || strlen($email) > 254) {
|
|
return null;
|
|
}
|
|
// Match the account lookup used by this backend, including older releases.
|
|
$query = method_exists(User::class, 'scopeByEmail') || method_exists(User::class, 'byEmail')
|
|
? User::byEmail($email) : User::where('email', $email);
|
|
return $query->first(['id','is_admin']);
|
|
}
|
|
|
|
public static function rejected(Request $request, $email = null): void
|
|
{
|
|
self::handle($request, self::account($email), fn () => [false, null], fn () => null);
|
|
}
|
|
|
|
public static function password(Request $request, string $email, callable $verify, callable $issue): array
|
|
{
|
|
$candidate = self::account($email);
|
|
return self::handle($request, $candidate, $verify, $issue);
|
|
}
|
|
|
|
public static function verified(Request $request, $user, callable $issue)
|
|
{
|
|
[, $data] = self::handle($request, $user, fn () => [true, $user], $issue);
|
|
return $data;
|
|
}
|
|
|
|
private static function handle(Request $request, $candidate, callable $verify, callable $issue): array
|
|
{
|
|
try {
|
|
$ticket = self::begin($request, $candidate);
|
|
try {
|
|
[$success, $result] = $verify();
|
|
if ($success) {
|
|
// Account privileges may have changed during authentication.
|
|
if ($ticket === null && $result->is_admin && (!$candidate || !$candidate->is_admin)) {
|
|
$ticket = self::begin($request, $result);
|
|
}
|
|
$result = $issue($result);
|
|
}
|
|
} catch (\Throwable $error) {
|
|
if ($ticket !== null) {
|
|
$ticket->finish('error');
|
|
}
|
|
throw $error;
|
|
}
|
|
if ($ticket !== null) {
|
|
$ticket->finish($success ? 'success' : 'failure');
|
|
}
|
|
return [$success, $result];
|
|
} catch (LoginBlocked $error) {
|
|
abort(429, '该来源 IP 已触发管理员登录保护。');
|
|
} catch (GuardUnavailable $error) {
|
|
abort(503, '管理员登录保护暂不可用,请稍后重试。');
|
|
}
|
|
}
|
|
}
|