first commit

This commit is contained in:
CN-JS-HuiBai
2026-04-07 16:54:24 +08:00
commit 2c6a38c80d
399 changed files with 42205 additions and 0 deletions

View File

@@ -0,0 +1,154 @@
<?php
namespace App\Services\Auth;
use App\Models\User;
use App\Services\Plugin\HookManager;
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::byEmail($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();
HookManager::call('user.login.after', $user);
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::byEmail($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')]];
}
HookManager::call('user.password.reset.after', $user);
// 清除邮箱验证码
Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $email));
return [true, true];
}
/**
* 生成临时登录令牌和快速登录URL
*
* @param User $user 用户对象
* @param string $redirect 重定向路径
* @return string|null 快速登录URL
*/
public function generateQuickLoginUrl(User $user, ?string $redirect = null): ?string
{
if (!$user || !$user->exists) {
return null;
}
$code = Helper::guid();
$key = CacheKey::get('TEMP_TOKEN', $code);
Cache::put($key, $user->id, 60);
$redirect = $redirect ?: 'dashboard';
$loginRedirect = '/#/login?verify=' . $code . '&redirect=' . rawurlencode($redirect);
if (admin_setting('app_url')) {
$url = admin_setting('app_url') . $loginRedirect;
} else {
$url = url($loginRedirect);
}
return $url;
}
}

View File

@@ -0,0 +1,100 @@
<?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::byEmail($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')
]
]);
}
/**
* 处理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;
}
}

View File

@@ -0,0 +1,193 @@
<?php
namespace App\Services\Auth;
use App\Exceptions\ApiException;
use App\Models\InviteCode;
use App\Models\Plan;
use App\Models\User;
use App\Services\CaptchaService;
use App\Services\Plugin\HookManager;
use App\Services\UserService;
use App\Utils\CacheKey;
use App\Utils\Dict;
use App\Utils\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
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)
])
]
];
}
}
// 检查验证码
$captchaService = app(CaptchaService::class);
[$captchaValid, $captchaError] = $captchaService->verify($request);
if (!$captchaValid) {
return [false, $captchaError];
}
// 检查邮箱白名单
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')]];
}
}
// 检查邮箱是否存在
$exist = User::byEmail($request->input('email'))->first();
if ($exist) {
return [false, [400201, __('Email already exists')]];
}
return [true, null];
}
/**
* 处理邀请码
*
* @param string $inviteCode 邀请码
* @return int|null 邀请人ID
*/
public function handleInviteCode(string $inviteCode): int|null
{
$inviteCodeModel = InviteCode::where('code', $inviteCode)
->where('status', InviteCode::STATUS_UNUSED)
->first();
if (!$inviteCodeModel) {
if ((int) admin_setting('invite_force', 0)) {
throw new ApiException(__('Invalid invitation code'));
}
return null;
}
if (!(int) admin_setting('invite_never_expire', 0)) {
$inviteCodeModel->status = InviteCode::STATUS_USED;
$inviteCodeModel->save();
}
return $inviteCodeModel->user_id;
}
/**
* 注册用户
*
* @param Request $request 请求对象
* @return array [成功状态, 用户对象或错误信息]
*/
public function register(Request $request): array
{
// 验证注册数据
[$valid, $error] = $this->validateRegister($request);
if (!$valid) {
return [false, $error];
}
HookManager::call('user.register.before', $request);
$email = $request->input('email');
$password = $request->input('password');
$inviteCode = $request->input('invite_code');
// 处理邀请码获取邀请人ID
$inviteUserId = null;
if ($inviteCode) {
$inviteUserId = $this->handleInviteCode($inviteCode);
}
// 创建用户
$userService = app(UserService::class);
$user = $userService->createUser([
'email' => $email,
'password' => $password,
'invite_user_id' => $inviteUserId,
]);
// 保存用户
if (!$user->save()) {
return [false, [500, __('Register failed')]];
}
HookManager::call('user.register.after', $user);
// 清除邮箱验证码
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];
}
}