feat: HR Portal - Complete Multi-Tenant System with Redis Session Storage
Major Features: - ✅ Multi-tenant architecture (tenant isolation) - ✅ Employee CRUD with lifecycle management (onboarding/offboarding) - ✅ Department tree structure with email domain management - ✅ Company info management (single-record editing) - ✅ System functions CRUD (permission management) - ✅ Email account management (multi-account per employee) - ✅ Keycloak SSO integration (auth.lab.taipei) - ✅ Redis session storage (10.1.0.254:6379) - Solves Cookie 4KB limitation - Cross-system session sharing - Sliding expiration (8 hours) - Automatic token refresh Technical Stack: Backend: - FastAPI + SQLAlchemy - PostgreSQL 16 (10.1.0.20:5433) - Keycloak Admin API integration - Docker Mailserver integration (SSH) - Alembic migrations Frontend: - Next.js 14 (App Router) - NextAuth 4 with Keycloak Provider - Redis session storage (ioredis) - Tailwind CSS Infrastructure: - Redis 7 (10.1.0.254:6379) - Session + Cache - Keycloak 26.1.0 (auth.lab.taipei) - Docker Mailserver (10.1.0.254) Architecture Highlights: - Session管理由 Keycloak + Redis 統一控制 - 支援多系統 (HR/WebMail/Calendar/Drive/Office) 共享 session - Token 自動刷新,異質服務整合 - 未來可無縫遷移到雲端 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
0
backend/app/core/__init__.py
Normal file
0
backend/app/core/__init__.py
Normal file
136
backend/app/core/audit.py
Normal file
136
backend/app/core/audit.py
Normal file
@@ -0,0 +1,136 @@
|
||||
"""
|
||||
審計日誌裝飾器和工具函數
|
||||
"""
|
||||
from functools import wraps
|
||||
from typing import Callable, Optional
|
||||
from fastapi import Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
def get_current_username() -> str:
|
||||
"""
|
||||
獲取當前用戶名稱
|
||||
|
||||
TODO: 實作後從 JWT Token 獲取
|
||||
目前返回系統用戶
|
||||
"""
|
||||
# TODO: 從 Keycloak JWT Token 解析用戶名
|
||||
return "system@porscheworld.tw"
|
||||
|
||||
|
||||
def audit_log_decorator(
|
||||
action: str,
|
||||
resource_type: str,
|
||||
get_resource_id: Optional[Callable] = None,
|
||||
get_details: Optional[Callable] = None,
|
||||
):
|
||||
"""
|
||||
審計日誌裝飾器
|
||||
|
||||
使用範例:
|
||||
@audit_log_decorator(
|
||||
action="create",
|
||||
resource_type="employee",
|
||||
get_resource_id=lambda result: result.id,
|
||||
get_details=lambda result: {"employee_id": result.employee_id}
|
||||
)
|
||||
def create_employee(...):
|
||||
pass
|
||||
|
||||
Args:
|
||||
action: 操作類型
|
||||
resource_type: 資源類型
|
||||
get_resource_id: 從返回結果獲取資源 ID 的函數
|
||||
get_details: 從返回結果獲取詳細資訊的函數
|
||||
"""
|
||||
def decorator(func: Callable):
|
||||
@wraps(func)
|
||||
async def async_wrapper(*args, **kwargs):
|
||||
# 執行原函數
|
||||
result = await func(*args, **kwargs)
|
||||
|
||||
# 獲取 DB Session
|
||||
db: Optional[Session] = kwargs.get("db")
|
||||
if not db:
|
||||
return result
|
||||
|
||||
# 獲取 Request (用於 IP)
|
||||
request: Optional[Request] = kwargs.get("request")
|
||||
ip_address = None
|
||||
if request:
|
||||
from app.services.audit_service import audit_service
|
||||
ip_address = audit_service.get_client_ip(request)
|
||||
|
||||
# 獲取資源 ID
|
||||
resource_id = None
|
||||
if get_resource_id and result:
|
||||
resource_id = get_resource_id(result)
|
||||
|
||||
# 獲取詳細資訊
|
||||
details = None
|
||||
if get_details and result:
|
||||
details = get_details(result)
|
||||
|
||||
# 記錄審計日誌
|
||||
from app.services.audit_service import audit_service
|
||||
audit_service.log(
|
||||
db=db,
|
||||
action=action,
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
performed_by=get_current_username(),
|
||||
details=details,
|
||||
ip_address=ip_address,
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
@wraps(func)
|
||||
def sync_wrapper(*args, **kwargs):
|
||||
# 執行原函數
|
||||
result = func(*args, **kwargs)
|
||||
|
||||
# 獲取 DB Session
|
||||
db: Optional[Session] = kwargs.get("db")
|
||||
if not db:
|
||||
return result
|
||||
|
||||
# 獲取 Request (用於 IP)
|
||||
request: Optional[Request] = kwargs.get("request")
|
||||
ip_address = None
|
||||
if request:
|
||||
from app.services.audit_service import audit_service
|
||||
ip_address = audit_service.get_client_ip(request)
|
||||
|
||||
# 獲取資源 ID
|
||||
resource_id = None
|
||||
if get_resource_id and result:
|
||||
resource_id = get_resource_id(result)
|
||||
|
||||
# 獲取詳細資訊
|
||||
details = None
|
||||
if get_details and result:
|
||||
details = get_details(result)
|
||||
|
||||
# 記錄審計日誌
|
||||
from app.services.audit_service import audit_service
|
||||
audit_service.log(
|
||||
db=db,
|
||||
action=action,
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
performed_by=get_current_username(),
|
||||
details=details,
|
||||
ip_address=ip_address,
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
# 檢查是否為異步函數
|
||||
import asyncio
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
return async_wrapper
|
||||
else:
|
||||
return sync_wrapper
|
||||
|
||||
return decorator
|
||||
92
backend/app/core/config.py
Normal file
92
backend/app/core/config.py
Normal file
@@ -0,0 +1,92 @@
|
||||
"""簡化配置 - 用於測試"""
|
||||
from pydantic_settings import BaseSettings
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# 載入 .env 檔案 (必須在讀取環境變數之前)
|
||||
load_dotenv()
|
||||
|
||||
# 直接從環境變數讀取,不依賴 pydantic-settings 的複雜功能
|
||||
class Settings:
|
||||
"""應用配置 (簡化版)"""
|
||||
|
||||
# 基本資訊
|
||||
PROJECT_NAME: str = os.getenv("PROJECT_NAME", "HR Portal API")
|
||||
VERSION: str = os.getenv("VERSION", "2.0.0")
|
||||
ENVIRONMENT: str = os.getenv("ENVIRONMENT", "development")
|
||||
HOST: str = os.getenv("HOST", "0.0.0.0")
|
||||
PORT: int = int(os.getenv("PORT", "8000"))
|
||||
|
||||
# 資料庫
|
||||
DATABASE_URL: str = os.getenv("DATABASE_URL", "postgresql+psycopg://hr_admin:hr_dev_password_2026@localhost:5433/hr_portal")
|
||||
DATABASE_ECHO: bool = os.getenv("DATABASE_ECHO", "False").lower() == "true"
|
||||
|
||||
# CORS
|
||||
ALLOWED_ORIGINS: str = os.getenv("ALLOWED_ORIGINS", "http://localhost:3000,http://localhost:10180,http://10.1.0.245:3000,http://10.1.0.245:10180,https://hr.ease.taipei")
|
||||
|
||||
def get_allowed_origins(self):
|
||||
return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",")]
|
||||
|
||||
# Keycloak
|
||||
KEYCLOAK_URL: str = os.getenv("KEYCLOAK_URL", "https://auth.ease.taipei")
|
||||
KEYCLOAK_REALM: str = os.getenv("KEYCLOAK_REALM", "porscheworld")
|
||||
KEYCLOAK_CLIENT_ID: str = os.getenv("KEYCLOAK_CLIENT_ID", "hr-backend")
|
||||
KEYCLOAK_CLIENT_SECRET: str = os.getenv("KEYCLOAK_CLIENT_SECRET", "")
|
||||
KEYCLOAK_ADMIN_USERNAME: str = os.getenv("KEYCLOAK_ADMIN_USERNAME", "")
|
||||
KEYCLOAK_ADMIN_PASSWORD: str = os.getenv("KEYCLOAK_ADMIN_PASSWORD", "")
|
||||
|
||||
# JWT
|
||||
JWT_SECRET_KEY: str = os.getenv("JWT_SECRET_KEY", "dev-secret-key-change-in-production")
|
||||
JWT_ALGORITHM: str = os.getenv("JWT_ALGORITHM", "HS256")
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = int(os.getenv("JWT_ACCESS_TOKEN_EXPIRE_MINUTES", "30"))
|
||||
|
||||
# 郵件
|
||||
MAIL_SERVER: str = os.getenv("MAIL_SERVER", "10.1.0.30")
|
||||
MAIL_PORT: int = int(os.getenv("MAIL_PORT", "587"))
|
||||
MAIL_USE_TLS: bool = os.getenv("MAIL_USE_TLS", "True").lower() == "true"
|
||||
MAIL_ADMIN_USER: str = os.getenv("MAIL_ADMIN_USER", "admin@porscheworld.tw")
|
||||
MAIL_ADMIN_PASSWORD: str = os.getenv("MAIL_ADMIN_PASSWORD", "")
|
||||
|
||||
# NAS
|
||||
NAS_HOST: str = os.getenv("NAS_HOST", "10.1.0.30")
|
||||
NAS_PORT: int = int(os.getenv("NAS_PORT", "5000"))
|
||||
NAS_USERNAME: str = os.getenv("NAS_USERNAME", "")
|
||||
NAS_PASSWORD: str = os.getenv("NAS_PASSWORD", "")
|
||||
NAS_WEBDAV_URL: str = os.getenv("NAS_WEBDAV_URL", "https://nas.lab.taipei/webdav")
|
||||
NAS_SMB_SHARE: str = os.getenv("NAS_SMB_SHARE", "Working")
|
||||
|
||||
# 日誌
|
||||
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
|
||||
LOG_FILE: str = os.getenv("LOG_FILE", "logs/hr_portal.log")
|
||||
|
||||
# 分頁
|
||||
DEFAULT_PAGE_SIZE: int = int(os.getenv("DEFAULT_PAGE_SIZE", "20"))
|
||||
MAX_PAGE_SIZE: int = int(os.getenv("MAX_PAGE_SIZE", "100"))
|
||||
|
||||
# 郵件配額 (MB)
|
||||
EMAIL_QUOTA_JUNIOR: int = int(os.getenv("EMAIL_QUOTA_JUNIOR", "1000"))
|
||||
EMAIL_QUOTA_MID: int = int(os.getenv("EMAIL_QUOTA_MID", "2000"))
|
||||
EMAIL_QUOTA_SENIOR: int = int(os.getenv("EMAIL_QUOTA_SENIOR", "5000"))
|
||||
EMAIL_QUOTA_MANAGER: int = int(os.getenv("EMAIL_QUOTA_MANAGER", "10000"))
|
||||
|
||||
# NAS 配額 (GB)
|
||||
NAS_QUOTA_JUNIOR: int = int(os.getenv("NAS_QUOTA_JUNIOR", "50"))
|
||||
NAS_QUOTA_MID: int = int(os.getenv("NAS_QUOTA_MID", "100"))
|
||||
NAS_QUOTA_SENIOR: int = int(os.getenv("NAS_QUOTA_SENIOR", "200"))
|
||||
NAS_QUOTA_MANAGER: int = int(os.getenv("NAS_QUOTA_MANAGER", "500"))
|
||||
|
||||
# Drive Service (Nextcloud 微服務)
|
||||
DRIVE_SERVICE_URL: str = os.getenv("DRIVE_SERVICE_URL", "https://drive-api.ease.taipei")
|
||||
DRIVE_SERVICE_TIMEOUT: int = int(os.getenv("DRIVE_SERVICE_TIMEOUT", "10"))
|
||||
DRIVE_SERVICE_TENANT_ID: int = int(os.getenv("DRIVE_SERVICE_TENANT_ID", "1"))
|
||||
|
||||
# Docker Mailserver SSH 整合
|
||||
MAILSERVER_SSH_HOST: str = os.getenv("MAILSERVER_SSH_HOST", "10.1.0.254")
|
||||
MAILSERVER_SSH_PORT: int = int(os.getenv("MAILSERVER_SSH_PORT", "22"))
|
||||
MAILSERVER_SSH_USER: str = os.getenv("MAILSERVER_SSH_USER", "porsche")
|
||||
MAILSERVER_SSH_PASSWORD: str = os.getenv("MAILSERVER_SSH_PASSWORD", "")
|
||||
MAILSERVER_CONTAINER_NAME: str = os.getenv("MAILSERVER_CONTAINER_NAME", "mailserver")
|
||||
MAILSERVER_SSH_TIMEOUT: int = int(os.getenv("MAILSERVER_SSH_TIMEOUT", "30"))
|
||||
|
||||
# 創建實例
|
||||
settings = Settings()
|
||||
87
backend/app/core/config.py.backup
Normal file
87
backend/app/core/config.py.backup
Normal file
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
應用配置管理
|
||||
使用 Pydantic Settings 管理環境變數
|
||||
"""
|
||||
from typing import List, Union
|
||||
from pydantic import field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""應用配置"""
|
||||
|
||||
# 基本資訊
|
||||
PROJECT_NAME: str = "HR Portal API"
|
||||
VERSION: str = "2.0.0"
|
||||
ENVIRONMENT: str = "development" # development, staging, production
|
||||
HOST: str = "0.0.0.0"
|
||||
PORT: int = 8000
|
||||
|
||||
# 資料庫配置 (使用 psycopg 驅動)
|
||||
DATABASE_URL: str = "postgresql+psycopg://hr_admin:hr_dev_password_2026@localhost:5433/hr_portal"
|
||||
DATABASE_ECHO: bool = False # SQL 查詢日誌
|
||||
|
||||
# CORS 配置 (字串格式,逗號分隔)
|
||||
ALLOWED_ORIGINS: str = "http://localhost:3000,http://10.1.0.245:3000,https://hr.ease.taipei"
|
||||
|
||||
def get_allowed_origins(self) -> List[str]:
|
||||
"""取得 CORS 允許的來源清單"""
|
||||
return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",")]
|
||||
|
||||
# Keycloak 配置
|
||||
KEYCLOAK_URL: str = "https://auth.ease.taipei"
|
||||
KEYCLOAK_REALM: str = "porscheworld"
|
||||
KEYCLOAK_CLIENT_ID: str = "hr-backend"
|
||||
KEYCLOAK_CLIENT_SECRET: str = "" # 從環境變數讀取
|
||||
KEYCLOAK_ADMIN_USERNAME: str = ""
|
||||
KEYCLOAK_ADMIN_PASSWORD: str = ""
|
||||
|
||||
# JWT 配置
|
||||
JWT_SECRET_KEY: str = "your-secret-key-change-in-production"
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
|
||||
# 郵件配置 (Docker Mailserver)
|
||||
MAIL_SERVER: str = "10.1.0.30"
|
||||
MAIL_PORT: int = 587
|
||||
MAIL_USE_TLS: bool = True
|
||||
MAIL_ADMIN_USER: str = "admin@porscheworld.tw"
|
||||
MAIL_ADMIN_PASSWORD: str = ""
|
||||
|
||||
# NAS 配置 (Synology)
|
||||
NAS_HOST: str = "10.1.0.30"
|
||||
NAS_PORT: int = 5000
|
||||
NAS_USERNAME: str = ""
|
||||
NAS_PASSWORD: str = ""
|
||||
NAS_WEBDAV_URL: str = "https://nas.lab.taipei/webdav"
|
||||
NAS_SMB_SHARE: str = "Working"
|
||||
|
||||
# 日誌配置
|
||||
LOG_LEVEL: str = "INFO"
|
||||
LOG_FILE: str = "logs/hr_portal.log"
|
||||
|
||||
# 分頁配置
|
||||
DEFAULT_PAGE_SIZE: int = 20
|
||||
MAX_PAGE_SIZE: int = 100
|
||||
|
||||
# 配額配置 (MB)
|
||||
EMAIL_QUOTA_JUNIOR: int = 1000
|
||||
EMAIL_QUOTA_MID: int = 2000
|
||||
EMAIL_QUOTA_SENIOR: int = 5000
|
||||
EMAIL_QUOTA_MANAGER: int = 10000
|
||||
|
||||
# NAS 配額配置 (GB)
|
||||
NAS_QUOTA_JUNIOR: int = 50
|
||||
NAS_QUOTA_MID: int = 100
|
||||
NAS_QUOTA_SENIOR: int = 200
|
||||
NAS_QUOTA_MANAGER: int = 500
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
case_sensitive=True,
|
||||
)
|
||||
|
||||
|
||||
# 全域配置實例
|
||||
settings = Settings()
|
||||
94
backend/app/core/config.pydantic_backup
Normal file
94
backend/app/core/config.pydantic_backup
Normal file
@@ -0,0 +1,94 @@
|
||||
"""
|
||||
應用配置管理
|
||||
使用 Pydantic Settings 管理環境變數
|
||||
"""
|
||||
from typing import List, Union
|
||||
from pydantic import field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
|
||||
# 手動載入 .env 檔案 (避免網路磁碟 I/O 延遲問題)
|
||||
env_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), ".env")
|
||||
if os.path.exists(env_path):
|
||||
load_dotenv(env_path)
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""應用配置"""
|
||||
|
||||
# 基本資訊
|
||||
PROJECT_NAME: str = "HR Portal API"
|
||||
VERSION: str = "2.0.0"
|
||||
ENVIRONMENT: str = "development" # development, staging, production
|
||||
HOST: str = "0.0.0.0"
|
||||
PORT: int = 8000
|
||||
|
||||
# 資料庫配置 (使用 psycopg 驅動)
|
||||
DATABASE_URL: str = "postgresql+psycopg://hr_admin:hr_dev_password_2026@localhost:5433/hr_portal"
|
||||
DATABASE_ECHO: bool = False # SQL 查詢日誌
|
||||
|
||||
# CORS 配置 (字串格式,逗號分隔)
|
||||
ALLOWED_ORIGINS: str = "http://localhost:3000,http://10.1.0.245:3000,https://hr.ease.taipei"
|
||||
|
||||
def get_allowed_origins(self) -> List[str]:
|
||||
"""取得 CORS 允許的來源清單"""
|
||||
return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",")]
|
||||
|
||||
# Keycloak 配置
|
||||
KEYCLOAK_URL: str = "https://auth.ease.taipei"
|
||||
KEYCLOAK_REALM: str = "porscheworld"
|
||||
KEYCLOAK_CLIENT_ID: str = "hr-backend"
|
||||
KEYCLOAK_CLIENT_SECRET: str = "" # 從環境變數讀取
|
||||
KEYCLOAK_ADMIN_USERNAME: str = ""
|
||||
KEYCLOAK_ADMIN_PASSWORD: str = ""
|
||||
|
||||
# JWT 配置
|
||||
JWT_SECRET_KEY: str = "your-secret-key-change-in-production"
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
|
||||
# 郵件配置 (Docker Mailserver)
|
||||
MAIL_SERVER: str = "10.1.0.30"
|
||||
MAIL_PORT: int = 587
|
||||
MAIL_USE_TLS: bool = True
|
||||
MAIL_ADMIN_USER: str = "admin@porscheworld.tw"
|
||||
MAIL_ADMIN_PASSWORD: str = ""
|
||||
|
||||
# NAS 配置 (Synology)
|
||||
NAS_HOST: str = "10.1.0.30"
|
||||
NAS_PORT: int = 5000
|
||||
NAS_USERNAME: str = ""
|
||||
NAS_PASSWORD: str = ""
|
||||
NAS_WEBDAV_URL: str = "https://nas.lab.taipei/webdav"
|
||||
NAS_SMB_SHARE: str = "Working"
|
||||
|
||||
# 日誌配置
|
||||
LOG_LEVEL: str = "INFO"
|
||||
LOG_FILE: str = "logs/hr_portal.log"
|
||||
|
||||
# 分頁配置
|
||||
DEFAULT_PAGE_SIZE: int = 20
|
||||
MAX_PAGE_SIZE: int = 100
|
||||
|
||||
# 配額配置 (MB)
|
||||
EMAIL_QUOTA_JUNIOR: int = 1000
|
||||
EMAIL_QUOTA_MID: int = 2000
|
||||
EMAIL_QUOTA_SENIOR: int = 5000
|
||||
EMAIL_QUOTA_MANAGER: int = 10000
|
||||
|
||||
# NAS 配額配置 (GB)
|
||||
NAS_QUOTA_JUNIOR: int = 50
|
||||
NAS_QUOTA_MID: int = 100
|
||||
NAS_QUOTA_SENIOR: int = 200
|
||||
NAS_QUOTA_MANAGER: int = 500
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
# 不使用 pydantic-settings 的 env_file (避免網路磁碟I/O問題)
|
||||
# 改用 python-dotenv 手動載入 (見檔案開頭)
|
||||
case_sensitive=True,
|
||||
)
|
||||
|
||||
|
||||
# 全域配置實例
|
||||
settings = Settings()
|
||||
77
backend/app/core/config_simple.py
Normal file
77
backend/app/core/config_simple.py
Normal file
@@ -0,0 +1,77 @@
|
||||
"""簡化配置 - 用於測試"""
|
||||
from pydantic_settings import BaseSettings
|
||||
import os
|
||||
|
||||
# 直接從環境變數讀取,不依賴 pydantic-settings 的複雜功能
|
||||
class Settings:
|
||||
"""應用配置 (簡化版)"""
|
||||
|
||||
# 基本資訊
|
||||
PROJECT_NAME: str = os.getenv("PROJECT_NAME", "HR Portal API")
|
||||
VERSION: str = os.getenv("VERSION", "2.0.0")
|
||||
ENVIRONMENT: str = os.getenv("ENVIRONMENT", "development")
|
||||
HOST: str = os.getenv("HOST", "0.0.0.0")
|
||||
PORT: int = int(os.getenv("PORT", "8000"))
|
||||
|
||||
# 資料庫
|
||||
DATABASE_URL: str = os.getenv("DATABASE_URL", "postgresql+psycopg://hr_admin:hr_dev_password_2026@localhost:5433/hr_portal")
|
||||
DATABASE_ECHO: bool = os.getenv("DATABASE_ECHO", "False").lower() == "true"
|
||||
|
||||
# CORS
|
||||
ALLOWED_ORIGINS: str = os.getenv("ALLOWED_ORIGINS", "http://localhost:3000,http://10.1.0.245:3000,https://hr.ease.taipei")
|
||||
|
||||
def get_allowed_origins(self):
|
||||
return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",")]
|
||||
|
||||
# Keycloak
|
||||
KEYCLOAK_URL: str = os.getenv("KEYCLOAK_URL", "https://auth.ease.taipei")
|
||||
KEYCLOAK_REALM: str = os.getenv("KEYCLOAK_REALM", "porscheworld")
|
||||
KEYCLOAK_CLIENT_ID: str = os.getenv("KEYCLOAK_CLIENT_ID", "hr-backend")
|
||||
KEYCLOAK_CLIENT_SECRET: str = os.getenv("KEYCLOAK_CLIENT_SECRET", "")
|
||||
KEYCLOAK_ADMIN_USERNAME: str = os.getenv("KEYCLOAK_ADMIN_USERNAME", "")
|
||||
KEYCLOAK_ADMIN_PASSWORD: str = os.getenv("KEYCLOAK_ADMIN_PASSWORD", "")
|
||||
|
||||
# JWT
|
||||
JWT_SECRET_KEY: str = os.getenv("JWT_SECRET_KEY", "dev-secret-key-change-in-production")
|
||||
JWT_ALGORITHM: str = os.getenv("JWT_ALGORITHM", "HS256")
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = int(os.getenv("JWT_ACCESS_TOKEN_EXPIRE_MINUTES", "30"))
|
||||
|
||||
# 郵件
|
||||
MAIL_SERVER: str = os.getenv("MAIL_SERVER", "10.1.0.30")
|
||||
MAIL_PORT: int = int(os.getenv("MAIL_PORT", "587"))
|
||||
MAIL_USE_TLS: bool = os.getenv("MAIL_USE_TLS", "True").lower() == "true"
|
||||
MAIL_ADMIN_USER: str = os.getenv("MAIL_ADMIN_USER", "admin@porscheworld.tw")
|
||||
MAIL_ADMIN_PASSWORD: str = os.getenv("MAIL_ADMIN_PASSWORD", "")
|
||||
|
||||
# NAS
|
||||
NAS_HOST: str = os.getenv("NAS_HOST", "10.1.0.30")
|
||||
NAS_PORT: int = int(os.getenv("NAS_PORT", "5000"))
|
||||
NAS_USERNAME: str = os.getenv("NAS_USERNAME", "")
|
||||
NAS_PASSWORD: str = os.getenv("NAS_PASSWORD", "")
|
||||
NAS_WEBDAV_URL: str = os.getenv("NAS_WEBDAV_URL", "https://nas.lab.taipei/webdav")
|
||||
NAS_SMB_SHARE: str = os.getenv("NAS_SMB_SHARE", "Working")
|
||||
|
||||
# 日誌
|
||||
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
|
||||
LOG_FILE: str = os.getenv("LOG_FILE", "logs/hr_portal.log")
|
||||
|
||||
# 分頁
|
||||
DEFAULT_PAGE_SIZE: int = int(os.getenv("DEFAULT_PAGE_SIZE", "20"))
|
||||
MAX_PAGE_SIZE: int = int(os.getenv("MAX_PAGE_SIZE", "100"))
|
||||
|
||||
# 郵件配額 (MB)
|
||||
EMAIL_QUOTA_JUNIOR: int = int(os.getenv("EMAIL_QUOTA_JUNIOR", "1000"))
|
||||
EMAIL_QUOTA_MID: int = int(os.getenv("EMAIL_QUOTA_MID", "2000"))
|
||||
EMAIL_QUOTA_SENIOR: int = int(os.getenv("EMAIL_QUOTA_SENIOR", "5000"))
|
||||
EMAIL_QUOTA_MANAGER: int = int(os.getenv("EMAIL_QUOTA_MANAGER", "10000"))
|
||||
|
||||
# NAS 配額 (GB)
|
||||
NAS_QUOTA_JUNIOR: int = int(os.getenv("NAS_QUOTA_JUNIOR", "50"))
|
||||
NAS_QUOTA_MID: int = int(os.getenv("NAS_QUOTA_MID", "100"))
|
||||
NAS_QUOTA_SENIOR: int = int(os.getenv("NAS_QUOTA_SENIOR", "200"))
|
||||
NAS_QUOTA_MANAGER: int = int(os.getenv("NAS_QUOTA_MANAGER", "500"))
|
||||
|
||||
# 載入 .env 並創建實例
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
settings = Settings()
|
||||
11
backend/app/core/config_test.py
Normal file
11
backend/app/core/config_test.py
Normal file
@@ -0,0 +1,11 @@
|
||||
"""測試配置"""
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
class TestSettings(BaseSettings):
|
||||
PROJECT_NAME: str = "Test"
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
|
||||
settings = TestSettings()
|
||||
print(f"[OK] Settings loaded: {settings.PROJECT_NAME}")
|
||||
54
backend/app/core/logging_config.py
Normal file
54
backend/app/core/logging_config.py
Normal file
@@ -0,0 +1,54 @@
|
||||
"""
|
||||
日誌配置
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from pythonjsonlogger import jsonlogger
|
||||
|
||||
|
||||
def setup_logging():
|
||||
"""設置日誌系統"""
|
||||
# 延遲導入避免循環依賴
|
||||
from app.core.config import settings
|
||||
|
||||
# 創建日誌目錄
|
||||
log_file = Path(settings.LOG_FILE)
|
||||
log_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 根日誌器
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(getattr(logging, settings.LOG_LEVEL))
|
||||
|
||||
# 格式化器
|
||||
formatter = logging.Formatter(
|
||||
"%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
|
||||
# JSON 格式化器 (生產環境)
|
||||
json_formatter = jsonlogger.JsonFormatter(
|
||||
"%(asctime)s %(name)s %(levelname)s %(message)s"
|
||||
)
|
||||
|
||||
# 控制台處理器
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(logging.INFO)
|
||||
console_handler.setFormatter(formatter)
|
||||
|
||||
# 文件處理器
|
||||
file_handler = logging.FileHandler(log_file, encoding="utf-8")
|
||||
file_handler.setLevel(logging.DEBUG)
|
||||
|
||||
if settings.ENVIRONMENT == "production":
|
||||
file_handler.setFormatter(json_formatter)
|
||||
else:
|
||||
file_handler.setFormatter(formatter)
|
||||
|
||||
# 添加處理器
|
||||
root_logger.addHandler(console_handler)
|
||||
root_logger.addHandler(file_handler)
|
||||
|
||||
# 設置第三方日誌級別
|
||||
logging.getLogger("uvicorn").setLevel(logging.INFO)
|
||||
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
|
||||
Reference in New Issue
Block a user