You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Controllers/AuthController.php

1043 lines
46 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Controllers;
use App\Models\Configurations;
use App\Models\InviteCode;
use App\Services\Config;
use App\Utils\Check;
use voku\helper\AntiXSS;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use App\Utils\Hash;
use App\Utils\Totp;
use App\Utils\Cookie;
use App\Services\Auth;
use App\Services\CaptchaConfig;
use App\Services\Mail;
use App\Services\LoginSessionDurationService;
use App\Services\RegistrationEmailWhitelist;
use App\Services\RedisClient;
use App\Services\ReferralService;
use App\Services\TrustedLoginDeviceService;
use App\Models\User;
use App\Models\LoginIp;
use App\Models\EmailVerify;
/**
* AuthController
*/
class AuthController extends BaseController
{
private $login_forbidden_ips = '';
private $enable_login_email_verify = 'false';
private $login_session_ttl = 2592000;
private $trusted_login_device_ttl = 15552000;
private $login_verify_password_fail_ttl = 600;
private $login_verify_password_fail_limit = 8;
private $login_verify_ip_fail_limit = 30;
private $login_email_code_fail_ttl = 600;
private $login_email_code_fail_limit = 5;
public function __construct()
{
$configurations = $this->getDomainConfigurations();
$redis = new RedisClient();
$domain = $_SERVER['HTTP_HOST'];
$this->applyDomainTheme($configurations);
if ($this->domainMatchesConfigHost($configurations, 'host_1', $domain)) {
$this->cdn = $redis->get('admin_cdn', 60, function () {
return Configurations::where('name', 'admin_cdn')->value('value');
});
} elseif ($this->domainMatchesConfigHost($configurations, 'host_5', $domain)) {
// 如果 host_2 匹配
$this->cdn = $redis->get('backup_cdn', 60, function () {
return Configurations::where('name', 'backup_cdn')->value('value');
});
} else {
$this->cdn = $redis->get('cdn', 60, function () {
return Configurations::where('name', 'cdn')->value('value');
});
$this->backup_cdn = $redis->get('backup_cdn', 60, function () {
return Configurations::where('name', 'backup_cdn')->value('value');
});
}
$this->seo = $redis->get('seo', 60, function () {
return Configurations::where('name', 'seo')->value('value');
});
$this->aff_method = $redis->get('aff_method', 60, function () {
return Configurations::where('name', 'aff_method')->value('value');
});
if (!in_array($this->aff_method, ['code', 'affid'], true)) {
$this->aff_method = 'affid';
}
$this->enable_invite_code = $redis->get('enable_invite_code', 60, function () {
return Configurations::where('name', 'enable_invite_code')->value('value');
});
$this->login_forbidden_ips = $redis->get('login_forbidden_ips', 60, function () {
$value = Configurations::where('name', 'login_forbidden_ips')->value('value');
return $value === null ? '' : $value;
});
$this->enable_login_email_verify = $redis->get('enable_login_email_verify', 60, function () {
$value = Configurations::where('name', 'enable_login_email_verify')->value('value');
return $value === null ? 'false' : $value;
});
$loginSessionDays = $redis->get(LoginSessionDurationService::CONFIG_KEY, 60, function () {
$value = Configurations::where('name', LoginSessionDurationService::CONFIG_KEY)->value('value');
return $value === null ? (string) LoginSessionDurationService::DEFAULT_DAYS : $value;
});
$this->login_session_ttl = LoginSessionDurationService::ttlSeconds($loginSessionDays);
$trustedLoginDeviceDays = $redis->get(TrustedLoginDeviceService::CONFIG_KEY, 60, function () {
$value = Configurations::where('name', TrustedLoginDeviceService::CONFIG_KEY)->value('value');
return $value === null ? (string) TrustedLoginDeviceService::DEFAULT_DAYS : $value;
});
$this->trusted_login_device_ttl = TrustedLoginDeviceService::ttlSeconds($trustedLoginDeviceDays);
$this->appName = Config::get('appName');
$this->initializePublicLocale();
}
public function login()
{
$this->getLoginDeviceId();
return $this->publicView()->assign('captch_login', CaptchaConfig::get('captch_login'))
->assign('cdn', $this->cdn)->assign('backup_cdn', $this->backup_cdn)
->assign('appName', $this->appName)->assign('seo', $this->seo)
->display('auth/login.tpl');
}
private function getLoginClientIp()
{
$ip = isset($_SERVER["REMOTE_ADDR"]) ? trim((string) $_SERVER["REMOTE_ADDR"]) : '';
return preg_replace('/^::ffff:/i', '', $ip);
}
private function normalizeIpForCompare($ip)
{
$ip = preg_replace('/^::ffff:/i', '', trim((string) $ip));
if ($ip === '' || !filter_var($ip, FILTER_VALIDATE_IP)) {
return null;
}
return inet_pton($ip);
}
private function isLoginIpForbidden($ip)
{
$requestIp = $this->normalizeIpForCompare($ip);
if ($requestIp === null) {
return false;
}
$lines = preg_split('/\r\n|\r|\n/', (string) $this->login_forbidden_ips);
foreach ($lines as $line) {
$blockedIp = trim($line);
if ($blockedIp === '') {
continue;
}
if (strpos($blockedIp, '#') !== false) {
$blockedIp = trim(explode('#', $blockedIp, 2)[0]);
}
$blockedIp = $this->normalizeIpForCompare($blockedIp);
if ($blockedIp !== null && $blockedIp === $requestIp) {
return true;
}
}
return false;
}
private function getLoginDeviceId()
{
$cookieName = 'login_device_id';
$deviceId = isset($_COOKIE[$cookieName]) ? trim((string) $_COOKIE[$cookieName]) : '';
if (!preg_match('/^[a-zA-Z0-9]{32,64}$/', $deviceId)) {
$deviceId = bin2hex(random_bytes(24));
}
Cookie::set([$cookieName => $deviceId], time() + 86400 * 365);
return $deviceId;
}
private function trustedLoginDeviceKey($userId, $deviceId, $method = 'email')
{
if ($method === 'ga') {
return TrustedLoginDeviceService::KEY_PREFIX . (int) $userId . ':ga:' . hash('sha256', (string) $deviceId);
}
return TrustedLoginDeviceService::KEY_PREFIX . (int) $userId . ':' . hash('sha256', (string) $deviceId);
}
private function pendingLoginEmailVerifyCaptchaKey($email, $deviceId, $clientIp)
{
return 'pending_login_email_verify_captcha:' . hash('sha256', strtolower(trim((string) $email)) . '|' . (string) $deviceId . '|' . (string) $clientIp);
}
private function loginEmailVerifySendCooldownKey($email, $deviceId, $clientIp)
{
return 'login_email_verify_send_cooldown:' . hash('sha256', strtolower(trim((string) $email)) . '|' . (string) $deviceId . '|' . (string) $clientIp);
}
private function loginVerifyPasswordFailKey($email, $clientIp)
{
return 'login_verify_password_fail:' . hash('sha256', strtolower(trim((string) $email)) . '|' . (string) $clientIp);
}
private function loginVerifyIpFailKey($clientIp)
{
return 'login_verify_ip_fail:' . hash('sha256', (string) $clientIp);
}
private function loginEmailCodeFailKey($userId, $deviceId, $clientIp)
{
return 'login_email_code_fail:' . (int) $userId . ':' . hash('sha256', (string) $deviceId . '|' . (string) $clientIp);
}
private function loginGaCodeFailKey($userId, $deviceId, $clientIp)
{
return 'login_ga_code_fail:' . (int) $userId . ':' . hash('sha256', (string) $deviceId . '|' . (string) $clientIp);
}
private function hasGoogleAuthenticator($user)
{
return $user !== null
&& (int) $user->ga_enable === 1
&& Totp::normalizeSecret($user->ga_token) !== '';
}
private function loginVerifyMethod($user)
{
if ($this->hasGoogleAuthenticator($user) && (string) $user->login_verify_method === 'ga') {
return 'ga';
}
return 'email';
}
private function isTrustedLoginDevice($redis, $userId, $deviceId, $method = 'email')
{
return (string) $redis->get($this->trustedLoginDeviceKey($userId, $deviceId, $method)) === '1';
}
private function markTrustedLoginDevice($redis, $userId, $deviceId, $method = 'email')
{
$redis->setex($this->trustedLoginDeviceKey($userId, $deviceId, $method), $this->trusted_login_device_ttl, '1');
}
private function hasPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp)
{
return (string) $redis->get($this->pendingLoginEmailVerifyCaptchaKey($email, $deviceId, $clientIp)) === '1';
}
private function markPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp)
{
$redis->setex($this->pendingLoginEmailVerifyCaptchaKey($email, $deviceId, $clientIp), 600, '1');
}
private function clearPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp)
{
$redis->del($this->pendingLoginEmailVerifyCaptchaKey($email, $deviceId, $clientIp));
}
private function getLoginEmailVerifySendRetryAfter($redis, $email, $deviceId, $clientIp)
{
$ttl = $redis->getClient()->ttl($this->loginEmailVerifySendCooldownKey($email, $deviceId, $clientIp));
return $ttl > 0 ? (int) $ttl : 0;
}
private function markLoginEmailVerifySendCooldown($redis, $email, $deviceId, $clientIp)
{
$redis->setex($this->loginEmailVerifySendCooldownKey($email, $deviceId, $clientIp), 60, '1');
}
private function getRedisCount($redis, $key)
{
return (int) $redis->get($key);
}
private function incrementRedisCount($redis, $key, $ttl)
{
$count = (int) $redis->getClient()->incr($key);
if ($count === 1) {
$redis->getClient()->expire($key, $ttl);
}
return $count;
}
private function isLoginVerifyPasswordLimited($redis, $email, $clientIp)
{
return $this->getRedisCount($redis, $this->loginVerifyPasswordFailKey($email, $clientIp)) >= $this->login_verify_password_fail_limit
|| $this->getRedisCount($redis, $this->loginVerifyIpFailKey($clientIp)) >= $this->login_verify_ip_fail_limit;
}
private function recordLoginVerifyPasswordFail($redis, $email, $clientIp)
{
$this->incrementRedisCount($redis, $this->loginVerifyPasswordFailKey($email, $clientIp), $this->login_verify_password_fail_ttl);
$this->incrementRedisCount($redis, $this->loginVerifyIpFailKey($clientIp), $this->login_verify_password_fail_ttl);
}
private function clearLoginVerifyPasswordFail($redis, $email, $clientIp)
{
$redis->del($this->loginVerifyPasswordFailKey($email, $clientIp));
}
private function isLoginEmailCodeLimited($redis, $userId, $deviceId, $clientIp)
{
return $this->getRedisCount($redis, $this->loginEmailCodeFailKey($userId, $deviceId, $clientIp)) >= $this->login_email_code_fail_limit;
}
private function recordLoginEmailCodeFail($redis, $userId, $deviceId, $clientIp)
{
return $this->incrementRedisCount($redis, $this->loginEmailCodeFailKey($userId, $deviceId, $clientIp), $this->login_email_code_fail_ttl);
}
private function clearLoginEmailCodeFail($redis, $userId, $deviceId, $clientIp)
{
$redis->del($this->loginEmailCodeFailKey($userId, $deviceId, $clientIp));
}
private function isLoginGaCodeLimited($redis, $userId, $deviceId, $clientIp)
{
return $this->getRedisCount($redis, $this->loginGaCodeFailKey($userId, $deviceId, $clientIp)) >= $this->login_email_code_fail_limit;
}
private function recordLoginGaCodeFail($redis, $userId, $deviceId, $clientIp)
{
return $this->incrementRedisCount($redis, $this->loginGaCodeFailKey($userId, $deviceId, $clientIp), $this->login_email_code_fail_ttl);
}
private function clearLoginGaCodeFail($redis, $userId, $deviceId, $clientIp)
{
$redis->del($this->loginGaCodeFailKey($userId, $deviceId, $clientIp));
}
private function isLoginEmailVerifyEnabled()
{
return (string) $this->enable_login_email_verify === 'true';
}
private function verifyLoginEmailCode($email, $emailcode)
{
if (Mail::isRecipientBlacklisted($email)) {
return false;
}
if ($emailcode === null || trim((string) $emailcode) === '') {
return false;
}
$mailcount = EmailVerify::where('email', '=', $email)
->where('code', '=', trim((string) $emailcode))
->where('expire_in', '>', time())
->first();
if ($mailcount == null) {
return false;
}
EmailVerify::where('email', '=', $email)->where('code', '=', trim((string) $emailcode))->delete();
return true;
}
private function hasActiveLoginEmailCode($email, $emailcode)
{
if ($emailcode === null || trim((string) $emailcode) === '') {
return false;
}
return EmailVerify::where('email', '=', $email)
->where('code', '=', trim((string) $emailcode))
->where('expire_in', '>', time())
->first() !== null;
}
private function canReuseLoginCaptcha($redis, $email, $deviceId, $clientIp, $emailcode)
{
if ($redis !== null && $this->hasPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp)) {
return true;
}
return $this->hasActiveLoginEmailCode($email, $emailcode);
}
public function loginHandle($request, $response, $args)
{
Cookie::startSession();
$captch = $request->getParam('captch');
// $data = $request->post('sdf');
$email = $request->getParam('email');
$passwd = $request->getParam('passwd');
if (!is_string($email) || !is_string($passwd) || strlen($email) > 254 || strlen($passwd) > 72) {
return $response->withJson([
'ret' => 0,
'msg' => $this->publicText('邮箱或密码格式无效', 'The email or password format is invalid.'),
], 400);
}
$email = strtolower(trim($email));
$code = $request->getParam('code');
$emailcode = $request->getParam('emailcode');
$gacode = $request->getParam('gacode');
$clientIp = $this->getLoginClientIp();
$deviceId = $this->getLoginDeviceId();
$loginEmailVerifyEnabled = $this->isLoginEmailVerifyEnabled();
$redis = new RedisClient();
if ($this->isLoginIpForbidden($clientIp)) {
$rs['ret'] = 0;
if ($this->language == 'true') {
$rs['msg'] = "Login is blocked from your IP address";
} else {
$rs['msg'] = "当前 IP 已被禁止登录";
}
return $response->getBody()->write(json_encode($rs));
}
if (CaptchaConfig::get('captch_login') == 'true') {
if ($this->canReuseLoginCaptcha($redis, $email, $deviceId, $clientIp, $emailcode)) {
// 二次安全验证提交时复用首次登录已通过的图形验证码,避免要求用户重复输入。
} elseif (!isset($_SESSION['captch']) || strtolower($_SESSION['captch']) != strtolower($captch)) {
$res['ret'] = 0;
$res['msg'] = $this->language === 'true' ? 'Verification code is incorrect.' : '验证码错误。';
return $response->getBody()->write(json_encode($res));
}
unset($_SESSION['captch']);
}
if ($this->isLoginVerifyPasswordLimited($redis, $email, $clientIp)) {
return $response->withJson([
'ret' => 0,
'msg' => $this->publicText('尝试次数过多,请稍后再试', 'Too many attempts. Please try again later.'),
], 429);
}
// Handle Login
$user = User::where('email', '=', $email)->first();
if ($user == null) {
$this->recordLoginVerifyPasswordFail($redis, $email, $clientIp);
$rs['ret'] = 0;
if ($this->language == 'true') {
$rs['msg'] = "Email or password is wrong";
} else {
$rs['msg'] = "邮箱或密码错误";
}
return $response->getBody()->write(json_encode($rs));
}
if (!Hash::checkPassword($user->pass, $passwd)) {
$this->recordLoginVerifyPasswordFail($redis, $email, $clientIp);
$rs['ret'] = 0;
if ($this->language == 'true') {
$rs['msg'] = "Password is wrong";
} else {
$rs['msg'] = "密码错误";
}
$loginip=new LoginIp();
$loginip->ip=$_SERVER["REMOTE_ADDR"];
$loginip->userid=$user->id;
$loginip->request_domain = $_SERVER['HTTP_HOST'];
$loginip->datetime=time();
$loginip->type=1;
$loginip->save();
if ($redis !== null) {
$this->clearPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp);
}
return $response->getBody()->write(json_encode($rs));
}
if ((int) $user->enable !== 1) {
return $this->echoJson($response, [
'ret' => 0,
'msg' => $this->publicText('账户已停用', 'This account has been disabled.'),
]);
}
$this->clearLoginVerifyPasswordFail($redis, $email, $clientIp);
$loginVerifyMethod = $this->loginVerifyMethod($user);
$loginSecurityRequired = $loginEmailVerifyEnabled || $loginVerifyMethod === 'ga';
if ($loginSecurityRequired && $redis === null) {
$redis = new RedisClient();
}
$emailVerificationBlocked = $loginVerifyMethod === 'email'
&& Mail::isRecipientBlacklisted($user->email);
$trustedLoginDevice = !$emailVerificationBlocked
&& $loginSecurityRequired
&& $this->isTrustedLoginDevice($redis, $user->id, $deviceId, $loginVerifyMethod);
if ($loginSecurityRequired && !$trustedLoginDevice) {
if ($loginVerifyMethod === 'ga') {
$hasGaCode = trim((string) $gacode) !== '';
if ($hasGaCode && $this->isLoginGaCodeLimited($redis, $user->id, $deviceId, $clientIp)) {
$this->clearPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp);
$rs['ret'] = 0;
$rs['need_ga_verify'] = 1;
$rs['msg'] = $this->language == 'true' ? "Too many incorrect authenticator attempts. Please try again in 10 minutes." : "谷歌验证码错误次数过多,请 10 分钟后再试。";
return $response->getBody()->write(json_encode($rs));
}
if (!Totp::verify($user->ga_token, $gacode)) {
if ($hasGaCode) {
$failCount = $this->recordLoginGaCodeFail($redis, $user->id, $deviceId, $clientIp);
if ($failCount >= $this->login_email_code_fail_limit) {
$this->clearPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp);
$rs['ret'] = 0;
$rs['need_ga_verify'] = 1;
$rs['msg'] = $this->language == 'true' ? "Too many incorrect authenticator attempts. Please try again in 10 minutes." : "谷歌验证码错误次数过多,请 10 分钟后再试。";
return $response->getBody()->write(json_encode($rs));
}
} else {
$this->markPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp);
}
$rs['ret'] = 0;
$rs['need_ga_verify'] = 1;
if ($this->language == 'true') {
$rs['msg'] = $hasGaCode ? "Authenticator code is incorrect or expired." : "Please enter the Google Authenticator code for this account.";
} else {
$rs['msg'] = $hasGaCode ? "谷歌验证码不正确或已过期。" : "请输入当前账户的谷歌验证器动态码。";
}
return $response->getBody()->write(json_encode($rs));
}
$this->markTrustedLoginDevice($redis, $user->id, $deviceId, 'ga');
$this->clearLoginGaCodeFail($redis, $user->id, $deviceId, $clientIp);
} else {
$hasEmailCode = trim((string) $emailcode) !== '';
if ($hasEmailCode && $this->isLoginEmailCodeLimited($redis, $user->id, $deviceId, $clientIp)) {
$this->clearPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp);
$rs['ret'] = 0;
$rs['need_email_verify'] = 1;
$rs['msg'] = $this->language == 'true' ? "Too many incorrect email verification attempts. Please try again in 10 minutes." : "邮箱验证码错误次数过多,请 10 分钟后再试。";
return $response->getBody()->write(json_encode($rs));
}
if (!$this->verifyLoginEmailCode($user->email, $emailcode)) {
if ($hasEmailCode) {
$failCount = $this->recordLoginEmailCodeFail($redis, $user->id, $deviceId, $clientIp);
if ($failCount >= $this->login_email_code_fail_limit) {
$this->clearPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp);
$rs['ret'] = 0;
$rs['need_email_verify'] = 1;
$rs['msg'] = $this->language == 'true' ? "Too many incorrect email verification attempts. Please try again in 10 minutes." : "邮箱验证码错误次数过多,请 10 分钟后再试。";
return $response->getBody()->write(json_encode($rs));
}
} else {
$this->markPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp);
}
$rs['ret'] = 0;
$rs['need_email_verify'] = 1;
if ($this->language == 'true') {
$rs['msg'] = $hasEmailCode ? "Email verification code is incorrect or expired." : "This account has not completed email verification on this device. Please verify your email.";
} else {
$rs['msg'] = $hasEmailCode ? "邮箱验证码不正确或已过期。" : "当前账户尚未在此设备完成邮箱验证,请先验证邮箱。";
}
return $response->getBody()->write(json_encode($rs));
}
$this->markTrustedLoginDevice($redis, $user->id, $deviceId, 'email');
$this->clearLoginEmailCodeFail($redis, $user->id, $deviceId, $clientIp);
}
}
if ($redis !== null) {
$this->clearPendingLoginEmailVerifyCaptcha($redis, $email, $deviceId, $clientIp);
}
Auth::login($user->id, $this->login_session_ttl);
$rs['ret'] = 1;
if ($this->language == 'true') {
$rs['msg'] = "Welcome";
} else {
$rs['msg'] = "欢迎进入";
}
$rs['user'] = $user->user_name;
$loginip=new LoginIp();
$loginip->ip=$_SERVER["REMOTE_ADDR"];
$loginip->userid=$user->id;
$loginip->request_domain = $_SERVER['HTTP_HOST'];
$loginip->datetime=time();
$loginip->type=0;
$loginip->save();
return $response->getBody()->write(json_encode($rs));
}
public function sendLoginVerify($request, $response, $next)
{
$email = strtolower((string) $request->getParam('email'));
$passwd = $request->getParam('passwd');
$clientIp = $this->getLoginClientIp();
$deviceId = $this->getLoginDeviceId();
if ($this->isLoginIpForbidden($clientIp)) {
return $response->getBody()->write(json_encode([
'ret' => 0,
'msg' => $this->language == 'true' ? 'Login is blocked from your IP address' : '当前 IP 已被禁止登录',
]));
}
$redis = new RedisClient();
if ($this->isLoginVerifyPasswordLimited($redis, $email, $clientIp)) {
return $response->getBody()->write(json_encode([
'ret' => 0,
'msg' => $this->language == 'true' ? 'Too many attempts. Please try again later.' : '尝试次数过多,请稍后再试。',
]));
}
$user = User::where('email', '=', $email)->first();
if ($user == null || !Hash::checkPassword($user->pass, $passwd)) {
$this->recordLoginVerifyPasswordFail($redis, $email, $clientIp);
return $response->getBody()->write(json_encode([
'ret' => 0,
'msg' => $this->language == 'true' ? 'Email or password is wrong' : '邮箱或密码错误',
]));
}
$this->clearLoginVerifyPasswordFail($redis, $email, $clientIp);
$loginVerifyMethod = $this->loginVerifyMethod($user);
if ($loginVerifyMethod === 'ga') {
return $response->getBody()->write(json_encode([
'ret' => 0,
'need_ga_verify' => 1,
'msg' => $this->language == 'true' ? 'This account uses Google Authenticator. Please enter the authenticator code.' : '当前账户已选择谷歌验证器登录,请输入谷歌验证码。',
]));
}
if (!$this->isLoginEmailVerifyEnabled()) {
return $response->getBody()->write(json_encode([
'ret' => 0,
'msg' => $this->language == 'true' ? 'Email verification is not required' : '当前登录不需要邮箱验证',
]));
}
if ($this->isTrustedLoginDevice($redis, $user->id, $deviceId, 'email')) {
return $response->getBody()->write(json_encode([
'ret' => 0,
'msg' => $this->language == 'true' ? 'Email verification is not required' : '当前登录不需要邮箱验证',
]));
}
$retryAfter = $this->getLoginEmailVerifySendRetryAfter($redis, $email, $deviceId, $clientIp);
if ($retryAfter > 0) {
return $response->getBody()->write(json_encode([
'ret' => 0,
'retry_after' => $retryAfter,
'msg' => $this->language == 'true' ? 'Please try again later' : '请稍后再重新发送验证码',
]));
}
$ipcount = EmailVerify::where('ip', '=', $clientIp)->where('expire_in', '>', time())->count();
if ($ipcount >= (int) CaptchaConfig::get('email_verify_iplimit')) {
return $response->getBody()->write(json_encode([
'ret' => 0,
'msg' => $this->language == 'true' ? 'Too many IP requests' : '当前IP请求过多',
]));
}
$mailcount = EmailVerify::where('email', '=', $email)->where('expire_in', '>', time())->count();
if ($mailcount >= 3) {
return $response->getBody()->write(json_encode([
'ret' => 0,
'msg' => $this->language == 'true' ? 'This email has been requested too many times' : '此电子邮件已请求太多次',
]));
}
$code = (string) random_int(100000, 999999);
$ev = new EmailVerify();
$ev->expire_in = time() + (int) CaptchaConfig::get('email_verify_ttl');
$ev->ip = $clientIp;
$ev->email = $email;
$ev->code = $code;
if (!$ev->save()) {
return $response->getBody()->write(json_encode([
'ret' => 0,
'msg' => $this->language == 'true' ? 'Verification code could not be sent' : '验证码发送失败,请稍后重试',
]));
}
try {
$sent = Mail::send($email, Config::get('appName') . ($this->language === 'true' ? ' - Login verification' : ' - 登录安全验证'), 'auth/verify.tpl', [
"code" => $code,
"expire" => date("Y-m-d H:i:s", time() + (int) CaptchaConfig::get('email_verify_ttl')),
"language" => $this->language,
"scene" => "login",
], [], '登录安全验证');
} catch (\Throwable $exception) {
$sent = false;
}
if (!$sent) {
$ev->delete();
return $response->getBody()->write(json_encode([
'ret' => 0,
'msg' => $this->language == 'true' ? 'Verification code could not be sent' : '验证码发送失败,请稍后重试',
]));
}
$this->markLoginEmailVerifySendCooldown($redis, $email, $deviceId, $clientIp);
return $response->getBody()->write(json_encode([
'ret' => 1,
'retry_after' => 60,
'msg' => $this->language == 'true' ? 'Verification code sent successfully' : '验证码发送成功,请检查邮箱',
]));
}
public function register($request, $response, $next)
{
$query = $request->getQueryParams();
$code = ReferralService::registrationCode($query, Cookie::get('aff_code'));
if ($code === '' && isset($query['code']) && is_scalar($query['code'])) {
// Preserve direct links issued before the eight-character `aff`
// format was introduced; registration still validates the stored
// legacy code inside the transaction.
$code = trim((string) $query['code']);
}
$legacyAffid = isset($query['aff']) && is_scalar($query['aff']) && ctype_digit((string) $query['aff'])
? (int) $query['aff'] : (int) Cookie::get('affid');
if ($code !== '') {
Cookie::set(['aff_code' => $code], time() + 86400 * 30);
} elseif ($legacyAffid > 0) {
Cookie::set(['affid' => (string) $legacyAffid], time() + 86400 * 30);
}
return $this->publicView()->assign('enable_invite_code', $this->enable_invite_code)
->assign('enable_email_verify', CaptchaConfig::get('enable_email_verify'))
->assign('code', $code)->assign('aff_code', $code)->assign('aff', max(0, $legacyAffid))->assign('aff_method', $this->aff_method)
->assign('invite_required', $this->aff_method === 'code')->assign('tos_reg', Config::get('tos_reg'))
->assign('captch_reg', CaptchaConfig::get('captch_reg'))
->assign('cdn', $this->cdn)->assign('backup_cdn', $this->backup_cdn)
->assign('appName', $this->appName)->assign('seo', $this->seo)
->display('auth/register.tpl');
}
public function sendVerify($request, $response, $next)
{
if (CaptchaConfig::get('enable_email_verify')=='true') {
$email = $request->getParam('email');
if (Config::get('enable_register')=='false') {
$res['ret'] = 0;
if ($this->language == 'true') {
$res['msg'] = "Registration is currently suspended";
} else {
$res['msg'] = "目前关闭注册";
}
return $response->getBody()->write(json_encode($res));
}
if ($email=="") {
$res['ret'] = 0;
if ($this->language == 'true') {
$res['msg'] = "Unfilled email address";
} else {
$res['msg'] = "未填写的电子邮件地址";
}
return $response->getBody()->write(json_encode($res));
}
// check email format
if (!Check::isEmailLegal($email)) {
$res['ret'] = 0;
if ($this->language == 'true') {
$res['msg'] = "Email is invalid";
} else {
$res['msg'] = "电子邮件无效";
}
return $response->getBody()->write(json_encode($res));
}
$emailWhitelist = RegistrationEmailWhitelist::configuredRules();
$allowed_domains = $emailWhitelist['domains'];
if ($emailWhitelist['enabled'] && !RegistrationEmailWhitelist::allows($email, $allowed_domains)) {
$res['ret'] = 0;
if ($this->language == 'true') {
$res['msg'] = "The email is invalid. Only the following emails are supported:";
} else {
$res['msg'] = "该电子邮件无效。仅支持以下邮箱:";
}
foreach ($allowed_domains as $domain) {
$res['msg'] .= $domain . PHP_EOL;
}
return $response->getBody()->write(json_encode($res));
}
$user = User::where('email', '=', $email)->first();
if ($user!=null) {
$res['ret'] = 0;
if ($this->language == 'true') {
$res['msg'] = "This email address is already registered";
} else {
$res['msg'] = "该邮箱地址已被注册";
}
return $response->getBody()->write(json_encode($res));
}
$ipcount = EmailVerify::where('ip', '=', $_SERVER["REMOTE_ADDR"])->where('expire_in', '>', time())->count();
if ($ipcount>=(int)CaptchaConfig::get('email_verify_iplimit')) {
$res['ret'] = 0;
if ($this->language == 'true') {
$res['msg'] = "Too many IP requests";
} else {
$res['msg'] = "当前IP请求过多";
}
return $response->getBody()->write(json_encode($res));
}
$mailcount = EmailVerify::where('email', '=', $email)->where('expire_in', '>', time())->count();
if ($mailcount>=3) {
$res['ret'] = 0;
if ($this->language == 'true') {
$res['msg'] = "This email has been requested too many times";
} else {
$res['msg'] = "此电子邮件已请求太多次";
}
return $response->getBody()->write(json_encode($res));
}
$code = (string) random_int(100000, 999999);
$ev = new EmailVerify();
$ev->expire_in = time() + (int) CaptchaConfig::get('email_verify_ttl');
$ev->ip = $_SERVER["REMOTE_ADDR"];
$ev->email = $email;
$ev->code = $code;
if (!$ev->save()) {
$res['ret'] = 0;
$res['msg'] = $this->language === 'true' ? 'Verification code could not be sent.' : '验证码发送失败,请稍后重试。';
return $response->getBody()->write(json_encode($res));
}
$subject = Config::get('appName') . ($this->language === 'true'
? ' - Registration email verification' : ' - 注册邮箱验证');
try {
$sent = Mail::send($email, $subject, 'auth/verify.tpl', [
"code" => $code,
"expire" => date("Y-m-d H:i:s", time() + (int) CaptchaConfig::get('email_verify_ttl')),
"language" => $this->language,
"scene" => "registration",
], [
//BASE_PATH.'/public/assets/email/styles.css'
], '验证邮件');
} catch (\Throwable $exception) {
$sent = false;
}
if (!$sent) {
$ev->delete();
$res['ret'] = 0;
$res['msg'] = $this->language === 'true' ? 'Verification code could not be sent.' : '验证码发送失败,请稍后重试。';
return $response->getBody()->write(json_encode($res));
}
$res['ret'] = 1;
if ($this->language == 'true') {
$res['msg'] = "Verification code sent successfully. Please check your mailbox. If not, check the trash!";
} else {
$res['msg'] = "验证码发送成功。请检查您的邮箱。如果没有,请检查垃圾箱!";
}
return $response->getBody()->write(json_encode($res));
}
return $response->getBody()->write(json_encode([
'ret' => 0,
'msg' => $this->language === 'true' ? 'Email verification is disabled.' : '邮箱验证码已关闭',
]));
}
public function registerHandle($request, $response, $next)
{
Cookie::startSession();
if (Config::get('enable_register', 'true') === 'false') {
return $this->echoJson($response, [
'ret' => 0,
'msg' => $this->publicText('目前关闭注册', 'Registration is currently unavailable.'),
]);
}
$read = static function ($name) use ($request) {
$value = $request->getParam($name, '');
return is_string($value) ? $value : '';
};
if (Config::get('tos_reg') === 'true' && $read('accept_legal') !== 'true') {
return $this->echoJson($response, [
'ret' => 0,
'msg' => $this->publicText(
'请先阅读并同意服务条款和隐私政策',
'Please read and accept the Terms of Service and Privacy Policy.'
),
]);
}
$email = strtolower(trim($read('email')));
$name = trim($read('name'));
$password = $read('passwd');
$code = trim($read('code'));
if (!Check::isEmailLegal($email) || strlen($email) > 254 || $name === '' || mb_strlen($name) > 128) {
return $this->echoJson($response, [
'ret' => 0,
'msg' => $this->publicText('请填写有效的用户名和邮箱', 'Please enter a valid username and email address.'),
]);
}
$whitelist = RegistrationEmailWhitelist::configuredRules();
if ($whitelist['enabled'] && !RegistrationEmailWhitelist::allows($email, $whitelist['domains'])) {
return $this->echoJson($response, [
'ret' => 0,
'msg' => $this->publicText('此邮箱暂不允许注册', 'This email address is not currently allowed to register.'),
]);
}
$error = Hash::newPasswordError($password);
if ($error !== null || $password !== $read('repasswd')) {
$message = $error !== null
? $this->publicText(
$error,
'The password must be 12–72 bytes and include uppercase and lowercase letters, a number, and a symbol.'
)
: $this->publicText('两次密码不一致', 'The passwords do not match.');
return $this->echoJson($response, ['ret' => 0, 'msg' => $message]);
}
if (CaptchaConfig::get('captch_reg') === 'true') {
$expected = isset($_SESSION['captch']) && is_string($_SESSION['captch']) ? strtolower($_SESSION['captch']) : '';
$provided = strtolower(trim($read('captch')));
if ($expected === '' || !hash_equals($expected, $provided)) {
return $this->echoJson($response, [
'ret' => 0,
'msg' => $this->publicText('验证码错误', 'The verification code is incorrect.'),
]);
}
unset($_SESSION['captch']);
}
$connection = (new User())->getConnection();
try {
$connection->transaction(function () use ($read, $email, $name, $password, $code) {
if (User::where('email', $email)->exists()) {
throw new \InvalidArgumentException($this->publicText(
'该邮箱已被注册',
'This email address is already registered.'
));
}
if (CaptchaConfig::get('enable_email_verify') === 'true') {
$verification = EmailVerify::where('email', $email)->where('code', $read('emailcode'))
->where('expire_in', '>', time())->lockForUpdate()->first();
if ($verification === null) {
throw new \InvalidArgumentException($this->publicText(
'邮箱验证码错误或已过期',
'The email verification code is incorrect or expired.'
));
}
EmailVerify::where('email', $email)->delete();
}
$refBy = 0;
$invitation = null;
$aff = trim($read('aff'));
$affCode = ReferralService::normalizeCode($aff);
if ($affCode === '') {
$affCode = ReferralService::normalizeCode($code);
}
if ($affCode !== '') {
$invitation = ReferralService::findInvitation($affCode, true);
if ($invitation === null) {
throw new \InvalidArgumentException($this->publicText(
'推广链接无效',
'The referral link is invalid.'
));
}
$refBy = (int) $invitation->user_id;
} elseif ($code !== '' && $this->aff_method === 'code') {
// Accept legacy, longer invite codes already issued by
// older installations while new links stay eight chars.
$invitation = InviteCode::where('code', $code)->lockForUpdate()->first();
if ($invitation === null) {
throw new \InvalidArgumentException($this->publicText(
'邀请码无效',
'The invitation code is invalid.'
));
}
$refBy = (int) $invitation->user_id;
} elseif ($this->aff_method === 'code') {
throw new \InvalidArgumentException($this->publicText(
'推广链接或邀请码无效',
'A valid referral link or invitation code is required.'
));
} else {
if ($aff !== '' && (!ctype_digit($aff) || (int) $aff < 0)) {
throw new \InvalidArgumentException($this->publicText(
'邀请链接无效',
'The invitation link is invalid.'
));
}
$refBy = (int) $aff;
}
if ($refBy > 0) {
$referrer = User::where('id', $refBy)->lockForUpdate()->first();
if ($referrer === null || !$referrer->canInvite()) {
throw new \InvalidArgumentException($this->publicText(
'邀请服务暂不可用',
'The invitation service is currently unavailable.'
));
}
// New eight-character promotion links are reusable and do
// not consume the legacy invite quota. Older, longer
// `code` invitations retain their one-time quota rules.
if ($invitation !== null && $affCode === '') {
if ((int) $referrer->invite_num < 1) {
throw new \InvalidArgumentException($this->publicText(
'邀请次数不足',
'The inviter has no invitation quota remaining.'
));
}
$referrer->invite_num = (int) $referrer->invite_num - 1;
$referrer->save();
}
}
$user = new User();
$user->user_name = (new AntiXSS())->xss_clean($name);
$user->email = $email;
$user->pass = Hash::passwordHash($password);
$user->enable = 1;
$user->is_admin = 0;
$user->money = 0;
$user->invite_num = max(0, (int) Config::get('inviteNum', 0));
$user->ref_by = $refBy;
$user->reg_date = date('Y-m-d H:i:s');
$user->reg_ip = $this->getLoginClientIp();
$user->theme = 'venix';
$user->save();
ReferralService::codeForUser($user);
if ($invitation !== null && (int) $invitation->user_id === 0) {
$invitation->delete();
}
}, 3);
} catch (\InvalidArgumentException $exception) {
return $this->echoJson($response, ['ret' => 0, 'msg' => $exception->getMessage()]);
} catch (\Throwable $exception) {
error_log('Account registration failed: ' . get_class($exception));
return $this->echoJson($response, [
'ret' => 0,
'msg' => $this->publicText('注册失败,请稍后重试', 'Registration failed. Please try again later.'),
]);
}
return $this->echoJson($response, [
'ret' => 1,
'msg' => $this->publicText('注册成功', 'Registration completed successfully.'),
]);
}
public function logout($request, $response, $next)
{
Auth::logout();
$newResponse = $response->withStatus(302)->withHeader('Location', '/');
return $newResponse;
}
}