diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..7ba0d09 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,40 @@ +# Git +.git/ +.gitignore +.gitattributes + +# 文档 +*.md +!README.md + +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# Node +node_modules/ +frontend/node_modules/ +frontend/dist/ + +# PHP +vendor/ +backend/vendor/ +backend/.env +backend/storage/cache/* +backend/storage/logs/* +backend/tests/ +backend/tmp_*.php +backend/composer.lock + +# Docker +docker-compose.yml +.dockerignore +.env.docker +deploy.sh + +# OS +.DS_Store +Thumbs.db +*.log diff --git a/.env.docker b/.env.docker new file mode 100644 index 0000000..8f51936 --- /dev/null +++ b/.env.docker @@ -0,0 +1,21 @@ +# Docker Compose 环境变量 +# 复制为 .env 并按需修改 + +# 访问地址 +APP_URL=http://localhost:8080 + +# 数据库 +MYSQL_ROOT_PASSWORD=root_secret_change_me +DB_NAME=card_auth +DB_USER=card_auth +DB_PASS=card_auth_pass + +# JWT 密钥(留空则自动生成随机密钥,但容器重启会变) +# 生成方式: openssl rand -base64 48 +JWT_SECRET= + +# 支付(可选) +PAYMENT_TYPE=epay +PAYMENT_API_URL= +PAYMENT_APP_ID= +PAYMENT_APP_KEY= diff --git a/.gitignore b/.gitignore index 52d857b..0c7c6d9 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,10 @@ # 后端 /backend/.env +/.env /backend/storage/cache/* +/backend/storage/logs/* +!/backend/storage/logs/.gitkeep /backend/vendor/ # 前端 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d004c1b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,59 @@ +# ============================================ +# CardAuth Docker - Multi-stage Build +# ============================================ + +# Stage 1: 前端构建 +FROM node:18-alpine AS frontend-builder +WORKDIR /app/frontend +COPY frontend/package*.json ./ +RUN npm ci --registry=https://registry.npmmirror.com +COPY frontend/ ./ +RUN npm run build + +# Stage 2: PHP 运行时 +FROM php:8.1-fpm-alpine + +# 安装系统依赖 & PHP 扩展 +RUN set -ex \ + && apk add --no-cache \ + nginx \ + supervisor \ + curl \ + tzdata \ + netcat-openbsd \ + && cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ + && echo "Asia/Shanghai" > /etc/timezone \ + && docker-php-ext-install -j$(nproc) pdo pdo_mysql bcmath + +# Composer +COPY --from=composer:2 /usr/bin/composer /usr/bin/composer + +# 后端代码 +WORKDIR /var/www +COPY backend/composer.json backend/composer.lock* ./ +RUN composer install --no-dev --optimize-autoloader --no-interaction --no-scripts +COPY backend/ ./ + +# 前端构建产物 +COPY --from=frontend-builder /app/frontend/dist/ ./public/ + +# 权限 +RUN set -ex \ + && mkdir -p storage/cache storage/logs \ + && chown -R www-data:www-data storage \ + && chmod -R 775 storage \ + && rm -rf tests .phpunit.cache + +# Nginx 配置 +COPY docker/nginx.conf /etc/nginx/http.d/default.conf + +# Supervisor 配置 (管理 Nginx + PHP-FPM) +COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf + +# 入口脚本 +COPY docker/entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh + +EXPOSE 80 + +ENTRYPOINT ["/entrypoint.sh"] diff --git a/README.md b/README.md index d63d2f8..5446322 100644 --- a/README.md +++ b/README.md @@ -40,43 +40,119 @@ ## 快速开始 -### 环境要求 -- PHP 7.4+(需启用 PDO、PDO_MySQL) -- MySQL 8.0+ -- Node.js 16+ +### 方式一:Docker 部署(推荐) -### 1. 初始化数据库 +```bash +# 1. 配置环境变量 +cp .env.docker .env +# 编辑 .env,设置 JWT_SECRET 和数据库密码 + +# 2. 一键启动 +docker compose up -d + +# 3. 访问 +http://localhost:8080 +``` + +首次启动自动完成:前端构建 → 数据库初始化 → Nginx + PHP-FPM 启动。 + +### 方式二:传统部署 + +#### 环境要求 +- Linux 服务器(CentOS 7+ / Ubuntu 18+ / Debian 10+) +- Nginx 1.18+ +- PHP 8.1+(需启用 PDO、PDO_MySQL、mbstring、bcmath) +- PHP-FPM +- MySQL 8.0+ +- Node.js 18+(仅构建阶段需要,部署后不需要) +- Composer + +#### 1. 一键部署脚本 + +```bash +# 在项目根目录执行,按提示输入配置 +sudo bash deploy.sh your-domain.com +``` + +脚本自动完成:环境检查 → 前端构建 → 文件部署 → 数据库初始化 → Nginx 配置 → 权限设置。 + +### 方式二:手动部署 + +#### 1. 初始化数据库 ```bash mysql -u root -p < backend/database/schema.sql ``` -### 2. 配置后端 +#### 2. 配置环境变量 ```bash cd backend cp .env.example .env -# 编辑 .env 填入数据库信息 +# 编辑 .env,确保: +# APP_ENV=production +# APP_DEBUG=false +# DB_* 填入实际数据库信息 +# JWT_SECRET 填入随机 64 位字符串 ``` -### 3. 启动 +#### 3. 安装依赖 ```bash -# 一键启动(前端 + 后端) -.\start.ps1 - -# 或分别启动 -cd backend && php -S 0.0.0.0:8080 -t backend -cd frontend && npm install && npm run dev +cd backend && composer install --no-dev --optimize-autoloader +cd ../frontend && npm install && npm run build ``` -### 4. 访问 -- 管理后台:`http://localhost:3000` -- 代理登录:`http://localhost:3000/#/agent/login` -- 购买商城:`http://localhost:3000/#/shop` +构建产物输出到 `frontend/dist/`,将其复制到 `backend/public/`: +```bash +cp -r frontend/dist/* backend/public/ +``` -### 5. 默认管理员 +#### 4. 配置 Nginx + +参考 [deploy/nginx.conf](deploy/nginx.conf),核心配置: + +```nginx +server { + listen 443 ssl http2; + server_name your-domain.com; + root /www/wwwroot/your-site/public; + index index.php index.html; + + # 前端 SPA fallback + location / { + try_files $uri $uri/ /index.html; + } + + # API 路由到 PHP + location /api { + try_files $uri $uri/ /index.php?$query_string; + } + + location ~ \.php$ { + fastcgi_pass unix:/tmp/php-cgi-74.sock; # 按实际 PHP 版本调整 + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + include fastcgi_params; + } + + # 安全加固 + location ~ /\.(?!well-known) { deny all; } + location ~* \.(env|sql|log|md)$ { deny all; } + location ~* ^/(storage|config|routes)/ { deny all; } +} +``` + +#### 5. 设置权限 +```bash +chown -R www:www /www/wwwroot/your-site +chmod -R 755 /www/wwwroot/your-site +chmod 600 /www/wwwroot/your-site/.env +``` + +#### 6. 默认管理员 | 用户名 | 密码 | |--------|------| | admin | admin123456 | +> 首次登录后请立即修改密码。 + ## SMTP 邮件通知配置 在系统配置 -> SMTP邮件配置中填写 SMTP 信息,系统将自动在授权到期前 N 天发送提醒邮件到联系人的 QQ 邮箱(`contact_qq@qq.com`)。 @@ -591,7 +667,14 @@ card/ │ ├── router/ # 路由配置 │ ├── stores/ # Pinia 状态管理 │ └── views/ # 页面组件 (管理后台 + 代理 + 公开) -└── deploy/ # 部署配置 (Nginx + 宝塔) +├── docker/ # Docker 配置 +│ ├── nginx.conf # Nginx 容器配置 +│ ├── supervisord.conf # Supervisor 进程管理 +│ └── entrypoint.sh # 容器入口脚本 +├── deploy/ # 传统部署配置 (Nginx + 宝塔) +├── Dockerfile # Docker 多阶段构建 +├── docker-compose.yml # Docker 编排 (MySQL + App) +└── .env.docker # Docker 环境变量模板 ``` ## License diff --git a/backend/.env.example b/backend/.env.example index 475b7ba..9b5b1e5 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -1,4 +1,6 @@ -APP_DEBUG=true +# 环境模式: development | production +APP_ENV=production +APP_DEBUG=false APP_URL=http://your-domain.com DB_HOST=127.0.0.1 diff --git a/backend/public/index.php b/backend/public/index.php index 672632f..0605f5f 100644 --- a/backend/public/index.php +++ b/backend/public/index.php @@ -5,9 +5,19 @@ */ // 错误报告设置 -error_reporting(E_ALL); -ini_set('display_errors', '0'); +$isDev = (getenv('APP_ENV') ?: 'production') === 'development'; +$isDebug = filter_var(getenv('APP_DEBUG') ?: 'false', FILTER_VALIDATE_BOOLEAN); + +error_reporting($isDev ? E_ALL : E_ALL & ~E_DEPRECATED & ~E_STRICT); +ini_set('display_errors', $isDev ? '1' : '0'); ini_set('log_errors', '1'); +ini_set('error_log', STORAGE_PATH . '/logs/error.log'); + +// 生产环境隐藏 PHP 版本 +if (!$isDev) { + ini_set('expose_php', '0'); + header_remove('X-Powered-By'); +} // 定义基础路径 define('BASE_PATH', dirname(__DIR__)); @@ -60,10 +70,10 @@ try { http_response_code(500); echo json_encode([ 'code' => 500, - 'message' => config('app.debug') ? $e->getMessage() : '服务器内部错误', + 'message' => $isDebug ? $e->getMessage() : '服务器内部错误', 'data' => null, ], JSON_UNESCAPED_UNICODE); - if (config('app.debug')) { + if ($isDebug) { error_log($e->getMessage() . "\n" . $e->getTraceAsString()); } } \ No newline at end of file diff --git a/backend/router.php b/backend/router.php deleted file mode 100644 index 9b835c8..0000000 --- a/backend/router.php +++ /dev/null @@ -1,44 +0,0 @@ - 'image/jpeg', 'jpeg' => 'image/jpeg', - 'png' => 'image/png', 'gif' => 'image/gif', - 'webp' => 'image/webp', 'svg' => 'image/svg+xml', - 'css' => 'text/css', 'js' => 'application/javascript', - 'json' => 'application/json', 'ico' => 'image/x-icon', - ]; - header('Content-Type: ' . ($mimeTypes[$ext] ?? 'application/octet-stream')); - header('Content-Length: ' . filesize($filePath)); - header('Cache-Control: public, max-age=31536000'); - readfile($filePath); - exit; -} - -// API 请求走后端入口 -if (str_starts_with($uri, '/api/')) { - require_once __DIR__ . '/public/index.php'; - exit; -} - -// 非 API 请求返回前端 SPA 入口(index.html),前端 Vue Router 负责渲染路由 -$indexHtml = __DIR__ . '/public/index.html'; -if (file_exists($indexHtml)) { - header('Content-Type: text/html; charset=utf-8'); - readfile($indexHtml); - exit; -} - -// 兜底:无法处理 -http_response_code(404); -echo 'Not Found'; -exit; diff --git a/backend/storage/logs/.gitkeep b/backend/storage/logs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..1bad09c --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,59 @@ +version: "3.8" + +services: + db: + image: mysql:8.0 + container_name: cardauth-db + restart: unless-stopped + environment: + MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-root_secret_change_me} + MYSQL_DATABASE: ${DB_NAME:-card_auth} + MYSQL_USER: ${DB_USER:-card_auth} + MYSQL_PASSWORD: ${DB_PASS:-card_auth_pass} + volumes: + - mysql_data:/var/lib/mysql + - ./backend/database/schema.sql:/docker-entrypoint-initdb.d/01-schema.sql:ro + command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci + healthcheck: + test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] + interval: 10s + timeout: 5s + retries: 5 + networks: + - cardauth + + app: + build: . + container_name: cardauth-app + restart: unless-stopped + ports: + - "8080:80" + environment: + APP_ENV: production + APP_DEBUG: "false" + APP_URL: ${APP_URL:-http://localhost:8080} + DB_HOST: db + DB_PORT: "3306" + DB_NAME: ${DB_NAME:-card_auth} + DB_USER: ${DB_USER:-card_auth} + DB_PASS: ${DB_PASS:-card_auth_pass} + DB_PREFIX: ca_ + JWT_SECRET: ${JWT_SECRET:-} + MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-root_secret_change_me} + PAYMENT_TYPE: ${PAYMENT_TYPE:-epay} + PAYMENT_API_URL: ${PAYMENT_API_URL:-} + PAYMENT_APP_ID: ${PAYMENT_APP_ID:-} + PAYMENT_APP_KEY: ${PAYMENT_APP_KEY:-} + depends_on: + db: + condition: service_healthy + networks: + - cardauth + +volumes: + mysql_data: + driver: local + +networks: + cardauth: + driver: bridge diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh new file mode 100644 index 0000000..20c35db --- /dev/null +++ b/docker/entrypoint.sh @@ -0,0 +1,38 @@ +#!/bin/sh +set -e + +# 从环境变量生成 .env +if [ ! -f /var/www/.env ]; then + echo ">>> Generating .env from environment..." + cat > /var/www/.env << EOF +APP_ENV=${APP_ENV:-production} +APP_DEBUG=${APP_DEBUG:-false} +APP_URL=${APP_URL:-http://localhost} + +DB_HOST=${DB_HOST:-db} +DB_PORT=${DB_PORT:-3306} +DB_NAME=${DB_NAME:-card_auth} +DB_USER=${DB_USER:-card_auth} +DB_PASS=${DB_PASS:-} +DB_PREFIX=${DB_PREFIX:-ca_} + +JWT_SECRET=${JWT_SECRET:-} + +PAYMENT_TYPE=${PAYMENT_TYPE:-epay} +PAYMENT_API_URL=${PAYMENT_API_URL:-} +PAYMENT_APP_ID=${PAYMENT_APP_ID:-} +PAYMENT_APP_KEY=${PAYMENT_APP_KEY:-} +EOF + chmod 600 /var/www/.env + echo ">>> .env generated" +fi + +# 等待 MySQL 就绪 +echo ">>> Waiting for MySQL at ${DB_HOST}:${DB_PORT}..." +until nc -z ${DB_HOST} ${DB_PORT} 2>/dev/null; do + sleep 2 +done +echo ">>> MySQL is ready" + +# 启动 Supervisor (Nginx + PHP-FPM) +exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf diff --git a/docker/nginx.conf b/docker/nginx.conf new file mode 100644 index 0000000..85d6fe9 --- /dev/null +++ b/docker/nginx.conf @@ -0,0 +1,53 @@ +server { + listen 80 default_server; + listen [::]:80 default_server; + server_name _; + + root /var/www/public; + index index.php index.html; + + client_max_body_size 20M; + + # 前端 SPA fallback + location / { + try_files $uri $uri/ /index.html; + } + + # API 路由 + location /api/ { + try_files $uri $uri/ /index.php?$query_string; + } + + # PHP-FPM + location ~ \.php$ { + fastcgi_pass 127.0.0.1:9000; + fastcgi_index index.php; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + include fastcgi_params; + fastcgi_param HTTP_AUTHORIZATION $http_authorization; + fastcgi_hide_header X-Powered-By; + } + + # 静态资源缓存 + location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { + expires 30d; + add_header Cache-Control "public, immutable"; + } + + # 安全:禁止访问敏感文件 + location ~ /\. { + deny all; + } + location ~* \.(env|sql|log|md|gitignore)$ { + deny all; + } + location ~* ^/(storage/cache|storage/logs)/ { + deny all; + } + + # 禁止访问源代码目录 + location ~* ^/(app|config|routes|database|vendor)/ { + deny all; + return 404; + } +} diff --git a/docker/supervisord.conf b/docker/supervisord.conf new file mode 100644 index 0000000..1d56378 --- /dev/null +++ b/docker/supervisord.conf @@ -0,0 +1,23 @@ +[supervisord] +nodaemon=true +user=root +logfile=/dev/stdout +logfile_maxbytes=0 + +[program:php-fpm] +command=php-fpm -F +autostart=true +autorestart=true +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 + +[program:nginx] +command=nginx -g "daemon off;" +autostart=true +autorestart=true +stdout_logfile=/dev/stdout +stdout_logfile_maxbytes=0 +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 9ca1a19..a497d44 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -5,7 +5,7 @@ import Components from 'unplugin-vue-components/vite' import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' import { fileURLToPath, URL } from 'node:url' -export default defineConfig({ +export default defineConfig(({ mode }) => ({ plugins: [ vue(), AutoImport({ resolvers: [ElementPlusResolver()] }), @@ -19,6 +19,8 @@ export default defineConfig({ server: { host: '0.0.0.0', port: 3000, + strictPort: false, + // 允许外部访问(开发模式下 nginx 反代需要,生产环境请用 npm run build) proxy: { '/api': { target: 'http://127.0.0.1:8080', @@ -34,5 +36,9 @@ export default defineConfig({ outDir: 'dist', assetsDir: 'assets', sourcemap: false, + // 生产构建时注入环境变量提示 + define: mode === 'production' ? {} : { + __DEV_SERVER_WARNING__: JSON.stringify('当前为开发模式, 生产环境请使用 npm run build 构建后部署') + } } -}) \ No newline at end of file +})) diff --git a/start.ps1 b/start.ps1 deleted file mode 100644 index af900ac..0000000 --- a/start.ps1 +++ /dev/null @@ -1,56 +0,0 @@ -# CardAuth One-Click Start Script -# Starts backend PHP server and frontend Vite dev server - -$projectRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition -$backendPath = Join-Path $projectRoot "backend" -$frontendPath = Join-Path $projectRoot "frontend" - -function Test-PortInUse { - param([int]$Port) - $listener = $null - try { - $listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, $Port) - $listener.Start() - $listener.Stop() - return $false - } catch { - return $true - } finally { - if ($listener -ne $null) { $listener.Stop() } - } -} - -function Start-Backend { - if (Test-PortInUse -Port 8080) { - Write-Host "[Backend] Port 8080 already in use, skip" -ForegroundColor Yellow - return - } - Write-Host "[Backend] Starting PHP server at http://127.0.0.1:8080 ..." -ForegroundColor Cyan - $proc = Start-Process -FilePath "php" -ArgumentList "-S 127.0.0.1:8080 router.php" -WorkingDirectory $backendPath -WindowStyle Hidden -PassThru - Write-Host "[Backend] Process ID: $($proc.Id)" -ForegroundColor Green -} - -function Start-Frontend { - if (Test-PortInUse -Port 3000) { - Write-Host "[Frontend] Port 3000 already in use, skip" -ForegroundColor Yellow - return - } - Write-Host "[Frontend] Starting Vite dev server at http://localhost:3000 ..." -ForegroundColor Cyan - $proc = Start-Process -FilePath "cmd.exe" -ArgumentList "/c npm run dev" -WorkingDirectory $frontendPath -WindowStyle Hidden -PassThru - Write-Host "[Frontend] Process ID: $($proc.Id)" -ForegroundColor Green -} - -Write-Host "============================================" -ForegroundColor Blue -Write-Host " CardAuth One-Click Start" -ForegroundColor Blue -Write-Host "============================================" -ForegroundColor Blue - -Start-Backend -Start-Frontend - -Write-Host "" -Write-Host "Services started. Please visit:" -ForegroundColor Green -Write-Host " Frontend: http://localhost:3000/" -ForegroundColor White -Write-Host " Admin: http://localhost:3000/#/login" -ForegroundColor White -Write-Host " Backend: http://127.0.0.1:8080" -ForegroundColor White -Write-Host "" -Write-Host "Note: background processes keep running after this window closes" -ForegroundColor Gray