fix: FOREIGN KEY constraint failed on POST /api/workspaces
Bug: create_workspace in dashboard.py set uid=1 when session was invalid, but user 1 might not exist in the users table, causing sqlite3.IntegrityError: FOREIGN KEY constraint failed (HTTP 500). Fix: ensure user row exists (INSERT OR IGNORE) before inserting workspace with FK reference, matching the pattern in workspace.py. Also: add name validation, use INSERT OR IGNORE for members.
This commit is contained in:
@@ -659,18 +659,27 @@ async def create_workspace(request: Request):
|
|||||||
import json
|
import json
|
||||||
body = await request.json()
|
body = await request.json()
|
||||||
name = body.get("name", "New Workspace").strip()
|
name = body.get("name", "New Workspace").strip()
|
||||||
|
if not name:
|
||||||
|
return {"error": "Name required"}
|
||||||
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
|
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
|
||||||
uid = user["id"] if user and user.get("id") else 1
|
uid = user["id"] if user and user.get("id") else 1
|
||||||
with get_conn() as conn:
|
with get_conn() as conn:
|
||||||
|
# Ensure user exists (FK constraint)
|
||||||
|
uid_ok = conn.execute("SELECT id FROM users WHERE id=?", (uid,)).fetchone()
|
||||||
|
if not uid_ok:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO users (id, login, full_name, is_admin) VALUES (?, ?, ?, 1)",
|
||||||
|
(uid, user.get("login", "admin") if user else "admin",
|
||||||
|
user.get("full_name", "Admin") if user else "Admin"),
|
||||||
|
)
|
||||||
cursor = conn.execute(
|
cursor = conn.execute(
|
||||||
"INSERT INTO workspaces (name, owner_id) VALUES (?, ?)",
|
"INSERT INTO workspaces (name, owner_id) VALUES (?, ?)",
|
||||||
(name, uid),
|
(name, uid),
|
||||||
)
|
)
|
||||||
conn.commit()
|
|
||||||
ws_id = cursor.lastrowid
|
ws_id = cursor.lastrowid
|
||||||
# Add owner as member
|
# Add owner as member
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"INSERT INTO workspace_members (workspace_id, user_id, role) VALUES (?, ?, 'owner')",
|
"INSERT OR IGNORE INTO workspace_members (workspace_id, user_id, role) VALUES (?, ?, 'owner')",
|
||||||
(ws_id, uid),
|
(ws_id, uid),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|||||||
Reference in New Issue
Block a user