Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions astrbot/core/db/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,13 @@ async def delete_platform_session(self, session_id: str) -> None:
"""Delete a Platform session by its ID."""
...

@abc.abstractmethod
async def migrate_user_webchat_data(
self, old_username: str, new_username: str
) -> None:
"""Migrate all webchat user data when username is changed."""
...

# ====
# ChatUI Project Management
# ====
Expand Down
41 changes: 41 additions & 0 deletions astrbot/core/db/sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -1616,6 +1616,47 @@ async def delete_platform_session(self, session_id: str) -> None:
),
)

async def migrate_user_webchat_data(
self, old_username: str, new_username: str
) -> None:
"""Migrate all webchat user data when username is changed."""
old_fragment = f"!{old_username}!"
new_fragment = f"!{new_username}!"
async with self.get_db() as session:
session: AsyncSession
async with session.begin():
await session.execute(
update(PlatformSession)
.where(col(PlatformSession.creator) == old_username)
.values(creator=new_username)
)
await session.execute(
update(ChatUIProject)
.where(col(ChatUIProject.creator) == old_username)
.values(creator=new_username)
)
await session.execute(
update(ConversationV2)
.where(col(ConversationV2.user_id).like("webchat%"))
.values(
user_id=func.replace(
ConversationV2.user_id, old_fragment, new_fragment
)
)
)
await session.execute(
update(Preference)
.where(
col(Preference.scope) == "umo",
col(Preference.scope_id).like("webchat%"),
)
.values(
scope_id=func.replace(
Preference.scope_id, old_fragment, new_fragment
)
)
)
Comment on lines +1628 to +1658
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The migration is missing several critical tables and columns that store webchat user identifiers. Specifically, PlatformMessageHistory.user_id, ProviderStat.umo, PlatformSession.session_id, and SessionProjectRelation.session_id should also be updated to ensure chat history, statistics, and project associations remain consistent after a username change. Additionally, adding a more specific filter to the WHERE clause (checking for the presence of old_fragment) improves efficiency and prevents unnecessary updates.

                await session.execute(
                    update(PlatformSession)
                    .where(col(PlatformSession.creator) == old_username)
                    .values(creator=new_username)
                )
                await session.execute(
                    update(PlatformSession)
                    .where(col(PlatformSession.platform_id) == "webchat", col(PlatformSession.session_id).contains(old_fragment))
                    .values(session_id=func.replace(PlatformSession.session_id, old_fragment, new_fragment))
                )
                await session.execute(
                    update(ChatUIProject)
                    .where(col(ChatUIProject.creator) == old_username)
                    .values(creator=new_username)
                )
                await session.execute(
                    update(ConversationV2)
                    .where(col(ConversationV2.user_id).like("webchat%"), col(ConversationV2.user_id).contains(old_fragment))
                    .values(user_id=func.replace(ConversationV2.user_id, old_fragment, new_fragment))
                )
                await session.execute(
                    update(PlatformMessageHistory)
                    .where(col(PlatformMessageHistory.platform_id) == "webchat", col(PlatformMessageHistory.user_id).contains(old_fragment))
                    .values(user_id=func.replace(PlatformMessageHistory.user_id, old_fragment, new_fragment))
                )
                await session.execute(
                    update(Preference)
                    .where(col(Preference.scope) == "umo", col(Preference.scope_id).contains(old_fragment))
                    .values(scope_id=func.replace(Preference.scope_id, old_fragment, new_fragment))
                )
                await session.execute(
                    update(SessionProjectRelation)
                    .where(col(SessionProjectRelation.session_id).contains(old_fragment))
                    .values(session_id=func.replace(SessionProjectRelation.session_id, old_fragment, new_fragment))
                )
                await session.execute(
                    update(ProviderStat)
                    .where(col(ProviderStat.umo).contains(old_fragment))
                    .values(umo=func.replace(ProviderStat.umo, old_fragment, new_fragment))
                )


# ====
# ChatUI Project Management
# ====
Expand Down
10 changes: 9 additions & 1 deletion astrbot/dashboard/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@

from astrbot import logger
from astrbot.core import DEMO_MODE
from astrbot.core.db import BaseDatabase

from .route import Response, Route, RouteContext


class AuthRoute(Route):
def __init__(self, context: RouteContext) -> None:
def __init__(self, context: RouteContext, db: BaseDatabase) -> None:
super().__init__(context)
self.db = db
self.routes = {
"/auth/login": ("POST", self.login),
"/auth/account/edit": ("POST", self.edit_account),
Expand Down Expand Up @@ -72,9 +74,15 @@ async def edit_account(self):
if confirm_pwd != new_pwd:
return Response().error("两次输入的新密码不一致").__dict__
self.config["dashboard"]["password"] = new_pwd

old_username = self.config["dashboard"]["username"]
if new_username:
self.config["dashboard"]["username"] = new_username

# Migrate webchat user data before saving config to keep them in sync.
if new_username and new_username != old_username:
await self.db.migrate_user_webchat_data(old_username, new_username)
Comment on lines +78 to +84
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The dashboard username is updated in the self.config object before the database migration is executed. If the migration fails (e.g., due to a database lock or constraint violation), the in-memory configuration will already hold the new username. On a subsequent retry, old_username will match new_username, causing the migration logic to be skipped entirely, leaving the database in an inconsistent state. The configuration should only be updated after the migration succeeds.

Suggested change
old_username = self.config["dashboard"]["username"]
if new_username:
self.config["dashboard"]["username"] = new_username
# Migrate webchat user data before saving config to keep them in sync.
if new_username and new_username != old_username:
await self.db.migrate_user_webchat_data(old_username, new_username)
old_username = self.config["dashboard"]["username"]
# Migrate webchat user data before updating config to ensure atomicity and prevent inconsistent state on failure.
if new_username and new_username != old_username:
await self.db.migrate_user_webchat_data(old_username, new_username)
if new_username:
self.config["dashboard"]["username"] = new_username
References
  1. In a single-threaded asyncio event loop, synchronous blocks are atomic, but atomicity is lost across 'await' points. State changes should be ordered to maintain consistency in case of failures during asynchronous operations.


self.config.save_config()

return Response().ok(None, "修改成功").__dict__
Expand Down
2 changes: 1 addition & 1 deletion astrbot/dashboard/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def __init__(
self.cr = ConfigRoute(self.context, core_lifecycle)
self.lr = LogRoute(self.context, core_lifecycle.log_broker)
self.sfr = StaticFileRoute(self.context)
self.ar = AuthRoute(self.context)
self.ar = AuthRoute(self.context, db)
self.api_key_route = ApiKeyRoute(self.context, db)
self.chat_route = ChatRoute(self.context, db, core_lifecycle)
self.open_api_route = OpenApiRoute(
Expand Down