Files
Gnuboard7/app/Providers/AppServiceProvider.php
T
HeuJung 50007d5cc6 fix(auth): 2단계 인증을 켠 사이트의 로그인 흐름 구현
2단계 인증은 7.0.6 에서 서버측이 갖춰졌지만 인증번호를 입력할 화면이 어느 버전에도
없었다. 그래서 그 설정을 켠 사이트는 관리자를 포함한 전원이 로그인할 수 없었다.

원인은 `POST /api/auth/login` 이 조건에 따라 **다른 형태의 200** 을 돌려준다는 것이다.
평소에는 `{token, user}` 지만 2단계 인증이 켜져 있으면 `{two_factor_required,
challenge_id, ...}` 를 돌려준다. 프론트는 앞의 형태만 선언하고 `response.data.user.language`
를 바로 읽었으므로 그 자리에서 TypeError 가 났고, 영문 원문이 로그인 화면에 그대로 노출됐다.
서버는 정상 응답했으므로 서버 로그에는 아무 흔적도 남지 않는다.

이어서 `setToken(undefined)` 가 `localStorage` 에 문자열 `"undefined"` 를 남겼다.
이 값은 truthy 라 이후 모든 요청이 `Bearer undefined` 로 나가 401 이 되고, 사용자에게는
「세션이 만료되었습니다」로 보인다. 관리자 로그인은 한발 더 나가 `null->isAdmin` 으로
500 이 되어, 설정을 되돌릴 수단까지 함께 사라졌다.

## 구현

- 로그인 응답을 판별 유니온(`LoginResult`)으로 표현하고, 형태를 판별한 뒤에 읽는다.
 `ApiClient.setToken` 은 비어 있지 않은 문자열만 저장한다.
- 사용자·관리자 로그인 화면에 인증번호 입력 단계를 추가했다. 같은 카드 안에서 넘어가며
 「인증번호 다시 받기」와 「처음부터」를 제공한다. 관리자 판정은 코드 확인에 성공한 뒤에
 수행하고, 거부할 때는 그 직전에 발급된 토큰을 회수한다.
- 재발송(`login/two-factor/resend`)은 기존 challenge 를 취소하고 새로 발행한다. 유효한
 코드를 여러 개 살려 두면 대입 시도의 표적이 넓어진다.
- 인증번호를 보내지 못하면 401 이 아니라 503 으로 답한다. 자격 증명은 올바른데 401 로
 뭉개면 사용자는 비밀번호를 의심하며 같은 시도를 반복하고, 운영자는 메일 설정이 깨진
 사실을 알 방법이 없다.
- 공개 본인인증 경로(`identity/verify`·`cancel`)가 로그인 목적의 challenge 를 소진하지
 못하도록 403 게이트를 세웠다. 소진되면 그 challenge 로 영영 로그인할 수 없다.
- 로그인 시도 제한 429 응답이 다국어 문구를 싣도록 했다(종전에는 프레임워크 기본 영문).
- 다국어 파라미터에서 파이프 표현식이 평가되지 않아 「유효시간 까지」처럼 값이 빠지던
 문제를 함께 고쳤다. 같은 결함이 문의 목록 화면에도 있었다.

## 이번 점검에서 함께 고친 것

- 계정 잠금(423)·발송 실패(503) 응답이 사용자·관리자 컨트롤러에 동일하게 복제돼 있었고
 그 주석 자신은 "단일 지점에서 만든다" 고 적혀 있었다. 페이로드에 필드가 하나 추가되면
 한쪽만 따라가 같은 실패를 두 화면이 다르게 안내하게 된다 — 트레이트로 통합했다.
- 테스트가 개발자 자신의 사이트 설정을 읽고 있었다. 2단계 인증을 켜 둔 환경에서는 로그인
 성공을 전제한 테스트가 503 으로 깨지는데 실패 메시지가 원인을 가리키지도 않는다.
 같은 결함군을 위해 이미 존재하던 단일 지점에 그 축을 추가했다.

## 버전

코어 7.0.11 · sirsoft-basic 1.1.4 · sirsoft-admin_basic 1.0.9 ·
번들 일본어팩 3종 · 템플릿 엔진 engine-v1.65.0.
2026-09-07 17:08:14 +09:00

195 lines
7.4 KiB
PHP

<?php
namespace App\Providers;
use App\Contracts\Extension\HookManagerInterface;
use App\Contracts\Extension\ModuleManagerInterface;
use App\Contracts\Extension\PluginManagerInterface;
use App\Contracts\Notifications\ChannelReadinessCheckerInterface;
use App\Extension\HookManager;
use App\Extension\ModuleManager;
use App\Extension\PluginManager;
use App\Helpers\ResponseHelper;
use App\Http\View\Composers\TemplateComposer;
use App\Http\View\Composers\UserTemplateComposer;
use App\Notifications\NotificationChannelManager;
use App\Services\ChannelReadinessService;
use App\Services\GeoIpService;
use App\Support\Routing\DualExtensionRoute;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Http\Request;
use Illuminate\Notifications\ChannelManager;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Laravel\Boost\BoostServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
// 자산 URL 이중 모드 Route 매크로 (dualSuffix / dualAsset).
// boot() 가 아니라 register() 에서 등록하는 이유: 라우트 파일은 프레임워크의
// 라우팅 부트스트랩(boot 단계)에서 로드되므로, 프로바이더 간 boot 순서에
// 의존하면 매크로 미정의 시점에 라우트가 로드될 수 있다. 모든 프로바이더의
// register() 는 어떤 boot() 보다 먼저 실행되므로 여기가 유일하게 안전한 지점이다.
DualExtensionRoute::register();
// NOTE: Faker 부재 시 FakerShim 대체는 app/Support/SampleData/bootstrap.php 에서 처리
// (composer autoload.files 진입점 — vendor/autoload.php 로드 직후 실행되어
// Laravel 의 fake() 헬퍼 정의 시점에 \Faker\Factory 가 이미 alias 되어 있음)
// 알림 발송 공통 디스패처 — 채널 독립 발송 + 발송 전후 G7 훅 실행
$this->app->singleton(
ChannelManager::class,
fn ($app) => new NotificationChannelManager($app)
);
// 채널 Readiness 검증 — 미설정 채널 발송 사전 차단
$this->app->singleton(
ChannelReadinessCheckerInterface::class,
ChannelReadinessService::class
);
// TODO: TemplateManagerInterface 바인딩을 추가해야 함
// PluginManagerInterface 바인딩
$this->app->bind(
PluginManagerInterface::class,
PluginManager::class
);
// ModuleManagerInterface 바인딩
$this->app->bind(
ModuleManagerInterface::class,
ModuleManager::class
);
// HookManagerInterface 바인딩
$this->app->bind(
HookManagerInterface::class,
HookManager::class
);
// GeoIpService 싱글톤 등록
$this->app->singleton(GeoIpService::class);
// Laravel Boost (개발 전용 - dont-discover 대상, 클래스 존재 시에만 등록)
if (class_exists(BoostServiceProvider::class)) {
$this->app->register(BoostServiceProvider::class);
}
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Schema::defaultStringLength(191);
// View Composer 등록
View::composer('admin', TemplateComposer::class);
View::composer('app', UserTemplateComposer::class);
// SQL 쿼리 로그 설정
$this->configureSqlQueryLogging();
// 아웃바운드 HTTP 프록시 설정
$this->configureOutboundProxy();
// 로그인 라우트 per-IP 백업 throttle — 보안 환경설정의 per-account 잠금과 2중 방어.
// 존재하지 않는 계정에 대한 brute-force / 동일 IP 의 다른 계정 시도까지 차단.
$this->configureLoginRateLimiter();
}
/**
* 로그인 엔드포인트(`/api/auth/login`, `/api/auth/admin/login`) 의 per-IP RateLimiter 를 등록합니다.
*
* 보안 환경설정 `security.max_login_attempts` 에 비례하여 분당 허용량을 산출하되
* 최소 30 회/분 을 보장 (정상 사용자 오타/타이핑 실수에 대비). 설정 조회 실패 시
* 기본값 60 회/분 으로 폴백 — 부팅 안전성 (마이그레이션 전 진입) 확보.
*/
private function configureLoginRateLimiter(): void
{
RateLimiter::for('auth-login', function (Request $request) {
try {
$perAccount = (int) g7_core_settings('security.max_login_attempts', 5);
$maxPerMinute = max(30, $perAccount * 6);
} catch (\Throwable $e) {
$maxPerMinute = 60;
}
// 기본 응답은 영문 "Too Many Attempts." 이다 — 로그인 화면은 이 문구를
// 그대로 노출하므로 다국어 키로 갈아끼운다.
return Limit::perMinute($maxPerMinute)
->by($request->ip())
->response(function (Request $request, array $headers) {
return ResponseHelper::error(
'auth.too_many_attempts',
429,
null,
['seconds' => (int) ($headers['Retry-After'] ?? 60)]
)->withHeaders($headers);
});
});
}
/**
* 아웃바운드 HTTP 프록시를 설정합니다.
*
* 환경설정에 프록시가 지정되어 있으면 `Http::` 파사드로 나가는 모든 요청이 그 프록시를
* 경유합니다. 결제 승인, 코어 업데이트 조회, GeoIP 내려받기, 알림 웹훅 등 확장이 보내는
* 요청까지 함께 적용되므로, 확장 코드를 고치지 않고도 출발지 IP 를 바꿀 수 있습니다.
*
* 적용 여부 판정은 `App\Support\OutboundProxy` 가 소유하며, 이 메서드는 판정 결과만
* 소비합니다 — 디버그 모드 게이트를 여기서 다시 검사하지 않는 이유입니다.
*
* 개별 요청이 `withOptions(['proxy' => ...])` 로 지정한 값은 전역 옵션보다 우선합니다.
*/
private function configureOutboundProxy(): void
{
$proxy = config('g7.outbound_proxy');
if (empty($proxy)) {
return;
}
Http::globalOptions(['proxy' => $proxy]);
}
/**
* SQL 쿼리 로깅을 설정합니다.
*
* 환경설정에서 sql_query_log가 활성화된 경우
* 모든 SQL 쿼리를 storage/logs/query.log에 기록합니다.
*/
private function configureSqlQueryLogging(): void
{
if (! config('g7.sql_query_log', false)) {
return;
}
DB::listen(function (QueryExecuted $query) {
$sql = $query->sql;
$bindings = $query->bindings;
$time = $query->time;
// 바인딩 값을 SQL에 삽입하여 완전한 쿼리 생성
foreach ($bindings as $binding) {
$value = is_numeric($binding) ? $binding : "'{$binding}'";
$sql = preg_replace('/\?/', (string) $value, $sql, 1);
}
Log::channel('query')->info("Query ({$time}ms): {$sql}");
});
}
}