<?php
// 登录安全增强
function enhanceLoginSecurity() {
    // 1. 登录失败次数限制
    $maxAttempts = 5;
    $lockoutTime = 900; // 15分钟
    
    // 2. IP 白名单/黑名单
    $allowedIPs = []; // 配置允许的IP
    $blockedIPs = []; // 配置阻止的IP
    
    // 3. 设备指纹检测
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    $acceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
    $deviceFingerprint = md5($userAgent . $acceptLanguage);
    
    // 4. 异地登录检测
    function detectSuspiciousLogin($uid, $currentIP) {
        global $DB;
        
        // 获取最近登录记录
        $lastLogin = $DB->getRow("SELECT * FROM pre_login_log WHERE uid = :uid ORDER BY created_at DESC LIMIT 1", [':uid' => $uid]);
        
        if ($lastLogin) {
            $lastIP = $lastLogin['ip'];
            $lastTime = strtotime($lastLogin['created_at']);
            $timeDiff = time() - $lastTime;
            
            // 检查IP地理位置变化
            if ($lastIP !== $currentIP && $timeDiff < 3600) { // 1小时内IP变化
                return true;
            }
        }
        
        return false;
    }
    
    // 5. 记录登录日志
    function logLoginAttempt($uid, $ip, $status, $userAgent = '') {
        global $DB;
        
        $DB->exec("INSERT INTO pre_login_log (uid, ip, status, user_agent, created_at) 
                  VALUES (:uid, :ip, :status, :user_agent, NOW())", [
            ':uid' => $uid,
            ':ip' => $ip,
            ':status' => $status,
            ':user_agent' => $userAgent
        ]);
    }
    
    // 6. 双因素认证（可选）
    function enableTwoFactorAuth($uid) {
        // 集成 Google Authenticator 或短信验证
        return true;
    }
}

// 创建登录日志表（如果不存在）
function createLoginLogTable() {
    global $DB;
    
    $sql = "CREATE TABLE IF NOT EXISTS `pre_login_log` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `uid` int(11) NOT NULL,
        `ip` varchar(45) NOT NULL,
        `status` tinyint(1) NOT NULL COMMENT '0=失败,1=成功',
        `user_agent` text,
        `created_at` datetime NOT NULL,
        PRIMARY KEY (`id`),
        KEY `idx_uid` (`uid`),
        KEY `idx_ip` (`ip`),
        KEY `idx_created_at` (`created_at`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
    
    $DB->exec($sql);
}
?>