Email supports password login, and the system configuration has added a new email login switch.

This commit is contained in:
Liujian committed 2025-07-23 15:50:14 +08:00
1 parent 3e9f0fcf43
commit 4d4f63a911
12 files changed
+278 -27

No files matched your search

+1
View File
@@ -40,3 +40,4 @@ htmlcov/
# Ignore local config
local_settings.py
/.secrets
/uploads/
@@ -5,6 +5,8 @@ KEY_WEBSITE_TITLE = "website_title"
KEY_HEADLINE = "headline"
KEY_SUBHEADLINE = "subheadline"
KEY_LANGUAGE = "language"
KEY_THEME = "theme"
KEY_ABOUT_PAGE = "about_page"
KEY_ADMIN_USERNAME = "admin_username"
KEY_ADMIN_PASSWORD = "admin_password"
KEY_LOGIN_GOOGLE_CLIENT = "login_google_client_id"
@@ -15,4 +17,7 @@ KEY_EMAIL_SMTP_HOST = "email_smtp_host"
KEY_EMAIL_SMTP_PORT = "email_smtp_port"
KEY_EMAIL_SMTP_USER = "email_smtp_user"
KEY_EMAIL_SMTP_PASSWORD = "email_smtp_password"
KEY_EMAIL_SMTP_SENDER = "email_smtp_sender"
KEY_EMAIL_SMTP_SENDER = "email_smtp_sender"
KEY_LOGIN_EMAIL_ENABLE = "login_email_enable"
KEY_LOGIN_EMAIL_MODE = "login_email_mode"
+28 -5
View File
@@ -3,7 +3,9 @@ from sqlalchemy.orm import Session
from services.common.database import get_db
from services.common.utils.response_utils import ResponseUtils
from services.admin_service.services.auth_service import AuthService
from services.admin_service.services.sys_config_service import SysConfigService
from services.admin_service.utils.user_utils import UserUtils
from services.admin_service.constants import sys_config_key
router = APIRouter()
@@ -11,15 +13,36 @@ router = APIRouter()
def get_auth_service(db: Session = Depends(get_db)) -> AuthService:
return AuthService(db)
def get_sys_config_service(db: Session = Depends(get_db)) -> SysConfigService:
return SysConfigService(db)
@router.post("/email/sign", response_model=dict)
def email_login(body: dict = Body(...), auth_service: AuthService = Depends(get_auth_service)):
def email_login(
body: dict = Body(...),
auth_service: AuthService = Depends(get_auth_service),
sys_config_service: SysConfigService = Depends(get_sys_config_service),
):
"""Authenticate user via email and captcha code."""
email_is_enabled_raw = sys_config_service.get_value_by_key(sys_config_key.KEY_LOGIN_EMAIL_ENABLE) or "false"
# Convert to boolean
email_is_enabled = email_is_enabled_raw.lower() in ("true", "t", "yes", "y", "1")
if not email_is_enabled:
return ResponseUtils.error(message="email login not enabled", code=400)
email_mode = sys_config_service.get_value_by_key(sys_config_key.KEY_LOGIN_EMAIL_MODE) or "password"
email = body.get("user_email")
captcha = body.get("captcha")
if not email or not captcha:
return ResponseUtils.error(message="email and captcha required", code=400)
token = auth_service.email_login(email, captcha)
token = None
match email_mode:
case "password":
password = body.get("password")
if not email or not password:
return ResponseUtils.error(message="email and password required", code=400)
token = auth_service.email_login_by_password(email=email, password=password)
case "captcha":
captcha = body.get("captcha")
if not email or not captcha:
return ResponseUtils.error(message="email and captcha required", code=400)
token = auth_service.email_login_by_captcha(email=email, captcha=captcha)
if token:
return ResponseUtils.success({"user_token": token})
else:
@@ -13,8 +13,12 @@ from services.admin_service.constants.sys_config_key import (
KEY_HEADLINE,
KEY_SUBHEADLINE,
KEY_LANGUAGE,
KEY_THEME,
KEY_ABOUT_PAGE,
KEY_LOGIN_GOOGLE_CLIENT,
KEY_LOGIN_GOOGLE_ENABLE,
KEY_LOGIN_EMAIL_ENABLE,
KEY_LOGIN_EMAIL_MODE,
)
logger = logging.getLogger(__name__)
@@ -36,16 +40,27 @@ def get_config(db: Session = Depends(get_db)):
headline = sys_config_service.get_value_by_key(KEY_HEADLINE) or ""
subheadline = sys_config_service.get_value_by_key(KEY_SUBHEADLINE) or ""
language = sys_config_service.get_value_by_key(KEY_LANGUAGE) or ""
theme = sys_config_service.get_value_by_key(KEY_THEME) or ""
about_page = sys_config_service.get_value_by_key(KEY_ABOUT_PAGE) or ""
# Get login config
google_client_id = sys_config_service.get_value_by_key(KEY_LOGIN_GOOGLE_CLIENT) or ""
google_is_enabled_raw = sys_config_service.get_value_by_key(KEY_LOGIN_GOOGLE_ENABLE) or "false"
# Convert to boolean
google_is_enabled = google_is_enabled_raw.lower() in ("true", "t", "yes", "y", "1")
# Get login email config
email_is_enabled_raw = sys_config_service.get_value_by_key(KEY_LOGIN_EMAIL_ENABLE) or "false"
# Convert to boolean
email_is_enabled = email_is_enabled_raw.lower() in ("true", "t", "yes", "y", "1")
email_mode = sys_config_service.get_value_by_key(KEY_LOGIN_EMAIL_MODE) or "password"
# Build response data
config_data = {
"login": {"google": {"client_id": google_client_id, "is_enabled": google_is_enabled}},
"login": {
"google": {"client_id": google_client_id, "is_enabled": google_is_enabled},
"email": {"is_enabled": email_is_enabled, "mode": email_mode},
},
"platform": {
"name": platform_name,
"logo": platform_logo,
@@ -53,6 +68,8 @@ def get_config(db: Session = Depends(get_db)):
"headline": headline,
"subheadline": subheadline,
"language": language,
"theme": theme,
"about_page": about_page,
},
}
@@ -34,16 +34,27 @@ def get_sysconfig(
headline = sysconfig_service.get_value_by_key(sys_config_key.KEY_HEADLINE)
subheadline = sysconfig_service.get_value_by_key(sys_config_key.KEY_SUBHEADLINE)
language = sysconfig_service.get_value_by_key(sys_config_key.KEY_LANGUAGE)
theme = sysconfig_service.get_value_by_key(sys_config_key.KEY_THEME)
about_page = sysconfig_service.get_value_by_key(sys_config_key.KEY_ABOUT_PAGE,True)
admin_username = ""
if admin_user and admin_user.name:
admin_username = admin_user.name
login_google_client = sysconfig_service.get_value_by_key(sys_config_key.KEY_LOGIN_GOOGLE_CLIENT)
login_google_secret = sysconfig_service.get_value_by_key(sys_config_key.KEY_LOGIN_GOOGLE_SECRET)
login_google_enable = sysconfig_service.get_value_by_key(sys_config_key.KEY_LOGIN_GOOGLE_ENABLE)
if not login_google_enable:
login_google_enable = False
else:
login_google_enable = bool(login_google_enable)
google_is_enabled_raw = sysconfig_service.get_value_by_key(sys_config_key.KEY_LOGIN_GOOGLE_ENABLE) or "false"
# Convert to boolean
login_google_enable = google_is_enabled_raw.lower() in ("true", "t", "yes", "y", "1")
# Get login email config
email_is_enabled_raw = sysconfig_service.get_value_by_key(sys_config_key.KEY_LOGIN_EMAIL_ENABLE) or "false"
# Convert to boolean
login_email_enable = email_is_enabled_raw.lower() in ("true", "t", "yes", "y", "1")
login_email_mode = sysconfig_service.get_value_by_key(sys_config_key.KEY_LOGIN_EMAIL_MODE)
if not login_email_mode:
login_email_mode = "password"
# Get email configuration
email_smtp_host = sysconfig_service.get_value_by_key(sys_config_key.KEY_EMAIL_SMTP_HOST)
@@ -62,6 +73,8 @@ def get_sysconfig(
"headline": headline,
"subheadline": subheadline,
"language": language,
"theme": theme,
"about_page": about_page,
},
"account": {
"username": admin_username,
@@ -79,6 +92,10 @@ def get_sysconfig(
"client_secret": login_google_secret,
"is_enabled": login_google_enable,
},
"email":{
"is_enabled": login_email_enable,
"mode": login_email_mode,
}
},
}
)
@@ -119,6 +136,8 @@ def set_sysconfig(
headline = platform.get("headline")
subheadline = platform.get("subheadline")
language = platform.get("language")
theme = platform.get("theme")
about_page = platform.get("about_page")
account = body.get("account", {})
admin_username = account.get("username")
@@ -128,8 +147,11 @@ def set_sysconfig(
google_config = login.get("google", {})
login_google_client = google_config.get("client_id")
login_google_secret = google_config.get("client_secret")
login_google_enable = google_config.get("is_enabled", False) # 设置默认值为 False
login_google_enable = google_config.get("is_enabled") # 设置默认值为 False
login_email_config = login.get("email", {})
login_email_mode = login_email_config.get("mode")
login_email_is_enable = login_email_config.get("is_enabled") # 设置默认值为 False
print("email info:",login_email_is_enable,login_email_mode)
# 获取邮件配置 - 现在从外层获取
email_config = body.get("email", {})
email_smtp_host = email_config.get("smtp_host")
@@ -138,19 +160,27 @@ def set_sysconfig(
email_smtp_password = email_config.get("smtp_password")
email_smtp_sender = email_config.get("smtp_sender")
if not login_google_enable or login_google_enable == "false":
login_google_enable = "False"
else:
login_google_enable = "True"
# if login_google_enable:
# if login_google_enable == "false":
# login_google_enable = "False"
# else:
# login_google_enable = "True"
# if login_email_is_enable:
# if login_email_is_enable == "false":
# login_email_is_enable = "False"
# else:
# login_email_is_enable = "True"
# 批量更新配置
configs = [
(sys_config_key.KEY_PLATFORM_NAME, platform_name, "Platform name"),
(sys_config_key.KEY_PLATFORM_LOGO, platform_logo, "Platform logo"),
(sys_config_key.KEY_PLATFORM_LOGO, platform_logo, "Platform logo",),
(sys_config_key.KEY_PLATFORM_URL, platform_url, "Platform URL"),
(sys_config_key.KEY_WEBSITE_TITLE, website_title, "Website title"),
(sys_config_key.KEY_HEADLINE, headline, "Homepage title"),
(sys_config_key.KEY_SUBHEADLINE, subheadline, "Subtitle"),
(sys_config_key.KEY_LANGUAGE, language, "Language"),
(sys_config_key.KEY_THEME, theme, "Theme"),
(sys_config_key.KEY_ABOUT_PAGE, about_page, "About page"),
(sys_config_key.KEY_LOGIN_GOOGLE_CLIENT, login_google_client, "Google login client ID"),
(sys_config_key.KEY_LOGIN_GOOGLE_SECRET, login_google_secret, "Google login client secret"),
(sys_config_key.KEY_LOGIN_GOOGLE_ENABLE, login_google_enable, "谷歌登录是否启用"),
@@ -159,6 +189,8 @@ def set_sysconfig(
(sys_config_key.KEY_EMAIL_SMTP_USER, email_smtp_user, "邮件SMTP用户名"),
(sys_config_key.KEY_EMAIL_SMTP_PASSWORD, email_smtp_password, "邮件SMTP密码"),
(sys_config_key.KEY_EMAIL_SMTP_SENDER, email_smtp_sender, "邮件发送者地址"),
(sys_config_key.KEY_LOGIN_EMAIL_ENABLE, login_email_is_enable, "邮件是否启用"),
(sys_config_key.KEY_LOGIN_EMAIL_MODE, login_email_mode, "邮件模式"),
]
# 更新管理员用户名和密码
@@ -166,7 +198,10 @@ def set_sysconfig(
for key, value, desc in configs:
if value is not None: # 只更新有值的配置
sysconfig_service.set_value_by_key(key, value, desc)
is_large = False
if key == sys_config_key.KEY_ABOUT_PAGE:
is_large = True
sysconfig_service.set_value_by_key(key, value, desc,is_large)
return get_sysconfig(sysconfig_service, user_service)
@@ -0,0 +1,50 @@
from fastapi import APIRouter, UploadFile, Form, File
import hashlib
import os
import shutil
from datetime import datetime
from services.common.utils.response_utils import ResponseUtils
router = APIRouter()
@router.post("/image")
async def upload(
img: UploadFile = File(None),
sha256: str = Form(None),
):
# 1. 获取上传文件的名称
if not img:
return ResponseUtils.error(message="未提供文件", code=400)
filename = img.filename
if not filename:
return ResponseUtils.error(message="未提供文件名称", code=400)
# 2. 计算上传文件的sha256值
contents = await img.read()
file_hash = hashlib.sha256(contents).hexdigest()
# 重置文件指针,以便后续保存文件
await img.seek(0)
# 检查sha256是否一致
if sha256 and file_hash != sha256:
return ResponseUtils.error(message="文件SHA256校验失败", code=400)
# 3. 根据当前日期创建目录
today = datetime.now()
date_dir = today.strftime("%Y%m%d")
# 创建上传目录
upload_dir = os.path.join("uploads","images")
upload_dir = os.path.join(upload_dir, date_dir)
os.makedirs(upload_dir, exist_ok=True)
# 保存文件
file_path = os.path.join(upload_dir, filename)
with open(file_path, "wb") as f:
shutil.copyfileobj(img.file, f)
return ResponseUtils.success(data={
"file_path": file_path
})
+3
View File
@@ -23,6 +23,8 @@ from services.admin_service.controllers import web
from services.admin_service.controllers import admin_stats
from services.admin_service.controllers import user_stats
from services.admin_service.controllers import email_test
from services.admin_service.controllers import upload
from services.admin_service.consumers.billing_message_consumer import BillingMessageConsumer
from services.admin_service.middleware import AuthMiddleware
from services.common.middleware.exception_middleware import ExceptionHandlingMiddleware
@@ -158,6 +160,7 @@ app.include_router(web.router, prefix="/api/web")
app.include_router(admin_stats.router, prefix="/api/overview")
app.include_router(user_stats.router, prefix="/api/stats")
app.include_router(email_test.router, prefix="/api/email_test")
app.include_router(upload.router, prefix="/api/upload")
# Logging is already configured by setup_logging("admin_service")
@@ -0,0 +1,43 @@
import uuid
import secrets
from datetime import datetime, timezone
from sqlalchemy.orm import Session
from services.common.models.sys_config_large import SysConfigLarge
from typing import Optional
class SysConfigLargeRepository:
def __init__(self, db: Session):
self.db = db
def get_by_key(self, key: str) -> Optional[SysConfigLarge]:
return self.db.query(SysConfigLarge).filter(SysConfigLarge.key == key).first()
def get_value_by_key(self, key: str) -> Optional[str]:
sys_config = self.get_by_key(key)
if sys_config:
return sys_config.value
return None
def set_value_by_key(self, key: str, value: str,description:str) -> Optional[SysConfigLarge]:
sys_config = self.get_by_key(key)
if sys_config:
sys_config.value = value
sys_config.description = description
self.db.commit()
self.db.refresh(sys_config)
return sys_config
sys_config = SysConfigLarge(
id=str(uuid.uuid4()),
key=key,
value=value,
description=description,
created_at=datetime.now(timezone.utc),
updated_at=datetime.now(timezone.utc),
)
self.db.add(sys_config)
self.db.commit()
return sys_config
def delete_by_key(self, key: str) -> bool:
sys_config = self.get_by_key(key)
if sys_config:
self.db.delete(sys_config)
self.db.commit()
return True
return False
@@ -16,8 +16,16 @@ class UserRepository:
def get_by_account(self, name: str) -> Optional[User]:
return self.db.query(User).filter(User.name == name).first()
def update_password(self,user_id:str, password:str) -> Optional[User]:
user = self.get_by_id(user_id)
if not user:
return None
user.password = password
self.db.commit()
self.db.refresh(user)
return user
def create(self, email: str, register_type: str, role_id: int = 2) -> Optional[User]:
def create(self, email: str, register_type: str, role_id: int = 2, password: Optional[str] = None) -> Optional[User]:
from uuid import uuid4
from services.common.models.user import RegisterType
@@ -27,6 +35,7 @@ class UserRepository:
id=str(uuid4()),
name=name,
email=email,
password=password,
avatar=None,
is_active=1,
is_deleted=0,
@@ -57,7 +57,7 @@ class AuthService:
# Send verification code using HTML email template
return EmailUtils.send_register_code_email(self.db, email, captcha)
def email_login(self, email: str, captcha: str) -> Optional[str]:
def email_login_by_captcha(self, email: str, captcha: str) -> Optional[str]:
cache_value = CacheUtils.get_cache(RedisKeys.email_login_captcha(email))
if cache_value is None:
logger.warning(f"not found captcha, email: {email}")
@@ -82,6 +82,29 @@ class AuthService:
CacheUtils.set_cache(RedisKeys.email_login_captcha(email), None)
return token
return None
def email_login_by_password(self, email: str, password: str) -> Optional[str]:
user = self.user_repository.get_by_email(email)
# User doesn't exist, register first
if user is None:
user = self.user_repository.create(email=email, register_type="email", role_id=2,password=password)
if user is None:
logger.warning(f"Failed to register user with email: {email}")
return None
if user.password is None or user.password == "":
user = self.user_repository.update_password(user.id,password)
if user is None:
logger.warning(f"Failed to update user password with email: {email}")
return None
if user.password != password:
logger.warning("password not match")
return None
# Create user access token
token = self.create_user_token(user.id)
if token is None:
logger.warning(f"Failed to create user token for email: {email}")
return None
return token
def create_user_token(self, user_id: str) -> Optional[str]:
user_access_token = self.user_access_token_repository.create(user_id)
@@ -7,20 +7,27 @@ import logging
from services.common.models.sys_config import SysConfig
from services.admin_service.repositories.sys_config_repository import SysConfigRepository
from services.admin_service.repositories.sys_config_large_repository import SysConfigLargeRepository
logger = logging.getLogger(__name__)
logger = logging.getLogger(__name__)
class SysConfigService:
def __init__(self, db: Session = SessionLocal()):
self.sys_config_repository = SysConfigRepository(db)
self.sys_config_large_repository = SysConfigLargeRepository(db)
try:
self.redis_client = RedisClient()
except Exception as e:
logger.warning(f"Redis connection failed, cache will be disabled: {e}")
self.redis_client = None
def get_value_by_key(self, key: str) -> str:
def get_value_by_key(self, key: str, is_large:bool = False) -> str:
if is_large:
sys_config = self.sys_config_large_repository.get_by_key(key)
if sys_config:
return sys_config.value
return ""
"""Get config value, prioritize cache, fallback to database if cache miss"""
cache_key = RedisKeys.sys_config_key(key)
@@ -56,12 +63,15 @@ class SysConfigService:
self._clear_cache(key)
return result
def set_value_by_key(self, key: str, value: str, description: str) -> Optional[SysConfig]:
def set_value_by_key(self, key: str, value: str, description: str, is_large:bool = False):
if is_large:
self.sys_config_large_repository.set_value_by_key(key=key, value=value, description=description)
return
"""Set config value and clear cache"""
result = self.sys_config_repository.set_value_by_key(key=key, value=value, description=description)
if result:
self._clear_cache(key)
return result
return
def _clear_cache(self, key: str) -> None:
"""Clear cache for specified config"""
@@ -0,0 +1,32 @@
from sqlalchemy import BigInteger, String, DateTime
from sqlalchemy.sql import func
from sqlalchemy.orm import Mapped, mapped_column
from services.common.models.base import Base
from datetime import datetime
class SysConfigLarge(Base):
__tablename__ = "sys_config_large"
id: Mapped[str] = mapped_column(
String(36),
primary_key=True,
autoincrement=False,
comment="Primary key",
)
key: Mapped[str] = mapped_column(String(255), unique=True, nullable=False, comment="Configuration key")
value: Mapped[str] = mapped_column(String, nullable=False, comment="Configuration value")
description: Mapped[str] = mapped_column(String, nullable=False, comment="Configuration description")
created_at: Mapped[datetime] = mapped_column(
DateTime,
nullable=True,
server_default=func.current_timestamp(),
comment="Creation timestamp",
)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
nullable=True,
server_default=func.current_timestamp(),
server_onupdate=func.current_timestamp(),
comment="Last update timestamp",
)