feat: TOTP 2차 인증, 관리자 메뉴/대시보드 및 의존성 반영
- robthree/twofactorauth, Auth 설정·TotpService·2FA 뷰·라우트 - member TOTP 컬럼 DDL(login_tables, member_add_totp.sql) - 관리자 메뉴·레이아웃·필터·대시보드 등 연관 변경 - env 샘플에 auth.requireTotp 주석 Made-with: Cursor
This commit is contained in:
@@ -2,10 +2,12 @@
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Libraries\TotpService;
|
||||
use App\Models\LocalGovernmentModel;
|
||||
use App\Models\MemberApprovalRequestModel;
|
||||
use App\Models\MemberLogModel;
|
||||
use App\Models\MemberModel;
|
||||
use CodeIgniter\HTTP\RedirectResponse;
|
||||
|
||||
class Auth extends BaseController
|
||||
{
|
||||
@@ -50,8 +52,8 @@ class Auth extends BaseController
|
||||
$loginId = trim($this->request->getPost('login_id'));
|
||||
$password = $this->request->getPost('password');
|
||||
|
||||
$memberModel = model(MemberModel::class);
|
||||
$member = $memberModel->findByLoginId($loginId);
|
||||
$memberModel = model(MemberModel::class);
|
||||
$member = $memberModel->findByLoginId($loginId);
|
||||
$approvalModel = model(MemberApprovalRequestModel::class);
|
||||
|
||||
$logData = $this->buildLogData($loginId, $member?->mb_idx);
|
||||
@@ -123,35 +125,177 @@ class Auth extends BaseController
|
||||
}
|
||||
}
|
||||
|
||||
// 로그인 성공
|
||||
$sessionData = [
|
||||
'mb_idx' => $member->mb_idx,
|
||||
'mb_id' => $member->mb_id,
|
||||
'mb_name' => $member->mb_name,
|
||||
'mb_level' => $member->mb_level,
|
||||
'mb_lg_idx' => $member->mb_lg_idx ?? null,
|
||||
'logged_in' => true,
|
||||
];
|
||||
session()->set($sessionData);
|
||||
if ($this->needsTotpStep($member)) {
|
||||
$this->beginPending2faSession((int) $member->mb_idx);
|
||||
$enabled = (int) ($member->mb_totp_enabled ?? 0) === 1;
|
||||
if ($enabled) {
|
||||
return redirect()->to(site_url('login/two-factor'));
|
||||
}
|
||||
session()->set('pending_totp_setup', true);
|
||||
|
||||
$memberModel->update($member->mb_idx, [
|
||||
'mb_latestdate' => date('Y-m-d H:i:s'),
|
||||
'mb_login_fail_count' => 0,
|
||||
'mb_locked_until' => null,
|
||||
return redirect()->to(site_url('login/totp-setup'));
|
||||
}
|
||||
|
||||
return $this->completeLogin($member, $logData);
|
||||
}
|
||||
|
||||
public function showTwoFactor()
|
||||
{
|
||||
if (session()->get('logged_in')) {
|
||||
return redirect()->to('/');
|
||||
}
|
||||
$member = $this->ensurePending2faContext();
|
||||
if ($member === null) {
|
||||
return redirect()->to(site_url('login'))->with('error', '로그인 세션이 만료되었습니다. 다시 로그인해 주세요.');
|
||||
}
|
||||
if (session()->get('pending_totp_setup')) {
|
||||
return redirect()->to(site_url('login/totp-setup'));
|
||||
}
|
||||
if ((int) ($member->mb_totp_enabled ?? 0) !== 1) {
|
||||
return redirect()->to(site_url('login/totp-setup'));
|
||||
}
|
||||
|
||||
return view('auth/login_two_factor', [
|
||||
'memberId' => $member->mb_id,
|
||||
]);
|
||||
}
|
||||
|
||||
$this->insertMemberLog($logData, true, '로그인 성공', $member->mb_idx);
|
||||
|
||||
// 지자체 관리자 → 관리자 대시보드로 이동
|
||||
if ((int) $member->mb_level === \Config\Roles::LEVEL_LOCAL_ADMIN) {
|
||||
return redirect()->to(site_url('admin'))->with('success', '로그인되었습니다.');
|
||||
public function verifyTwoFactor()
|
||||
{
|
||||
if (session()->get('logged_in')) {
|
||||
return redirect()->to('/');
|
||||
}
|
||||
// super admin → 지자체 선택 페이지로 이동 (선택 후 관리자 페이지 사용)
|
||||
if ((int) $member->mb_level === \Config\Roles::LEVEL_SUPER_ADMIN) {
|
||||
return redirect()->to(site_url('admin/select-local-government'))->with('success', '로그인되었습니다.');
|
||||
$member = $this->ensurePending2faContext();
|
||||
if ($member === null) {
|
||||
return redirect()->to(site_url('login'))->with('error', '로그인 세션이 만료되었습니다. 다시 로그인해 주세요.');
|
||||
}
|
||||
if (session()->get('pending_totp_setup') || (int) ($member->mb_totp_enabled ?? 0) !== 1) {
|
||||
return redirect()->to(site_url('login/totp-setup'));
|
||||
}
|
||||
|
||||
return redirect()->to(site_url('/'))->with('success', '로그인되었습니다.');
|
||||
$rules = [
|
||||
'totp_code' => 'required|exact_length[6]|numeric',
|
||||
];
|
||||
$messages = [
|
||||
'totp_code' => [
|
||||
'required' => '인증 코드 6자리를 입력해 주세요.',
|
||||
'exact_length' => '인증 코드는 6자리 숫자입니다.',
|
||||
'numeric' => '인증 코드는 숫자만 입력해 주세요.',
|
||||
],
|
||||
];
|
||||
if (! $this->validate($rules, $messages)) {
|
||||
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
|
||||
}
|
||||
|
||||
$code = (string) $this->request->getPost('totp_code');
|
||||
helper('pii_encryption');
|
||||
$secret = pii_decrypt((string) ($member->mb_totp_secret ?? ''));
|
||||
if ($secret === '') {
|
||||
$this->clearPending2faSession();
|
||||
|
||||
return redirect()->to(site_url('login'))->with('error', '2차 인증 설정이 올바르지 않습니다. 관리자에게 문의해 주세요.');
|
||||
}
|
||||
|
||||
$totp = new TotpService();
|
||||
if (! $totp->verify($secret, $code)) {
|
||||
return $this->handleTotpFailure($member, $this->buildLogData($member->mb_id, (int) $member->mb_idx));
|
||||
}
|
||||
|
||||
return $this->completeLogin($member, $this->buildLogData($member->mb_id, (int) $member->mb_idx));
|
||||
}
|
||||
|
||||
public function showTotpSetup()
|
||||
{
|
||||
if (session()->get('logged_in')) {
|
||||
return redirect()->to('/');
|
||||
}
|
||||
$member = $this->ensurePending2faContext();
|
||||
if ($member === null) {
|
||||
return redirect()->to(site_url('login'))->with('error', '로그인 세션이 만료되었습니다. 다시 로그인해 주세요.');
|
||||
}
|
||||
if (! session()->get('pending_totp_setup')) {
|
||||
if ((int) ($member->mb_totp_enabled ?? 0) === 1) {
|
||||
return redirect()->to(site_url('login/two-factor'));
|
||||
}
|
||||
|
||||
return redirect()->to(site_url('login'));
|
||||
}
|
||||
|
||||
$totp = new TotpService();
|
||||
$secret = session()->get('pending_totp_secret');
|
||||
if (! is_string($secret) || $secret === '') {
|
||||
$secret = $totp->createSecret();
|
||||
session()->set('pending_totp_secret', $secret);
|
||||
}
|
||||
|
||||
$qrDataUri = null;
|
||||
try {
|
||||
$qrDataUri = $totp->getQrDataUri((string) $member->mb_id, $secret);
|
||||
} catch (\Throwable) {
|
||||
$qrDataUri = null;
|
||||
}
|
||||
|
||||
return view('auth/totp_setup', [
|
||||
'memberId' => $member->mb_id,
|
||||
'qrDataUri' => $qrDataUri,
|
||||
'secret' => $secret,
|
||||
]);
|
||||
}
|
||||
|
||||
public function completeTotpSetup()
|
||||
{
|
||||
if (session()->get('logged_in')) {
|
||||
return redirect()->to('/');
|
||||
}
|
||||
$member = $this->ensurePending2faContext();
|
||||
if ($member === null) {
|
||||
return redirect()->to(site_url('login'))->with('error', '로그인 세션이 만료되었습니다. 다시 로그인해 주세요.');
|
||||
}
|
||||
if (! session()->get('pending_totp_setup')) {
|
||||
return redirect()->to(site_url('login/two-factor'));
|
||||
}
|
||||
|
||||
$rules = [
|
||||
'totp_code' => 'required|exact_length[6]|numeric',
|
||||
];
|
||||
$messages = [
|
||||
'totp_code' => [
|
||||
'required' => '인증 코드 6자리를 입력해 주세요.',
|
||||
'exact_length' => '인증 코드는 6자리 숫자입니다.',
|
||||
'numeric' => '인증 코드는 숫자만 입력해 주세요.',
|
||||
],
|
||||
];
|
||||
if (! $this->validate($rules, $messages)) {
|
||||
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
|
||||
}
|
||||
|
||||
$secret = session()->get('pending_totp_secret');
|
||||
if (! is_string($secret) || $secret === '') {
|
||||
return redirect()->to(site_url('login/totp-setup'))->with('error', '설정 정보가 없습니다. 페이지를 새로고침해 주세요.');
|
||||
}
|
||||
|
||||
$code = (string) $this->request->getPost('totp_code');
|
||||
$totp = new TotpService();
|
||||
if (! $totp->verify($secret, $code)) {
|
||||
return $this->handleTotpFailure($member, $this->buildLogData($member->mb_id, (int) $member->mb_idx));
|
||||
}
|
||||
|
||||
helper('pii_encryption');
|
||||
model(MemberModel::class)->update((int) $member->mb_idx, [
|
||||
'mb_totp_secret' => pii_encrypt($secret),
|
||||
'mb_totp_enabled' => 1,
|
||||
]);
|
||||
session()->remove('pending_totp_setup');
|
||||
session()->remove('pending_totp_secret');
|
||||
|
||||
$fresh = model(MemberModel::class)->find((int) $member->mb_idx);
|
||||
if ($fresh === null) {
|
||||
$this->clearPending2faSession();
|
||||
|
||||
return redirect()->to(site_url('login'))->with('error', '회원 정보를 다시 확인할 수 없습니다.');
|
||||
}
|
||||
|
||||
return $this->completeLogin($fresh, $this->buildLogData($fresh->mb_id, (int) $fresh->mb_idx));
|
||||
}
|
||||
|
||||
public function logout()
|
||||
@@ -182,6 +326,7 @@ class Auth extends BaseController
|
||||
}
|
||||
}
|
||||
|
||||
$this->clearPending2faSession();
|
||||
session()->destroy();
|
||||
|
||||
return redirect()->to('login')->with('success', '로그아웃되었습니다.');
|
||||
@@ -298,6 +443,130 @@ class Auth extends BaseController
|
||||
return redirect()->to('login')->with('success', '회원가입이 완료되었습니다. 관리자 승인 후 로그인 가능합니다.');
|
||||
}
|
||||
|
||||
private function needsTotpStep(object $member): bool
|
||||
{
|
||||
if (! config('Auth')->requireTotp) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return \Config\Roles::requiresTotp((int) $member->mb_level);
|
||||
}
|
||||
|
||||
private function beginPending2faSession(int $mbIdx): void
|
||||
{
|
||||
session()->set([
|
||||
'pending_2fa' => true,
|
||||
'pending_mb_idx' => $mbIdx,
|
||||
'pending_2fa_started' => time(),
|
||||
'totp_attempts' => 0,
|
||||
]);
|
||||
session()->remove('pending_totp_setup');
|
||||
session()->remove('pending_totp_secret');
|
||||
}
|
||||
|
||||
private function clearPending2faSession(): void
|
||||
{
|
||||
session()->remove([
|
||||
'pending_2fa',
|
||||
'pending_mb_idx',
|
||||
'pending_2fa_started',
|
||||
'pending_totp_setup',
|
||||
'pending_totp_secret',
|
||||
'totp_attempts',
|
||||
]);
|
||||
}
|
||||
|
||||
private function pending2faExpired(): bool
|
||||
{
|
||||
$started = (int) session()->get('pending_2fa_started');
|
||||
if ($started <= 0) {
|
||||
return true;
|
||||
}
|
||||
$ttl = config('Auth')->pending2faTtlSeconds;
|
||||
|
||||
return (time() - $started) > $ttl;
|
||||
}
|
||||
|
||||
private function ensurePending2faContext(): ?object
|
||||
{
|
||||
if (! session()->get('pending_2fa')) {
|
||||
return null;
|
||||
}
|
||||
if ($this->pending2faExpired()) {
|
||||
$this->clearPending2faSession();
|
||||
|
||||
return null;
|
||||
}
|
||||
$mbIdx = (int) session()->get('pending_mb_idx');
|
||||
if ($mbIdx <= 0) {
|
||||
$this->clearPending2faSession();
|
||||
|
||||
return null;
|
||||
}
|
||||
$member = model(MemberModel::class)->find($mbIdx);
|
||||
if ($member === null) {
|
||||
$this->clearPending2faSession();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $member;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $logData
|
||||
*/
|
||||
private function handleTotpFailure(object $member, array $logData): RedirectResponse
|
||||
{
|
||||
$this->insertMemberLog($logData, false, '2차 인증 실패', (int) $member->mb_idx);
|
||||
$attempts = (int) session()->get('totp_attempts') + 1;
|
||||
session()->set('totp_attempts', $attempts);
|
||||
$max = config('Auth')->totpMaxAttempts;
|
||||
if ($attempts >= $max) {
|
||||
$this->clearPending2faSession();
|
||||
|
||||
return redirect()->to(site_url('login'))->with('error', "인증 코드가 {$max}회 틀려 세션이 종료되었습니다. 처음부터 로그인해 주세요.");
|
||||
}
|
||||
|
||||
return redirect()->back()
|
||||
->withInput()
|
||||
->with('error', '인증 코드가 올바르지 않습니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $logData
|
||||
*/
|
||||
private function completeLogin(object $member, array $logData): RedirectResponse
|
||||
{
|
||||
$this->clearPending2faSession();
|
||||
$sessionData = [
|
||||
'mb_idx' => $member->mb_idx,
|
||||
'mb_id' => $member->mb_id,
|
||||
'mb_name' => $member->mb_name,
|
||||
'mb_level' => $member->mb_level,
|
||||
'mb_lg_idx' => $member->mb_lg_idx ?? null,
|
||||
'logged_in' => true,
|
||||
];
|
||||
session()->set($sessionData);
|
||||
|
||||
model(MemberModel::class)->update($member->mb_idx, [
|
||||
'mb_latestdate' => date('Y-m-d H:i:s'),
|
||||
'mb_login_fail_count' => 0,
|
||||
'mb_locked_until' => null,
|
||||
]);
|
||||
|
||||
$this->insertMemberLog($logData, true, '로그인 성공', (int) $member->mb_idx);
|
||||
|
||||
if ((int) $member->mb_level === \Config\Roles::LEVEL_LOCAL_ADMIN) {
|
||||
return redirect()->to(site_url('admin'))->with('success', '로그인되었습니다.');
|
||||
}
|
||||
if (\Config\Roles::isSuperAdminEquivalent((int) $member->mb_level)) {
|
||||
return redirect()->to(site_url('admin/select-local-government'))->with('success', '로그인되었습니다.');
|
||||
}
|
||||
|
||||
return redirect()->to(site_url('/'))->with('success', '로그인되었습니다.');
|
||||
}
|
||||
|
||||
private function buildLogData(string $mbId, ?int $mbIdx): array
|
||||
{
|
||||
return [
|
||||
|
||||
Reference in New Issue
Block a user