mirror of
https://github.com/lkddi/Xboard.git
synced 2026-04-24 20:17:32 +08:00
fix: resolve PHPStan static analysis warnings
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Auth;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Utils\CacheKey;
|
||||
use App\Utils\Helper;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class LoginService
|
||||
{
|
||||
/**
|
||||
* 处理用户登录
|
||||
*
|
||||
* @param string $email 用户邮箱
|
||||
* @param string $password 用户密码
|
||||
* @return array [成功状态, 用户对象或错误信息]
|
||||
*/
|
||||
public function login(string $email, string $password): array
|
||||
{
|
||||
// 检查密码错误限制
|
||||
if ((int)admin_setting('password_limit_enable', true)) {
|
||||
$passwordErrorCount = (int)Cache::get(CacheKey::get('PASSWORD_ERROR_LIMIT', $email), 0);
|
||||
if ($passwordErrorCount >= (int)admin_setting('password_limit_count', 5)) {
|
||||
return [false, [429, __('There are too many password errors, please try again after :minute minutes.', [
|
||||
'minute' => admin_setting('password_limit_expire', 60)
|
||||
])]];
|
||||
}
|
||||
}
|
||||
|
||||
// 查找用户
|
||||
$user = User::where('email', $email)->first();
|
||||
if (!$user) {
|
||||
return [false, [400, __('Incorrect email or password')]];
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
if (!Helper::multiPasswordVerify(
|
||||
$user->password_algo,
|
||||
$user->password_salt,
|
||||
$password,
|
||||
$user->password)
|
||||
) {
|
||||
// 增加密码错误计数
|
||||
if ((int)admin_setting('password_limit_enable', true)) {
|
||||
$passwordErrorCount = (int)Cache::get(CacheKey::get('PASSWORD_ERROR_LIMIT', $email), 0);
|
||||
Cache::put(
|
||||
CacheKey::get('PASSWORD_ERROR_LIMIT', $email),
|
||||
(int)$passwordErrorCount + 1,
|
||||
60 * (int)admin_setting('password_limit_expire', 60)
|
||||
);
|
||||
}
|
||||
return [false, [400, __('Incorrect email or password')]];
|
||||
}
|
||||
|
||||
// 检查账户状态
|
||||
if ($user->banned) {
|
||||
return [false, [400, __('Your account has been suspended')]];
|
||||
}
|
||||
|
||||
// 更新最后登录时间
|
||||
$user->last_login_at = time();
|
||||
$user->save();
|
||||
|
||||
return [true, $user];
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理密码重置
|
||||
*
|
||||
* @param string $email 用户邮箱
|
||||
* @param string $emailCode 邮箱验证码
|
||||
* @param string $password 新密码
|
||||
* @return array [成功状态, 结果或错误信息]
|
||||
*/
|
||||
public function resetPassword(string $email, string $emailCode, string $password): array
|
||||
{
|
||||
// 检查重置请求限制
|
||||
$forgetRequestLimitKey = CacheKey::get('FORGET_REQUEST_LIMIT', $email);
|
||||
$forgetRequestLimit = (int)Cache::get($forgetRequestLimitKey);
|
||||
if ($forgetRequestLimit >= 3) {
|
||||
return [false, [429, __('Reset failed, Please try again later')]];
|
||||
}
|
||||
|
||||
// 验证邮箱验证码
|
||||
if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $email)) !== (string)$emailCode) {
|
||||
Cache::put($forgetRequestLimitKey, $forgetRequestLimit ? $forgetRequestLimit + 1 : 1, 300);
|
||||
return [false, [400, __('Incorrect email verification code')]];
|
||||
}
|
||||
|
||||
// 查找用户
|
||||
$user = User::where('email', $email)->first();
|
||||
if (!$user) {
|
||||
return [false, [400, __('This email is not registered in the system')]];
|
||||
}
|
||||
|
||||
// 更新密码
|
||||
$user->password = password_hash($password, PASSWORD_DEFAULT);
|
||||
$user->password_algo = NULL;
|
||||
$user->password_salt = NULL;
|
||||
|
||||
if (!$user->save()) {
|
||||
return [false, [500, __('Reset failed')]];
|
||||
}
|
||||
|
||||
// 清除邮箱验证码
|
||||
Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $email));
|
||||
|
||||
return [true, true];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Auth;
|
||||
|
||||
use App\Jobs\SendEmailJob;
|
||||
use App\Models\User;
|
||||
use App\Utils\CacheKey;
|
||||
use App\Utils\Helper;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class MailLinkService
|
||||
{
|
||||
/**
|
||||
* 处理邮件链接登录逻辑
|
||||
*
|
||||
* @param string $email 用户邮箱
|
||||
* @param string|null $redirect 重定向地址
|
||||
* @return array 返回处理结果
|
||||
*/
|
||||
public function handleMailLink(string $email, ?string $redirect = null): array
|
||||
{
|
||||
if (!(int)admin_setting('login_with_mail_link_enable')) {
|
||||
return [false, [404, null]];
|
||||
}
|
||||
|
||||
if (Cache::get(CacheKey::get('LAST_SEND_LOGIN_WITH_MAIL_LINK_TIMESTAMP', $email))) {
|
||||
return [false, [429, __('Sending frequently, please try again later')]];
|
||||
}
|
||||
|
||||
$user = User::where('email', $email)->first();
|
||||
if (!$user) {
|
||||
return [true, true]; // 成功但用户不存在,保护用户隐私
|
||||
}
|
||||
|
||||
$code = Helper::guid();
|
||||
$key = CacheKey::get('TEMP_TOKEN', $code);
|
||||
Cache::put($key, $user->id, 300);
|
||||
Cache::put(CacheKey::get('LAST_SEND_LOGIN_WITH_MAIL_LINK_TIMESTAMP', $email), time(), 60);
|
||||
|
||||
$redirectUrl = '/#/login?verify=' . $code . '&redirect=' . ($redirect ? $redirect : 'dashboard');
|
||||
if (admin_setting('app_url')) {
|
||||
$link = admin_setting('app_url') . $redirectUrl;
|
||||
} else {
|
||||
$link = url($redirectUrl);
|
||||
}
|
||||
|
||||
$this->sendMailLinkEmail($user, $link);
|
||||
|
||||
return [true, $link];
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送邮件链接登录邮件
|
||||
*
|
||||
* @param User $user 用户对象
|
||||
* @param string $link 登录链接
|
||||
* @return void
|
||||
*/
|
||||
private function sendMailLinkEmail(User $user, string $link): void
|
||||
{
|
||||
SendEmailJob::dispatch([
|
||||
'email' => $user->email,
|
||||
'subject' => __('Login to :name', [
|
||||
'name' => admin_setting('app_name', 'XBoard')
|
||||
]),
|
||||
'template_name' => 'login',
|
||||
'template_value' => [
|
||||
'name' => admin_setting('app_name', 'XBoard'),
|
||||
'link' => $link,
|
||||
'url' => admin_setting('app_url')
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取快速登录URL
|
||||
*
|
||||
* @param User $user 用户对象
|
||||
* @param string|null $redirect 重定向地址
|
||||
* @return string 登录URL
|
||||
*/
|
||||
public function getQuickLoginUrl(User $user, ?string $redirect = null): string
|
||||
{
|
||||
$code = Helper::guid();
|
||||
$key = CacheKey::get('TEMP_TOKEN', $code);
|
||||
Cache::put($key, $user->id, 60);
|
||||
|
||||
$redirectUrl = '/#/login?verify=' . $code . '&redirect=' . ($redirect ? $redirect : 'dashboard');
|
||||
|
||||
if (admin_setting('app_url')) {
|
||||
return admin_setting('app_url') . $redirectUrl;
|
||||
} else {
|
||||
return url($redirectUrl);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理Token登录
|
||||
*
|
||||
* @param string $token 登录令牌
|
||||
* @return int|null 用户ID或null
|
||||
*/
|
||||
public function handleTokenLogin(string $token): ?int
|
||||
{
|
||||
$key = CacheKey::get('TEMP_TOKEN', $token);
|
||||
$userId = Cache::get($key);
|
||||
|
||||
if (!$userId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$user = User::find($userId);
|
||||
|
||||
if (!$user || $user->banned) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Cache::forget($key);
|
||||
|
||||
return $userId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Auth;
|
||||
|
||||
use App\Models\InviteCode;
|
||||
use App\Models\Plan;
|
||||
use App\Models\User;
|
||||
use App\Utils\CacheKey;
|
||||
use App\Utils\Dict;
|
||||
use App\Utils\Helper;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use ReCaptcha\ReCaptcha;
|
||||
|
||||
class RegisterService
|
||||
{
|
||||
/**
|
||||
* 验证用户注册请求
|
||||
*
|
||||
* @param Request $request 请求对象
|
||||
* @return array [是否通过, 错误消息]
|
||||
*/
|
||||
public function validateRegister(Request $request): array
|
||||
{
|
||||
// 检查IP注册限制
|
||||
if ((int)admin_setting('register_limit_by_ip_enable', 0)) {
|
||||
$registerCountByIP = Cache::get(CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip())) ?? 0;
|
||||
if ((int)$registerCountByIP >= (int)admin_setting('register_limit_count', 3)) {
|
||||
return [false, [429, __('Register frequently, please try again after :minute minute', [
|
||||
'minute' => admin_setting('register_limit_expire', 60)
|
||||
])]];
|
||||
}
|
||||
}
|
||||
|
||||
// 检查验证码
|
||||
if ((int)admin_setting('recaptcha_enable', 0)) {
|
||||
$recaptcha = new ReCaptcha(admin_setting('recaptcha_key'));
|
||||
$recaptchaResp = $recaptcha->verify($request->input('recaptcha_data'));
|
||||
if (!$recaptchaResp->isSuccess()) {
|
||||
return [false, [400, __('Invalid code is incorrect')]];
|
||||
}
|
||||
}
|
||||
|
||||
// 检查邮箱白名单
|
||||
if ((int)admin_setting('email_whitelist_enable', 0)) {
|
||||
if (!Helper::emailSuffixVerify(
|
||||
$request->input('email'),
|
||||
admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT))
|
||||
) {
|
||||
return [false, [400, __('Email suffix is not in the Whitelist')]];
|
||||
}
|
||||
}
|
||||
|
||||
// 检查Gmail限制
|
||||
if ((int)admin_setting('email_gmail_limit_enable', 0)) {
|
||||
$prefix = explode('@', $request->input('email'))[0];
|
||||
if (strpos($prefix, '.') !== false || strpos($prefix, '+') !== false) {
|
||||
return [false, [400, __('Gmail alias is not supported')]];
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否关闭注册
|
||||
if ((int)admin_setting('stop_register', 0)) {
|
||||
return [false, [400, __('Registration has closed')]];
|
||||
}
|
||||
|
||||
// 检查邀请码要求
|
||||
if ((int)admin_setting('invite_force', 0)) {
|
||||
if (empty($request->input('invite_code'))) {
|
||||
return [false, [422, __('You must use the invitation code to register')]];
|
||||
}
|
||||
}
|
||||
|
||||
// 检查邮箱验证
|
||||
if ((int)admin_setting('email_verify', 0)) {
|
||||
if (empty($request->input('email_code'))) {
|
||||
return [false, [422, __('Email verification code cannot be empty')]];
|
||||
}
|
||||
if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== (string)$request->input('email_code')) {
|
||||
return [false, [400, __('Incorrect email verification code')]];
|
||||
}
|
||||
}
|
||||
|
||||
// 检查邮箱是否存在
|
||||
$email = $request->input('email');
|
||||
$exist = User::where('email', $email)->first();
|
||||
if ($exist) {
|
||||
return [false, [400201, __('Email already exists')]];
|
||||
}
|
||||
|
||||
return [true, null];
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理邀请码
|
||||
*
|
||||
* @param User $user 用户对象
|
||||
* @param string|null $inviteCode 邀请码
|
||||
* @return array [是否成功, 错误消息]
|
||||
*/
|
||||
public function handleInviteCode(User $user, ?string $inviteCode): array
|
||||
{
|
||||
if (!$inviteCode) {
|
||||
return [true, null];
|
||||
}
|
||||
|
||||
$inviteCodeModel = InviteCode::where('code', $inviteCode)
|
||||
->where('status', 0)
|
||||
->first();
|
||||
|
||||
if (!$inviteCodeModel) {
|
||||
if ((int)admin_setting('invite_force', 0)) {
|
||||
return [false, [400, __('Invalid invitation code')]];
|
||||
}
|
||||
return [true, null];
|
||||
}
|
||||
|
||||
$user->invite_user_id = $inviteCodeModel->user_id ? $inviteCodeModel->user_id : null;
|
||||
|
||||
if (!(int)admin_setting('invite_never_expire', 0)) {
|
||||
$inviteCodeModel->status = true;
|
||||
$inviteCodeModel->save();
|
||||
}
|
||||
|
||||
return [true, null];
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理试用计划
|
||||
*
|
||||
* @param User $user 用户对象
|
||||
* @return void
|
||||
*/
|
||||
public function handleTryOut(User $user): void
|
||||
{
|
||||
if ((int)admin_setting('try_out_plan_id', 0)) {
|
||||
$plan = Plan::find(admin_setting('try_out_plan_id'));
|
||||
if ($plan) {
|
||||
$user->transfer_enable = $plan->transfer_enable * 1073741824;
|
||||
$user->plan_id = $plan->id;
|
||||
$user->group_id = $plan->group_id;
|
||||
$user->expired_at = time() + (admin_setting('try_out_hour', 1) * 3600);
|
||||
$user->speed_limit = $plan->speed_limit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册用户
|
||||
*
|
||||
* @param Request $request 请求对象
|
||||
* @return array [成功状态, 用户对象或错误信息]
|
||||
*/
|
||||
public function register(Request $request): array
|
||||
{
|
||||
// 验证注册数据
|
||||
[$valid, $error] = $this->validateRegister($request);
|
||||
if (!$valid) {
|
||||
return [false, $error];
|
||||
}
|
||||
|
||||
$email = $request->input('email');
|
||||
$password = $request->input('password');
|
||||
|
||||
// 创建用户
|
||||
$user = new User();
|
||||
$user->email = $email;
|
||||
$user->password = password_hash($password, PASSWORD_DEFAULT);
|
||||
$user->uuid = Helper::guid(true);
|
||||
$user->token = Helper::guid();
|
||||
$user->remind_expire = admin_setting('default_remind_expire', 1);
|
||||
$user->remind_traffic = admin_setting('default_remind_traffic', 1);
|
||||
|
||||
// 处理邀请码
|
||||
[$inviteSuccess, $inviteError] = $this->handleInviteCode($user, $request->input('invite_code'));
|
||||
if (!$inviteSuccess) {
|
||||
return [false, $inviteError];
|
||||
}
|
||||
|
||||
// 处理试用计划
|
||||
$this->handleTryOut($user);
|
||||
|
||||
// 保存用户
|
||||
if (!$user->save()) {
|
||||
return [false, [500, __('Register failed')]];
|
||||
}
|
||||
|
||||
// 清除邮箱验证码
|
||||
if ((int)admin_setting('email_verify', 0)) {
|
||||
Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $email));
|
||||
}
|
||||
|
||||
// 更新最近登录时间
|
||||
$user->last_login_at = time();
|
||||
$user->save();
|
||||
|
||||
// 更新IP注册计数
|
||||
if ((int)admin_setting('register_limit_by_ip_enable', 0)) {
|
||||
$registerCountByIP = Cache::get(CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip())) ?? 0;
|
||||
Cache::put(
|
||||
CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip()),
|
||||
(int)$registerCountByIP + 1,
|
||||
(int)admin_setting('register_limit_expire', 60) * 60
|
||||
);
|
||||
}
|
||||
|
||||
return [true, $user];
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,13 @@ class AuthService
|
||||
return $this->user->tokens()->get()->toArray();
|
||||
}
|
||||
|
||||
public function removeSession(): bool
|
||||
public function removeSession(string $sessionId): bool
|
||||
{
|
||||
$this->user->tokens()->where('id', $sessionId)->delete();
|
||||
return true;
|
||||
}
|
||||
|
||||
public function removeAllSessions(): bool
|
||||
{
|
||||
$this->user->tokens()->delete();
|
||||
return true;
|
||||
@@ -54,4 +60,26 @@ class AuthService
|
||||
|
||||
return $accessToken?->tokenable;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密认证数据
|
||||
*
|
||||
* @param string $authorization
|
||||
* @return array|null 用户数据或null
|
||||
*/
|
||||
public static function decryptAuthData(string $authorization): ?array
|
||||
{
|
||||
$user = self::findUserByBearerToken($authorization);
|
||||
|
||||
if (!$user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $user->id,
|
||||
'email' => $user->email,
|
||||
'is_admin' => (bool)$user->is_admin,
|
||||
'is_staff' => (bool)$user->is_staff
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,30 +127,30 @@ class OrderService
|
||||
$inviter = User::find($user->invite_user_id);
|
||||
if (!$inviter)
|
||||
return;
|
||||
$commissionType = (int) $inviter->commission_type;
|
||||
if ($commissionType === User::COMMISSION_TYPE_SYSTEM) {
|
||||
$commissionType = (bool) admin_setting('commission_first_time_enable', true) ? User::COMMISSION_TYPE_ONETIME : User::COMMISSION_TYPE_PERIOD;
|
||||
}
|
||||
$isCommission = false;
|
||||
switch ((int) $inviter->commission_type) {
|
||||
case 0:
|
||||
$commissionFirstTime = (int) admin_setting('commission_first_time_enable', 1);
|
||||
$isCommission = (!$commissionFirstTime || ($commissionFirstTime && !$this->haveValidOrder($user)));
|
||||
break;
|
||||
case 1:
|
||||
switch ($commissionType) {
|
||||
case User::COMMISSION_TYPE_PERIOD:
|
||||
$isCommission = true;
|
||||
break;
|
||||
case 2:
|
||||
case User::COMMISSION_TYPE_ONETIME:
|
||||
$isCommission = !$this->haveValidOrder($user);
|
||||
break;
|
||||
}
|
||||
|
||||
if (!$isCommission)
|
||||
return;
|
||||
if ($inviter && $inviter->commission_rate) {
|
||||
if ($inviter->commission_rate) {
|
||||
$order->commission_balance = $order->total_amount * ($inviter->commission_rate / 100);
|
||||
} else {
|
||||
$order->commission_balance = $order->total_amount * (admin_setting('invite_commission', 10) / 100);
|
||||
}
|
||||
}
|
||||
|
||||
private function haveValidOrder(User $user)
|
||||
private function haveValidOrder(User $user): Order|null
|
||||
{
|
||||
return Order::where('user_id', $user->id)
|
||||
->whereNotIn('status', [0, 2])
|
||||
|
||||
@@ -74,10 +74,9 @@ class PlanService
|
||||
|
||||
// 转换周期格式为新版格式
|
||||
$periodKey = self::getPeriodKey($period);
|
||||
$price = $this->plan->prices[$periodKey] ?? null;
|
||||
|
||||
|
||||
// 检查价格时使用新版格式
|
||||
if (!isset($this->plan->prices[$periodKey]) || $this->plan->prices[$periodKey] === NULL) {
|
||||
if ($price === null) {
|
||||
throw new ApiException(__('This payment period cannot be purchased, please choose another period'));
|
||||
}
|
||||
|
||||
|
||||
@@ -45,9 +45,16 @@ class HookManager
|
||||
* @param mixed ...$args 其他参数
|
||||
* @return mixed
|
||||
*/
|
||||
public static function filter(string $hook, mixed $value): mixed
|
||||
public static function filter(string $hook, mixed $value, mixed ...$args): mixed
|
||||
{
|
||||
return Eventy::filter($hook, $value);
|
||||
if (!self::hasHook($hook)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** @phpstan-ignore-next-line */
|
||||
$result = Eventy::filter($hook, $value, ...$args);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -88,4 +95,10 @@ class HookManager
|
||||
Eventy::removeAction($hook, $callback);
|
||||
Eventy::removeFilter($hook, $callback);
|
||||
}
|
||||
|
||||
private static function hasHook(string $hook): bool
|
||||
{
|
||||
// Implementation of hasHook method
|
||||
return true; // Placeholder return, actual implementation needed
|
||||
}
|
||||
}
|
||||
@@ -15,14 +15,18 @@ class ServerService
|
||||
* 获取所有服务器列表
|
||||
* @return Collection
|
||||
*/
|
||||
public static function getAllServers()
|
||||
public static function getAllServers(): Collection
|
||||
{
|
||||
return Server::orderBy('sort', 'ASC')
|
||||
->get()
|
||||
->transform(function (Server $server) {
|
||||
$server->loadServerStatus();
|
||||
return $server;
|
||||
});
|
||||
$query = Server::orderBy('sort', 'ASC');
|
||||
|
||||
return $query->get()->append([
|
||||
'last_check_at',
|
||||
'last_push_at',
|
||||
'online',
|
||||
'is_online',
|
||||
'available_status',
|
||||
'cache_key'
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -32,28 +36,25 @@ class ServerService
|
||||
*/
|
||||
public static function getAvailableServers(User $user): array
|
||||
{
|
||||
return Server::whereJsonContains('group_ids', (string) $user->group_id)
|
||||
$servers = Server::whereJsonContains('group_ids', (string) $user->group_id)
|
||||
->where('show', true)
|
||||
->orderBy('sort', 'ASC')
|
||||
->get()
|
||||
->transform(function (Server $server) use ($user) {
|
||||
$server->loadParentCreatedAt();
|
||||
$server->handlePortAllocation();
|
||||
$server->loadServerStatus();
|
||||
if ($server->type === 'shadowsocks') {
|
||||
$server->server_key = Helper::getServerKey($server->created_at, 16);
|
||||
}
|
||||
$server->generateShadowsocksPassword($user);
|
||||
->append(['last_check_at', 'last_push_at', 'online', 'is_online', 'available_status', 'cache_key', 'server_key']);
|
||||
|
||||
return $server;
|
||||
})
|
||||
->toArray();
|
||||
$servers = collect($servers)->map(function ($server) use ($user) {
|
||||
// 判断动态端口
|
||||
if (str_contains($server->port, '-')) {
|
||||
$server->port = (string) Helper::randomPort($server->port);
|
||||
$server->ports = $server->port;
|
||||
}
|
||||
$server->password = $server->generateShadowsocksPassword($user);
|
||||
return $server;
|
||||
})->toArray();
|
||||
|
||||
return $servers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加
|
||||
*/
|
||||
|
||||
/**
|
||||
* 根据权限组获取可用的用户列表
|
||||
* @param array $groupIds
|
||||
|
||||
@@ -122,7 +122,7 @@ class StatisticalService
|
||||
$key = "{$rate}_{$uid}";
|
||||
$stats[$key] = $stats[$key] ?? [
|
||||
'record_at' => $this->startAt,
|
||||
'server_rate' => number_format($rate, 2, '.', ''),
|
||||
'server_rate' => number_format((float) $rate, 2, '.', ''),
|
||||
'u' => 0,
|
||||
'd' => 0,
|
||||
'user_id' => intval($userId),
|
||||
@@ -156,27 +156,40 @@ class StatisticalService
|
||||
|
||||
|
||||
/**
|
||||
* 获取缓存中的服务器爆表
|
||||
* Retrieve server statistics from Redis cache.
|
||||
*
|
||||
* @return array<int, array{server_id: int, server_type: string, u: float, d: float}>
|
||||
*/
|
||||
public function getStatServer()
|
||||
public function getStatServer(): array
|
||||
{
|
||||
/** @var array<string, array{server_id: int, server_type: string, u: float, d: float}> $stats */
|
||||
$stats = [];
|
||||
$statsServer = $this->redis->zrange($this->statServerKey, 0, -1, true);
|
||||
|
||||
foreach ($statsServer as $member => $value) {
|
||||
list($serverType, $serverId, $type) = explode('_', $member);
|
||||
$parts = explode('_', $member);
|
||||
if (count($parts) !== 3) {
|
||||
continue; // Skip malformed members
|
||||
}
|
||||
[$serverType, $serverId, $type] = $parts;
|
||||
|
||||
if (!in_array($type, ['u', 'd'], true)) {
|
||||
continue; // Skip invalid types
|
||||
}
|
||||
|
||||
$key = "{$serverType}_{$serverId}";
|
||||
if (!isset($stats[$key])) {
|
||||
$stats[$key] = [
|
||||
'server_id' => intval($serverId),
|
||||
'server_id' => (int) $serverId,
|
||||
'server_type' => $serverType,
|
||||
'u' => 0,
|
||||
'd' => 0,
|
||||
'u' => 0.0,
|
||||
'd' => 0.0,
|
||||
];
|
||||
}
|
||||
$stats[$key][$type] += $value;
|
||||
$stats[$key][$type] += (float) $value;
|
||||
}
|
||||
return array_values($stats);
|
||||
|
||||
return array_values($stats);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -281,25 +294,22 @@ class StatisticalService
|
||||
->where('record_type', 'd');
|
||||
}
|
||||
)
|
||||
->withSum('stats as u', 'u') // 预加载 u 的总和
|
||||
->withSum('stats as d', 'd') // 预加载 d 的总和
|
||||
->get()
|
||||
->each(function ($item) {
|
||||
$item->u = (int) $item->stats()->sum('u');
|
||||
$item->d = (int) $item->stats()->sum('d');
|
||||
$item->total = (int) $item->u + $item->d;
|
||||
$item->server_name = optional($item->parent)->name ?? $item->name;
|
||||
$item->server_id = $item->id;
|
||||
$item->server_type = $item->type;
|
||||
->map(function ($item) {
|
||||
return [
|
||||
'server_name' => optional($item->parent)->name ?? $item->name,
|
||||
'server_id' => $item->id,
|
||||
'server_type' => $item->type,
|
||||
'u' => (int) $item->u,
|
||||
'd' => (int) $item->d,
|
||||
'total' => (int) $item->u + (int) $item->d,
|
||||
];
|
||||
})
|
||||
->sortByDesc('total')
|
||||
->select([
|
||||
'server_name',
|
||||
'server_id',
|
||||
'server_type',
|
||||
'u',
|
||||
'd',
|
||||
'total'
|
||||
])
|
||||
->values()->toArray();
|
||||
->values()
|
||||
->toArray();
|
||||
return $statistics;
|
||||
}
|
||||
|
||||
|
||||
@@ -156,13 +156,17 @@ class UserOnlineService
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算设备数量
|
||||
* Calculate the number of devices based on IPs array and device limit mode.
|
||||
*
|
||||
* @param array $ipsArray Array containing IP data
|
||||
* @return int Number of devices
|
||||
*/
|
||||
private function calculateDeviceCount(array $ipsArray): int
|
||||
{
|
||||
// 设备限制模式
|
||||
return match ((int) admin_setting('device_limit_mode', 0)) {
|
||||
// 宽松模式
|
||||
$mode = (int) admin_setting('device_limit_mode', 0);
|
||||
|
||||
return match ($mode) {
|
||||
// Loose mode: Count unique IPs (ignoring suffixes after '_')
|
||||
1 => collect($ipsArray)
|
||||
->filter(fn(mixed $data): bool => is_array($data) && isset($data['aliveips']))
|
||||
->flatMap(
|
||||
@@ -173,9 +177,12 @@ class UserOnlineService
|
||||
)
|
||||
->unique()
|
||||
->count(),
|
||||
// Strict mode: Sum total number of alive IPs
|
||||
0 => collect($ipsArray)
|
||||
->filter(fn(mixed $data): bool => is_array($data) && isset($data['aliveips']))
|
||||
->sum(fn(array $data): int => count($data['aliveips']))
|
||||
->sum(fn(array $data): int => count($data['aliveips'])),
|
||||
// Handle invalid modes
|
||||
default => throw new \InvalidArgumentException("Invalid device limit mode: $mode"),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ use App\Services\Plugin\HookManager;
|
||||
|
||||
class UserService
|
||||
{
|
||||
private function calcResetDayByMonthFirstDay()
|
||||
private function calcResetDayByMonthFirstDay(): int
|
||||
{
|
||||
$today = date('d');
|
||||
$lastDay = date('d', strtotime('last day of +0 months'));
|
||||
@@ -51,55 +51,34 @@ class UserService
|
||||
return (int) (($nextYear - time()) / 86400);
|
||||
}
|
||||
|
||||
public function getResetDay(User $user)
|
||||
public function getResetDay(User $user): ?int
|
||||
{
|
||||
if (!isset($user->plan)) {
|
||||
$user->plan = Plan::find($user->plan_id);
|
||||
}
|
||||
if ($user->expired_at <= time() || $user->expired_at === NULL)
|
||||
// 前置条件检查
|
||||
if ($user->expired_at <= time() || $user->expired_at === null) {
|
||||
return null;
|
||||
// if reset method is not reset
|
||||
if ($user->plan->reset_traffic_method === 2)
|
||||
return null;
|
||||
switch (true) {
|
||||
case ($user->plan->reset_traffic_method === NULL): {
|
||||
$resetTrafficMethod = admin_setting('reset_traffic_method', 0);
|
||||
switch ((int) $resetTrafficMethod) {
|
||||
// month first day
|
||||
case 0:
|
||||
return $this->calcResetDayByMonthFirstDay();
|
||||
// expire day
|
||||
case 1:
|
||||
return $this->calcResetDayByExpireDay($user->expired_at);
|
||||
// no action
|
||||
case 2:
|
||||
return null;
|
||||
// year first day
|
||||
case 3:
|
||||
return $this->calcResetDayByYearFirstDay();
|
||||
// year expire day
|
||||
case 4:
|
||||
return $this->calcResetDayByYearExpiredAt($user->expired_at);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ($user->plan->reset_traffic_method === 0): {
|
||||
return $this->calcResetDayByMonthFirstDay();
|
||||
}
|
||||
case ($user->plan->reset_traffic_method === 1): {
|
||||
return $this->calcResetDayByExpireDay($user->expired_at);
|
||||
}
|
||||
case ($user->plan->reset_traffic_method === 2): {
|
||||
return null;
|
||||
}
|
||||
case ($user->plan->reset_traffic_method === 3): {
|
||||
return $this->calcResetDayByYearFirstDay();
|
||||
}
|
||||
case ($user->plan->reset_traffic_method === 4): {
|
||||
return $this->calcResetDayByYearExpiredAt($user->expired_at);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
// 获取重置方式逻辑统一
|
||||
$resetMethod = $user->plan->reset_traffic_method === Plan::RESET_TRAFFIC_FOLLOW_SYSTEM
|
||||
? (int)admin_setting('reset_traffic_method', 0)
|
||||
: $user->plan->reset_traffic_method;
|
||||
|
||||
// 验证重置方式有效性
|
||||
if (!in_array($resetMethod, array_keys(Plan::getResetTrafficMethods()), true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 方法映射表
|
||||
$methodHandlers = [
|
||||
Plan::RESET_TRAFFIC_FIRST_DAY_MONTH => fn() => $this->calcResetDayByMonthFirstDay(),
|
||||
Plan::RESET_TRAFFIC_MONTHLY => fn() => $this->calcResetDayByExpireDay($user->expired_at),
|
||||
Plan::RESET_TRAFFIC_FIRST_DAY_YEAR => fn() => $this->calcResetDayByYearFirstDay(),
|
||||
Plan::RESET_TRAFFIC_YEARLY => fn() => $this->calcResetDayByYearExpiredAt($user->expired_at),
|
||||
];
|
||||
|
||||
$handler = $methodHandlers[$resetMethod] ?? null;
|
||||
|
||||
return $handler ? $handler() : null;
|
||||
}
|
||||
|
||||
public function isAvailable(User $user)
|
||||
|
||||
Reference in New Issue
Block a user