Multi-user sharing, groups, and in-app notifications
Backend: - Alembic migration 0025: groups, group_memberships, project_shares, note_shares, notifications tables - models: Group, GroupMembership, ProjectShare, NoteShare, Notification - services/access.py: permission resolution (viewer/editor/admin/owner) - services/groups.py + routes/groups.py: full group CRUD + membership - services/sharing.py + routes/shares.py: project/note sharing API - services/notifications.py: in-app notification create/list/mark-read - routes/in_app_notifications.py: GET/POST notification endpoints - routes/users.py: user search endpoint - services/projects.py + services/notes.py: *_for_user variants - routes updated to use *_for_user on get/list; adds permission field - app.py: register all new blueprints Frontend: - api/client.ts: ShareEntry, GroupEntry, NotificationEntry types + helpers - stores/notifications.ts: Pinia store with polling - NotificationBell.vue: bell icon + badge + dropdown toggle + 60s poll - NotificationsPanel.vue: unread notification list with mark-all-read - ShareDialog.vue: teleport modal for sharing projects/notes with users/groups - SharedWithMeView.vue: /shared route listing shared projects and notes - AppHeader: NotificationBell, Shared nav link - ProjectView, NoteViewerView, TaskViewerView: Share button + ShareDialog - SettingsView: Groups admin tab with create/delete groups + member mgmt - router: /shared route Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,10 @@ from fabledassistant.routes.push import push_bp
|
||||
from fabledassistant.routes.quick_capture import quick_capture_bp
|
||||
from fabledassistant.routes.settings import settings_bp
|
||||
from fabledassistant.routes.tasks import tasks_bp
|
||||
from fabledassistant.routes.groups import groups_bp
|
||||
from fabledassistant.routes.shares import shares_bp
|
||||
from fabledassistant.routes.in_app_notifications import notifications_bp
|
||||
from fabledassistant.routes.users import users_bp
|
||||
|
||||
STATIC_DIR = Path(__file__).parent / "static"
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -67,6 +71,10 @@ def create_app() -> Quart:
|
||||
app.register_blueprint(settings_bp)
|
||||
app.register_blueprint(task_logs_bp)
|
||||
app.register_blueprint(tasks_bp)
|
||||
app.register_blueprint(groups_bp)
|
||||
app.register_blueprint(shares_bp)
|
||||
app.register_blueprint(notifications_bp)
|
||||
app.register_blueprint(users_bp)
|
||||
|
||||
@app.before_request
|
||||
async def before_request():
|
||||
|
||||
@@ -35,3 +35,6 @@ from fabledassistant.models.milestone import Milestone # noqa: E402, F401
|
||||
from fabledassistant.models.task_log import TaskLog # noqa: E402, F401
|
||||
from fabledassistant.models.note_draft import NoteDraft # noqa: E402, F401
|
||||
from fabledassistant.models.note_version import NoteVersion # noqa: E402, F401
|
||||
from fabledassistant.models.group import Group, GroupMembership # noqa: E402, F401
|
||||
from fabledassistant.models.share import NoteShare, ProjectShare # noqa: E402, F401
|
||||
from fabledassistant.models.notification import Notification # noqa: E402, F401
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import ForeignKey, Integer, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from fabledassistant.models import Base
|
||||
from fabledassistant.models.base import CreatedAtMixin, TimestampMixin
|
||||
|
||||
|
||||
class Group(Base, TimestampMixin):
|
||||
__tablename__ = "groups"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
name: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
|
||||
description: Mapped[str | None] = mapped_column(Text)
|
||||
created_by: Mapped[int | None] = mapped_column(
|
||||
Integer, ForeignKey("users.id", ondelete="SET NULL")
|
||||
)
|
||||
|
||||
memberships: Mapped[list["GroupMembership"]] = relationship(
|
||||
"GroupMembership", back_populates="group", cascade="all, delete-orphan"
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
"created_by": self.created_by,
|
||||
"created_at": self.created_at.isoformat(),
|
||||
"updated_at": self.updated_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
class GroupMembership(Base, CreatedAtMixin):
|
||||
__tablename__ = "group_memberships"
|
||||
__table_args__ = (UniqueConstraint("group_id", "user_id", name="uq_gm_group_user"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
group_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("groups.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
role: Mapped[str] = mapped_column(Text, nullable=False, default="member")
|
||||
|
||||
group: Mapped["Group"] = relationship("Group", back_populates="memberships")
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"group_id": self.group_id,
|
||||
"user_id": self.user_id,
|
||||
"role": self.role,
|
||||
"created_at": self.created_at.isoformat(),
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, Text
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from fabledassistant.models import Base
|
||||
from fabledassistant.models.base import CreatedAtMixin
|
||||
|
||||
|
||||
class Notification(Base, CreatedAtMixin):
|
||||
__tablename__ = "notifications"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
# project_shared | note_shared | group_added
|
||||
type: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
payload: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict)
|
||||
read_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"user_id": self.user_id,
|
||||
"type": self.type,
|
||||
"payload": self.payload,
|
||||
"read_at": self.read_at.isoformat() if self.read_at else None,
|
||||
"created_at": self.created_at.isoformat(),
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
from sqlalchemy import CheckConstraint, ForeignKey, Integer, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from fabledassistant.models import Base
|
||||
from fabledassistant.models.base import TimestampMixin
|
||||
|
||||
|
||||
class ProjectShare(Base, TimestampMixin):
|
||||
__tablename__ = "project_shares"
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"(shared_with_user_id IS NOT NULL) != (shared_with_group_id IS NOT NULL)",
|
||||
name="ck_ps_exclusive_target",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
project_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("projects.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
shared_with_user_id: Mapped[int | None] = mapped_column(
|
||||
Integer, ForeignKey("users.id", ondelete="CASCADE")
|
||||
)
|
||||
shared_with_group_id: Mapped[int | None] = mapped_column(
|
||||
Integer, ForeignKey("groups.id", ondelete="CASCADE")
|
||||
)
|
||||
permission: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
invited_by: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("users.id"), nullable=False
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"project_id": self.project_id,
|
||||
"shared_with_user_id": self.shared_with_user_id,
|
||||
"shared_with_group_id": self.shared_with_group_id,
|
||||
"permission": self.permission,
|
||||
"invited_by": self.invited_by,
|
||||
"created_at": self.created_at.isoformat(),
|
||||
"updated_at": self.updated_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
class NoteShare(Base, TimestampMixin):
|
||||
__tablename__ = "note_shares"
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"(shared_with_user_id IS NOT NULL) != (shared_with_group_id IS NOT NULL)",
|
||||
name="ck_ns_exclusive_target",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
note_id: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("notes.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
shared_with_user_id: Mapped[int | None] = mapped_column(
|
||||
Integer, ForeignKey("users.id", ondelete="CASCADE")
|
||||
)
|
||||
shared_with_group_id: Mapped[int | None] = mapped_column(
|
||||
Integer, ForeignKey("groups.id", ondelete="CASCADE")
|
||||
)
|
||||
permission: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
invited_by: Mapped[int] = mapped_column(
|
||||
Integer, ForeignKey("users.id"), nullable=False
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"note_id": self.note_id,
|
||||
"shared_with_user_id": self.shared_with_user_id,
|
||||
"shared_with_group_id": self.shared_with_group_id,
|
||||
"permission": self.permission,
|
||||
"invited_by": self.invited_by,
|
||||
"created_at": self.created_at.isoformat(),
|
||||
"updated_at": self.updated_at.isoformat(),
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import asyncio
|
||||
|
||||
from quart import Blueprint, g, jsonify, request
|
||||
|
||||
from fabledassistant.auth import get_current_user_id, login_required
|
||||
from fabledassistant.services import groups as group_svc
|
||||
from fabledassistant.services.notifications import notify_group_added
|
||||
|
||||
groups_bp = Blueprint("groups", __name__, url_prefix="/api/groups")
|
||||
|
||||
|
||||
@groups_bp.route("", methods=["GET"])
|
||||
@login_required
|
||||
async def list_groups():
|
||||
uid = get_current_user_id()
|
||||
return jsonify({"groups": await group_svc.list_groups(uid)})
|
||||
|
||||
|
||||
@groups_bp.route("", methods=["POST"])
|
||||
@login_required
|
||||
async def create_group():
|
||||
uid = get_current_user_id()
|
||||
data = await request.get_json()
|
||||
name = (data.get("name") or "").strip()
|
||||
if not name:
|
||||
return jsonify({"error": "Name is required"}), 400
|
||||
try:
|
||||
group = await group_svc.create_group(uid, name, data.get("description"))
|
||||
except Exception:
|
||||
return jsonify({"error": "Group name already taken"}), 409
|
||||
return jsonify(group.to_dict()), 201
|
||||
|
||||
|
||||
@groups_bp.route("/<int:group_id>", methods=["GET"])
|
||||
@login_required
|
||||
async def get_group(group_id: int):
|
||||
group = await group_svc.get_group(group_id)
|
||||
if not group:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
members = await group_svc.list_members(group_id)
|
||||
return jsonify({**group.to_dict(), "members": members})
|
||||
|
||||
|
||||
@groups_bp.route("/<int:group_id>", methods=["PATCH"])
|
||||
@login_required
|
||||
async def update_group(group_id: int):
|
||||
uid = get_current_user_id()
|
||||
data = await request.get_json()
|
||||
updates = {k: v for k, v in data.items() if k in ("name", "description")}
|
||||
group = await group_svc.update_group(uid, group_id, g.user.role == "admin", **updates)
|
||||
if not group:
|
||||
return jsonify({"error": "Not found or forbidden"}), 404
|
||||
return jsonify(group.to_dict())
|
||||
|
||||
|
||||
@groups_bp.route("/<int:group_id>", methods=["DELETE"])
|
||||
@login_required
|
||||
async def delete_group(group_id: int):
|
||||
uid = get_current_user_id()
|
||||
deleted = await group_svc.delete_group(uid, group_id, g.user.role == "admin")
|
||||
if not deleted:
|
||||
return jsonify({"error": "Not found or forbidden"}), 404
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
|
||||
@groups_bp.route("/<int:group_id>/members", methods=["GET"])
|
||||
@login_required
|
||||
async def list_members(group_id: int):
|
||||
members = await group_svc.list_members(group_id)
|
||||
return jsonify({"members": members})
|
||||
|
||||
|
||||
@groups_bp.route("/<int:group_id>/members", methods=["POST"])
|
||||
@login_required
|
||||
async def add_member(group_id: int):
|
||||
uid = get_current_user_id()
|
||||
data = await request.get_json()
|
||||
target_uid = data.get("user_id")
|
||||
role = data.get("role", "member")
|
||||
if not target_uid:
|
||||
return jsonify({"error": "user_id required"}), 400
|
||||
if role not in ("owner", "member"):
|
||||
return jsonify({"error": "role must be owner or member"}), 400
|
||||
membership = await group_svc.add_member(uid, group_id, target_uid, role, g.user.role == "admin")
|
||||
if not membership:
|
||||
return jsonify({"error": "Forbidden, group not found, or user already a member"}), 403
|
||||
asyncio.create_task(notify_group_added(group_id, role, uid, target_uid))
|
||||
return jsonify(membership.to_dict()), 201
|
||||
|
||||
|
||||
@groups_bp.route("/<int:group_id>/members/<int:target_uid>", methods=["PATCH"])
|
||||
@login_required
|
||||
async def update_member(group_id: int, target_uid: int):
|
||||
uid = get_current_user_id()
|
||||
data = await request.get_json()
|
||||
role = data.get("role")
|
||||
if role not in ("owner", "member"):
|
||||
return jsonify({"error": "role must be owner or member"}), 400
|
||||
m = await group_svc.update_member_role(uid, group_id, target_uid, role, g.user.role == "admin")
|
||||
if not m:
|
||||
return jsonify({"error": "Not found or forbidden"}), 404
|
||||
return jsonify(m.to_dict())
|
||||
|
||||
|
||||
@groups_bp.route("/<int:group_id>/members/<int:target_uid>", methods=["DELETE"])
|
||||
@login_required
|
||||
async def remove_member(group_id: int, target_uid: int):
|
||||
uid = get_current_user_id()
|
||||
removed = await group_svc.remove_member(uid, group_id, target_uid, g.user.role == "admin")
|
||||
if not removed:
|
||||
return jsonify({"error": "Not found or forbidden"}), 404
|
||||
return jsonify({"status": "ok"})
|
||||
@@ -0,0 +1,44 @@
|
||||
from quart import Blueprint, jsonify, request
|
||||
|
||||
from fabledassistant.auth import get_current_user_id, login_required
|
||||
from fabledassistant.services.notifications import (
|
||||
list_in_app_notifications,
|
||||
mark_all_notifications_read,
|
||||
mark_notification_read,
|
||||
unread_notification_count,
|
||||
)
|
||||
|
||||
notifications_bp = Blueprint("notifications", __name__, url_prefix="/api/notifications")
|
||||
|
||||
|
||||
@notifications_bp.route("", methods=["GET"])
|
||||
@login_required
|
||||
async def list_notifications():
|
||||
uid = get_current_user_id()
|
||||
all_flag = request.args.get("all", "false").lower() == "true"
|
||||
items = await list_in_app_notifications(uid, unread_only=not all_flag)
|
||||
return jsonify({"notifications": items})
|
||||
|
||||
|
||||
@notifications_bp.route("/count", methods=["GET"])
|
||||
@login_required
|
||||
async def get_count():
|
||||
uid = get_current_user_id()
|
||||
return jsonify({"count": await unread_notification_count(uid)})
|
||||
|
||||
|
||||
@notifications_bp.route("/<int:notif_id>/read", methods=["POST"])
|
||||
@login_required
|
||||
async def mark_read(notif_id: int):
|
||||
uid = get_current_user_id()
|
||||
if not await mark_notification_read(uid, notif_id):
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
|
||||
@notifications_bp.route("/read-all", methods=["POST"])
|
||||
@login_required
|
||||
async def mark_all_read():
|
||||
uid = get_current_user_id()
|
||||
count = await mark_all_notifications_read(uid)
|
||||
return jsonify({"status": "ok", "marked": count})
|
||||
@@ -26,6 +26,7 @@ from fabledassistant.services.notes import (
|
||||
get_backlinks,
|
||||
get_note,
|
||||
get_note_by_title,
|
||||
get_note_for_user,
|
||||
get_or_create_note_by_title,
|
||||
list_notes,
|
||||
update_note,
|
||||
@@ -189,10 +190,13 @@ async def resolve_title_route():
|
||||
@login_required
|
||||
async def get_note_route(note_id: int):
|
||||
uid = get_current_user_id()
|
||||
note = await get_note(uid, note_id)
|
||||
if note is None:
|
||||
result = await get_note_for_user(uid, note_id)
|
||||
if result is None:
|
||||
return not_found("Note")
|
||||
return jsonify(note.to_dict())
|
||||
note, permission = result
|
||||
data = note.to_dict()
|
||||
data["permission"] = permission
|
||||
return jsonify(data)
|
||||
|
||||
|
||||
@notes_bp.route("/<int:note_id>", methods=["PUT"])
|
||||
|
||||
@@ -11,8 +11,9 @@ from fabledassistant.services.projects import (
|
||||
create_project,
|
||||
delete_project,
|
||||
get_project,
|
||||
get_project_for_user,
|
||||
get_project_summary,
|
||||
list_projects,
|
||||
list_projects_for_user,
|
||||
update_project,
|
||||
)
|
||||
|
||||
@@ -26,8 +27,8 @@ projects_bp = Blueprint("projects", __name__, url_prefix="/api/projects")
|
||||
async def list_projects_route():
|
||||
uid = get_current_user_id()
|
||||
status = request.args.get("status")
|
||||
projects = await list_projects(uid, status=status)
|
||||
return jsonify({"projects": [p.to_dict() for p in projects]})
|
||||
projects = await list_projects_for_user(uid, status=status)
|
||||
return jsonify({"projects": projects})
|
||||
|
||||
|
||||
@projects_bp.route("", methods=["POST"])
|
||||
@@ -51,12 +52,16 @@ async def create_project_route():
|
||||
@login_required
|
||||
async def get_project_route(project_id: int):
|
||||
uid = get_current_user_id()
|
||||
project = await get_project(uid, project_id)
|
||||
if project is None:
|
||||
result = await get_project_for_user(uid, project_id)
|
||||
if result is None:
|
||||
return not_found("Project")
|
||||
summary = await get_project_summary(uid, project_id)
|
||||
project, permission = result
|
||||
# Summary uses the project owner's uid for stats when viewer is not the owner
|
||||
owner_uid = project.user_id or uid
|
||||
summary = await get_project_summary(owner_uid, project_id)
|
||||
data = project.to_dict()
|
||||
data["summary"] = summary
|
||||
data["permission"] = permission
|
||||
return jsonify(data)
|
||||
|
||||
|
||||
@@ -87,9 +92,10 @@ async def delete_project_route(project_id: int):
|
||||
@login_required
|
||||
async def get_project_notes_route(project_id: int):
|
||||
uid = get_current_user_id()
|
||||
project = await get_project(uid, project_id)
|
||||
if project is None:
|
||||
result = await get_project_for_user(uid, project_id)
|
||||
if result is None:
|
||||
return not_found("Project")
|
||||
project, _ = result
|
||||
|
||||
# type filter: "note", "task", or None (both)
|
||||
type_filter = request.args.get("type")
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import asyncio
|
||||
|
||||
from quart import Blueprint, jsonify, request
|
||||
|
||||
from fabledassistant.auth import get_current_user_id, login_required
|
||||
from fabledassistant.services import sharing as share_svc
|
||||
from fabledassistant.services.access import can_admin_project, can_write_note
|
||||
from fabledassistant.services.notifications import notify_note_shared, notify_project_shared
|
||||
from fabledassistant.services.sharing import list_shared_with_me
|
||||
|
||||
shares_bp = Blueprint("shares", __name__)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Project shares
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@shares_bp.route("/api/projects/<int:project_id>/shares", methods=["GET"])
|
||||
@login_required
|
||||
async def list_project_shares(project_id: int):
|
||||
uid = get_current_user_id()
|
||||
if not await can_admin_project(uid, project_id):
|
||||
return jsonify({"error": "Forbidden"}), 403
|
||||
return jsonify({"shares": await share_svc.list_project_shares(project_id)})
|
||||
|
||||
|
||||
@shares_bp.route("/api/projects/<int:project_id>/shares", methods=["POST"])
|
||||
@login_required
|
||||
async def create_project_share(project_id: int):
|
||||
uid = get_current_user_id()
|
||||
data = await request.get_json()
|
||||
share = await share_svc.share_project(
|
||||
uid, project_id,
|
||||
target_user_id=data.get("user_id"),
|
||||
target_group_id=data.get("group_id"),
|
||||
permission=data.get("permission", "viewer"),
|
||||
)
|
||||
if not share:
|
||||
return jsonify({"error": "Forbidden or invalid permission"}), 403
|
||||
asyncio.create_task(notify_project_shared(
|
||||
project_id, share.permission, uid,
|
||||
data.get("user_id"), data.get("group_id"),
|
||||
))
|
||||
return jsonify(share.to_dict()), 201
|
||||
|
||||
|
||||
@shares_bp.route("/api/projects/<int:project_id>/shares/<int:share_id>", methods=["PATCH"])
|
||||
@login_required
|
||||
async def update_project_share(project_id: int, share_id: int):
|
||||
uid = get_current_user_id()
|
||||
data = await request.get_json()
|
||||
share = await share_svc.update_project_share(uid, share_id, data.get("permission", ""))
|
||||
if not share:
|
||||
return jsonify({"error": "Not found or forbidden"}), 404
|
||||
return jsonify(share.to_dict())
|
||||
|
||||
|
||||
@shares_bp.route("/api/projects/<int:project_id>/shares/<int:share_id>", methods=["DELETE"])
|
||||
@login_required
|
||||
async def remove_project_share(project_id: int, share_id: int):
|
||||
uid = get_current_user_id()
|
||||
if not await share_svc.remove_project_share(uid, share_id):
|
||||
return jsonify({"error": "Not found or forbidden"}), 404
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Note / task shares
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@shares_bp.route("/api/notes/<int:note_id>/shares", methods=["GET"])
|
||||
@login_required
|
||||
async def list_note_shares(note_id: int):
|
||||
uid = get_current_user_id()
|
||||
if not await can_write_note(uid, note_id):
|
||||
return jsonify({"error": "Forbidden"}), 403
|
||||
return jsonify({"shares": await share_svc.list_note_shares(note_id)})
|
||||
|
||||
|
||||
@shares_bp.route("/api/notes/<int:note_id>/shares", methods=["POST"])
|
||||
@login_required
|
||||
async def create_note_share(note_id: int):
|
||||
uid = get_current_user_id()
|
||||
data = await request.get_json()
|
||||
share = await share_svc.share_note(
|
||||
uid, note_id,
|
||||
target_user_id=data.get("user_id"),
|
||||
target_group_id=data.get("group_id"),
|
||||
permission=data.get("permission", "viewer"),
|
||||
)
|
||||
if not share:
|
||||
return jsonify({"error": "Forbidden or invalid permission"}), 403
|
||||
asyncio.create_task(notify_note_shared(
|
||||
note_id, share.permission, uid,
|
||||
data.get("user_id"), data.get("group_id"),
|
||||
))
|
||||
return jsonify(share.to_dict()), 201
|
||||
|
||||
|
||||
@shares_bp.route("/api/notes/<int:note_id>/shares/<int:share_id>", methods=["PATCH"])
|
||||
@login_required
|
||||
async def update_note_share(note_id: int, share_id: int):
|
||||
uid = get_current_user_id()
|
||||
data = await request.get_json()
|
||||
share = await share_svc.update_note_share(uid, share_id, data.get("permission", ""))
|
||||
if not share:
|
||||
return jsonify({"error": "Not found or forbidden"}), 404
|
||||
return jsonify(share.to_dict())
|
||||
|
||||
|
||||
@shares_bp.route("/api/notes/<int:note_id>/shares/<int:share_id>", methods=["DELETE"])
|
||||
@login_required
|
||||
async def remove_note_share(note_id: int, share_id: int):
|
||||
uid = get_current_user_id()
|
||||
if not await share_svc.remove_note_share(uid, share_id):
|
||||
return jsonify({"error": "Not found or forbidden"}), 404
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Shared-with-me
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@shares_bp.route("/api/shared-with-me", methods=["GET"])
|
||||
@login_required
|
||||
async def shared_with_me():
|
||||
uid = get_current_user_id()
|
||||
return jsonify(await list_shared_with_me(uid))
|
||||
@@ -7,6 +7,7 @@ from fabledassistant.services.notes import (
|
||||
create_note,
|
||||
delete_note,
|
||||
get_note,
|
||||
get_note_for_user,
|
||||
list_notes,
|
||||
update_note,
|
||||
)
|
||||
@@ -99,10 +100,12 @@ async def create_task_route():
|
||||
@login_required
|
||||
async def get_task_route(task_id: int):
|
||||
uid = get_current_user_id()
|
||||
task = await get_note(uid, task_id)
|
||||
if task is None:
|
||||
result = await get_note_for_user(uid, task_id)
|
||||
if result is None:
|
||||
return not_found("Task")
|
||||
task, permission = result
|
||||
data = task.to_dict()
|
||||
data["permission"] = permission
|
||||
if task.parent_id:
|
||||
parent = await get_note(uid, task.parent_id)
|
||||
data["parent_title"] = parent.title if parent else None
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
from quart import Blueprint, jsonify, request
|
||||
from sqlalchemy import or_, select
|
||||
|
||||
from fabledassistant.auth import get_current_user_id, login_required
|
||||
from fabledassistant.models import async_session
|
||||
from fabledassistant.models.user import User
|
||||
|
||||
users_bp = Blueprint("users", __name__, url_prefix="/api/users")
|
||||
|
||||
|
||||
@users_bp.route("/search", methods=["GET"])
|
||||
@login_required
|
||||
async def search_users():
|
||||
uid = get_current_user_id()
|
||||
q = (request.args.get("q") or "").strip()
|
||||
if len(q) < 2:
|
||||
return jsonify({"users": []})
|
||||
like = f"{q}%"
|
||||
async with async_session() as session:
|
||||
users = (await session.execute(
|
||||
select(User).where(
|
||||
User.id != uid,
|
||||
or_(User.username.ilike(like), User.email.ilike(like)),
|
||||
).limit(10)
|
||||
)).scalars().all()
|
||||
return jsonify({"users": [
|
||||
{"id": u.id, "username": u.username, "email": u.email}
|
||||
for u in users
|
||||
]})
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Access control service.
|
||||
|
||||
Single source of truth for permission resolution on projects and notes.
|
||||
All human-facing routes that should honour shares call these functions.
|
||||
LLM tool routes continue to use owner-scoped service functions directly.
|
||||
|
||||
Permission rank: owner > admin > editor > viewer
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from fabledassistant.models import async_session
|
||||
from fabledassistant.models.group import GroupMembership
|
||||
from fabledassistant.models.note import Note
|
||||
from fabledassistant.models.project import Project
|
||||
from fabledassistant.models.share import NoteShare, ProjectShare
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PERMISSION_RANK: dict[str, int] = {
|
||||
"viewer": 1,
|
||||
"editor": 2,
|
||||
"admin": 3,
|
||||
"owner": 4,
|
||||
}
|
||||
|
||||
|
||||
def _higher(a: str | None, b: str | None) -> str | None:
|
||||
"""Return the higher-ranked permission, or None if both are None."""
|
||||
if a is None:
|
||||
return b
|
||||
if b is None:
|
||||
return a
|
||||
return a if PERMISSION_RANK[a] >= PERMISSION_RANK[b] else b
|
||||
|
||||
|
||||
async def _user_group_ids(session, user_id: int) -> list[int]:
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(GroupMembership.group_id).where(GroupMembership.user_id == user_id)
|
||||
)
|
||||
).scalars().all()
|
||||
return list(rows)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Project permissions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def get_project_permission(user_id: int, project_id: int) -> str | None:
|
||||
"""Return the effective permission string for user on project, or None."""
|
||||
async with async_session() as session:
|
||||
project = await session.get(Project, project_id)
|
||||
if project is None:
|
||||
return None
|
||||
if project.user_id == user_id:
|
||||
return "owner"
|
||||
|
||||
# Direct share
|
||||
direct = (
|
||||
await session.execute(
|
||||
select(ProjectShare).where(
|
||||
ProjectShare.project_id == project_id,
|
||||
ProjectShare.shared_with_user_id == user_id,
|
||||
)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
|
||||
# Group shares
|
||||
group_ids = await _user_group_ids(session, user_id)
|
||||
group_perm: str | None = None
|
||||
if group_ids:
|
||||
group_shares = (
|
||||
await session.execute(
|
||||
select(ProjectShare).where(
|
||||
ProjectShare.project_id == project_id,
|
||||
ProjectShare.shared_with_group_id.in_(group_ids),
|
||||
)
|
||||
)
|
||||
).scalars().all()
|
||||
for gs in group_shares:
|
||||
group_perm = _higher(group_perm, gs.permission)
|
||||
|
||||
return _higher(direct.permission if direct else None, group_perm)
|
||||
|
||||
|
||||
async def can_read_project(user_id: int, project_id: int) -> bool:
|
||||
return (await get_project_permission(user_id, project_id)) is not None
|
||||
|
||||
|
||||
async def can_write_project(user_id: int, project_id: int) -> bool:
|
||||
perm = await get_project_permission(user_id, project_id)
|
||||
return perm in ("editor", "admin", "owner")
|
||||
|
||||
|
||||
async def can_admin_project(user_id: int, project_id: int) -> bool:
|
||||
perm = await get_project_permission(user_id, project_id)
|
||||
return perm in ("admin", "owner")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Note / task permissions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def get_note_permission(user_id: int, note_id: int) -> str | None:
|
||||
"""Return the effective permission for user on a note/task, or None.
|
||||
|
||||
Resolution order:
|
||||
1. Ownership
|
||||
2. Direct note share
|
||||
3. Group-based note share
|
||||
4. Inherited from project share (if note belongs to a project)
|
||||
Highest rank wins.
|
||||
"""
|
||||
async with async_session() as session:
|
||||
note = await session.get(Note, note_id)
|
||||
if note is None:
|
||||
return None
|
||||
if note.user_id == user_id:
|
||||
return "owner"
|
||||
|
||||
direct = (
|
||||
await session.execute(
|
||||
select(NoteShare).where(
|
||||
NoteShare.note_id == note_id,
|
||||
NoteShare.shared_with_user_id == user_id,
|
||||
)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
|
||||
group_ids = await _user_group_ids(session, user_id)
|
||||
group_perm: str | None = None
|
||||
if group_ids:
|
||||
group_shares = (
|
||||
await session.execute(
|
||||
select(NoteShare).where(
|
||||
NoteShare.note_id == note_id,
|
||||
NoteShare.shared_with_group_id.in_(group_ids),
|
||||
)
|
||||
)
|
||||
).scalars().all()
|
||||
for gs in group_shares:
|
||||
group_perm = _higher(group_perm, gs.permission)
|
||||
|
||||
note_perm = _higher(direct.permission if direct else None, group_perm)
|
||||
|
||||
# Inherit from project if note belongs to one
|
||||
if note.project_id is not None:
|
||||
project_perm = await get_project_permission(user_id, note.project_id)
|
||||
note_perm = _higher(note_perm, project_perm)
|
||||
|
||||
return note_perm
|
||||
|
||||
|
||||
async def can_read_note(user_id: int, note_id: int) -> bool:
|
||||
return (await get_note_permission(user_id, note_id)) is not None
|
||||
|
||||
|
||||
async def can_write_note(user_id: int, note_id: int) -> bool:
|
||||
perm = await get_note_permission(user_id, note_id)
|
||||
return perm in ("editor", "admin", "owner")
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Group management service."""
|
||||
|
||||
import logging
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from fabledassistant.models import async_session
|
||||
from fabledassistant.models.group import Group, GroupMembership
|
||||
from fabledassistant.models.user import User
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def create_group(
|
||||
user_id: int, name: str, description: str | None = None
|
||||
) -> Group:
|
||||
async with async_session() as session:
|
||||
group = Group(name=name, description=description, created_by=user_id)
|
||||
session.add(group)
|
||||
await session.flush()
|
||||
session.add(GroupMembership(group_id=group.id, user_id=user_id, role="owner"))
|
||||
await session.commit()
|
||||
await session.refresh(group)
|
||||
return group
|
||||
|
||||
|
||||
async def list_groups(user_id: int) -> list[dict]:
|
||||
"""All users see all groups with member count and their own membership status."""
|
||||
async with async_session() as session:
|
||||
groups = (await session.execute(select(Group).order_by(Group.name))).scalars().all()
|
||||
user_group_ids = set(
|
||||
(await session.execute(
|
||||
select(GroupMembership.group_id).where(GroupMembership.user_id == user_id)
|
||||
)).scalars().all()
|
||||
)
|
||||
result = []
|
||||
for g in groups:
|
||||
count = len(
|
||||
(await session.execute(
|
||||
select(GroupMembership).where(GroupMembership.group_id == g.id)
|
||||
)).scalars().all()
|
||||
)
|
||||
d = g.to_dict()
|
||||
d["member_count"] = count
|
||||
d["is_member"] = g.id in user_group_ids
|
||||
result.append(d)
|
||||
return result
|
||||
|
||||
|
||||
async def get_group(group_id: int) -> Group | None:
|
||||
async with async_session() as session:
|
||||
return await session.get(Group, group_id)
|
||||
|
||||
|
||||
async def _is_group_owner(session, acting_user_id: int, group_id: int) -> bool:
|
||||
m = (await session.execute(
|
||||
select(GroupMembership).where(
|
||||
GroupMembership.group_id == group_id,
|
||||
GroupMembership.user_id == acting_user_id,
|
||||
GroupMembership.role == "owner",
|
||||
)
|
||||
)).scalar_one_or_none()
|
||||
return m is not None
|
||||
|
||||
|
||||
async def update_group(
|
||||
acting_user_id: int, group_id: int, is_site_admin: bool, **fields
|
||||
) -> Group | None:
|
||||
async with async_session() as session:
|
||||
group = await session.get(Group, group_id)
|
||||
if not group:
|
||||
return None
|
||||
if not is_site_admin and not await _is_group_owner(session, acting_user_id, group_id):
|
||||
return None
|
||||
for k, v in fields.items():
|
||||
if hasattr(group, k):
|
||||
setattr(group, k, v)
|
||||
await session.commit()
|
||||
await session.refresh(group)
|
||||
return group
|
||||
|
||||
|
||||
async def delete_group(acting_user_id: int, group_id: int, is_site_admin: bool) -> bool:
|
||||
async with async_session() as session:
|
||||
group = await session.get(Group, group_id)
|
||||
if not group:
|
||||
return False
|
||||
if not is_site_admin and group.created_by != acting_user_id:
|
||||
return False
|
||||
await session.delete(group)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
|
||||
async def list_members(group_id: int) -> list[dict]:
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(GroupMembership, User)
|
||||
.join(User, User.id == GroupMembership.user_id)
|
||||
.where(GroupMembership.group_id == group_id)
|
||||
)).all()
|
||||
return [
|
||||
{**m.to_dict(), "username": u.username, "email": u.email}
|
||||
for m, u in rows
|
||||
]
|
||||
|
||||
|
||||
async def add_member(
|
||||
acting_user_id: int,
|
||||
group_id: int,
|
||||
target_user_id: int,
|
||||
role: str,
|
||||
is_site_admin: bool,
|
||||
) -> GroupMembership | None:
|
||||
async with async_session() as session:
|
||||
if not is_site_admin and not await _is_group_owner(session, acting_user_id, group_id):
|
||||
return None
|
||||
membership = GroupMembership(group_id=group_id, user_id=target_user_id, role=role)
|
||||
session.add(membership)
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError:
|
||||
await session.rollback()
|
||||
return None
|
||||
await session.refresh(membership)
|
||||
return membership
|
||||
|
||||
|
||||
async def update_member_role(
|
||||
acting_user_id: int,
|
||||
group_id: int,
|
||||
target_user_id: int,
|
||||
role: str,
|
||||
is_site_admin: bool,
|
||||
) -> GroupMembership | None:
|
||||
async with async_session() as session:
|
||||
if not is_site_admin and not await _is_group_owner(session, acting_user_id, group_id):
|
||||
return None
|
||||
m = (await session.execute(
|
||||
select(GroupMembership).where(
|
||||
GroupMembership.group_id == group_id,
|
||||
GroupMembership.user_id == target_user_id,
|
||||
)
|
||||
)).scalar_one_or_none()
|
||||
if not m:
|
||||
return None
|
||||
m.role = role
|
||||
await session.commit()
|
||||
await session.refresh(m)
|
||||
return m
|
||||
|
||||
|
||||
async def remove_member(
|
||||
acting_user_id: int,
|
||||
group_id: int,
|
||||
target_user_id: int,
|
||||
is_site_admin: bool,
|
||||
) -> bool:
|
||||
"""Group owner, site admin, or self-removal are all permitted."""
|
||||
async with async_session() as session:
|
||||
is_self = acting_user_id == target_user_id
|
||||
if not is_site_admin and not is_self:
|
||||
if not await _is_group_owner(session, acting_user_id, group_id):
|
||||
return False
|
||||
m = (await session.execute(
|
||||
select(GroupMembership).where(
|
||||
GroupMembership.group_id == group_id,
|
||||
GroupMembership.user_id == target_user_id,
|
||||
)
|
||||
)).scalar_one_or_none()
|
||||
if not m:
|
||||
return False
|
||||
await session.delete(m)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
|
||||
async def get_user_groups(user_id: int) -> list[Group]:
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(Group)
|
||||
.join(GroupMembership, GroupMembership.group_id == Group.id)
|
||||
.where(GroupMembership.user_id == user_id)
|
||||
)).scalars().all()
|
||||
return list(rows)
|
||||
@@ -441,3 +441,20 @@ async def build_note_graph(
|
||||
edges.append({"source": nid, "target": tag_node_id, "type": "tag"})
|
||||
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Shared-access variant
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def get_note_for_user(
|
||||
accessing_user_id: int, note_id: int
|
||||
) -> tuple["Note", str] | None:
|
||||
"""Returns (note, permission) if user has any access, else None."""
|
||||
from fabledassistant.services.access import get_note_permission
|
||||
perm = await get_note_permission(accessing_user_id, note_id)
|
||||
if perm is None:
|
||||
return None
|
||||
async with async_session() as session:
|
||||
note = await session.get(Note, note_id)
|
||||
return (note, perm) if note else None
|
||||
|
||||
@@ -249,3 +249,199 @@ def start_notification_loop() -> None:
|
||||
global _notification_task
|
||||
if _notification_task is None or _notification_task.done():
|
||||
_notification_task = asyncio.create_task(_notification_loop())
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# In-app notifications (Notification model — shares, group events)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def create_in_app_notification(user_id: int, notif_type: str, payload: dict):
|
||||
"""Create an in-app Notification record."""
|
||||
from fabledassistant.models.notification import Notification
|
||||
async with async_session() as session:
|
||||
n = Notification(user_id=user_id, type=notif_type, payload=payload)
|
||||
session.add(n)
|
||||
await session.commit()
|
||||
await session.refresh(n)
|
||||
return n
|
||||
|
||||
|
||||
async def _fire_push_notif(user_id: int, title: str, body: str, url: str) -> None:
|
||||
try:
|
||||
from fabledassistant.services.push import send_push_notification
|
||||
await send_push_notification(user_id, title, body, url=url)
|
||||
except Exception:
|
||||
logger.exception("Push notification failed for user %d", user_id)
|
||||
|
||||
|
||||
async def _fire_share_email(user_id: int, subject: str, body_text: str) -> None:
|
||||
try:
|
||||
if not await is_smtp_configured():
|
||||
return
|
||||
async with async_session() as session:
|
||||
user = await session.get(User, user_id)
|
||||
if user and user.email:
|
||||
html = _email_html(subject, f"<p>{body_text.replace(chr(10), '<br>')}</p>")
|
||||
await send_email(user.email, subject, html)
|
||||
except Exception:
|
||||
logger.exception("Share email notification failed for user %d", user_id)
|
||||
|
||||
|
||||
async def _group_member_ids(group_id: int) -> list[int]:
|
||||
from fabledassistant.models.group import GroupMembership
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(GroupMembership.user_id).where(GroupMembership.group_id == group_id)
|
||||
)).scalars().all()
|
||||
return list(rows)
|
||||
|
||||
|
||||
async def notify_project_shared(
|
||||
project_id: int,
|
||||
permission: str,
|
||||
invited_by_user_id: int,
|
||||
target_user_id: int | None,
|
||||
target_group_id: int | None,
|
||||
) -> None:
|
||||
from fabledassistant.models.project import Project
|
||||
async with async_session() as session:
|
||||
project = await session.get(Project, project_id)
|
||||
inviter = await session.get(User, invited_by_user_id)
|
||||
if not project or not inviter:
|
||||
return
|
||||
|
||||
recipients: list[int] = []
|
||||
if target_user_id:
|
||||
recipients = [target_user_id]
|
||||
elif target_group_id:
|
||||
recipients = [uid for uid in await _group_member_ids(target_group_id) if uid != invited_by_user_id]
|
||||
|
||||
url = f"/projects/{project_id}"
|
||||
msg = f"{inviter.username} shared \"{project.title}\" with you as {permission}"
|
||||
|
||||
for uid in recipients:
|
||||
await create_in_app_notification(uid, "project_shared", {
|
||||
"project_id": project_id,
|
||||
"project_title": project.title,
|
||||
"permission": permission,
|
||||
"invited_by": inviter.username,
|
||||
"url": url,
|
||||
})
|
||||
asyncio.create_task(_fire_push_notif(uid, "Project shared with you", msg, url))
|
||||
asyncio.create_task(_fire_share_email(uid, f"[Fabled] {inviter.username} shared a project with you", msg))
|
||||
|
||||
|
||||
async def notify_note_shared(
|
||||
note_id: int,
|
||||
permission: str,
|
||||
invited_by_user_id: int,
|
||||
target_user_id: int | None,
|
||||
target_group_id: int | None,
|
||||
) -> None:
|
||||
from fabledassistant.models.note import Note
|
||||
async with async_session() as session:
|
||||
note = await session.get(Note, note_id)
|
||||
inviter = await session.get(User, invited_by_user_id)
|
||||
if not note or not inviter:
|
||||
return
|
||||
|
||||
recipients: list[int] = []
|
||||
if target_user_id:
|
||||
recipients = [target_user_id]
|
||||
elif target_group_id:
|
||||
recipients = [uid for uid in await _group_member_ids(target_group_id) if uid != invited_by_user_id]
|
||||
|
||||
route = "tasks" if note.is_task else "notes"
|
||||
url = f"/{route}/{note_id}"
|
||||
msg = f"{inviter.username} shared \"{note.title}\" with you as {permission}"
|
||||
|
||||
for uid in recipients:
|
||||
await create_in_app_notification(uid, "note_shared", {
|
||||
"note_id": note_id,
|
||||
"note_title": note.title,
|
||||
"permission": permission,
|
||||
"invited_by": inviter.username,
|
||||
"url": url,
|
||||
})
|
||||
asyncio.create_task(_fire_push_notif(uid, "Note shared with you", msg, url))
|
||||
asyncio.create_task(_fire_share_email(uid, f"[Fabled] {inviter.username} shared a note with you", msg))
|
||||
|
||||
|
||||
async def notify_group_added(
|
||||
group_id: int, role: str, invited_by_user_id: int, target_user_id: int
|
||||
) -> None:
|
||||
from fabledassistant.models.group import Group
|
||||
async with async_session() as session:
|
||||
group = await session.get(Group, group_id)
|
||||
inviter = await session.get(User, invited_by_user_id)
|
||||
if not group or not inviter:
|
||||
return
|
||||
|
||||
url = f"/groups/{group_id}"
|
||||
msg = f"{inviter.username} added you to group \"{group.name}\" as {role}"
|
||||
|
||||
await create_in_app_notification(target_user_id, "group_added", {
|
||||
"group_id": group_id,
|
||||
"group_name": group.name,
|
||||
"role": role,
|
||||
"invited_by": inviter.username,
|
||||
"url": url,
|
||||
})
|
||||
asyncio.create_task(_fire_push_notif(target_user_id, "Added to a group", msg, url))
|
||||
asyncio.create_task(_fire_share_email(target_user_id, "[Fabled] You've been added to a group", msg))
|
||||
|
||||
|
||||
async def list_in_app_notifications(user_id: int, unread_only: bool = True) -> list[dict]:
|
||||
from fabledassistant.models.notification import Notification
|
||||
async with async_session() as session:
|
||||
q = select(Notification).where(Notification.user_id == user_id)
|
||||
if unread_only:
|
||||
q = q.where(Notification.read_at.is_(None))
|
||||
q = q.order_by(Notification.created_at.desc()).limit(50)
|
||||
rows = (await session.execute(q)).scalars().all()
|
||||
return [n.to_dict() for n in rows]
|
||||
|
||||
|
||||
async def unread_notification_count(user_id: int) -> int:
|
||||
from fabledassistant.models.notification import Notification
|
||||
async with async_session() as session:
|
||||
result = await session.execute(
|
||||
select(func.count()).where(
|
||||
Notification.user_id == user_id,
|
||||
Notification.read_at.is_(None),
|
||||
)
|
||||
)
|
||||
return result.scalar() or 0
|
||||
|
||||
|
||||
async def mark_notification_read(user_id: int, notification_id: int) -> bool:
|
||||
from fabledassistant.models.notification import Notification
|
||||
from datetime import timezone as tz
|
||||
async with async_session() as session:
|
||||
n = (await session.execute(
|
||||
select(Notification).where(
|
||||
Notification.id == notification_id,
|
||||
Notification.user_id == user_id,
|
||||
)
|
||||
)).scalar_one_or_none()
|
||||
if not n:
|
||||
return False
|
||||
from datetime import datetime
|
||||
n.read_at = datetime.now(tz.utc)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
|
||||
async def mark_all_notifications_read(user_id: int) -> int:
|
||||
from fabledassistant.models.notification import Notification
|
||||
from datetime import datetime, timezone as tz
|
||||
from sqlalchemy import update as sa_update
|
||||
async with async_session() as session:
|
||||
result = await session.execute(
|
||||
sa_update(Notification)
|
||||
.where(Notification.user_id == user_id, Notification.read_at.is_(None))
|
||||
.values(read_at=datetime.now(tz.utc))
|
||||
.returning(Notification.id)
|
||||
)
|
||||
await session.commit()
|
||||
return len(result.fetchall())
|
||||
|
||||
@@ -144,3 +144,78 @@ async def get_project_summary(user_id: int, project_id: int) -> dict:
|
||||
"last_activity": last_activity_result.isoformat() if last_activity_result else None,
|
||||
"milestone_summary": milestone_summary,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Shared-access variants (honour ProjectShare in addition to ownership)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def get_project_for_user(
|
||||
accessing_user_id: int, project_id: int
|
||||
) -> tuple[Project, str] | None:
|
||||
"""Returns (project, permission) if user has any access, else None."""
|
||||
from fabledassistant.services.access import get_project_permission
|
||||
perm = await get_project_permission(accessing_user_id, project_id)
|
||||
if perm is None:
|
||||
return None
|
||||
async with async_session() as session:
|
||||
project = await session.get(Project, project_id)
|
||||
return (project, perm) if project else None
|
||||
|
||||
|
||||
async def list_projects_for_user(user_id: int, status: str | None = None) -> list[dict]:
|
||||
"""Owned projects + shared projects, each dict has 'permission' field."""
|
||||
from fabledassistant.models.group import GroupMembership
|
||||
from fabledassistant.models.share import ProjectShare
|
||||
from fabledassistant.services.access import PERMISSION_RANK
|
||||
|
||||
owned = await list_projects(user_id, status)
|
||||
owned_ids = {p.id for p in owned}
|
||||
|
||||
result = []
|
||||
for p in owned:
|
||||
d = p.to_dict() if hasattr(p, "to_dict") else {"id": p.id, "title": p.title}
|
||||
d["permission"] = "owner"
|
||||
result.append(d)
|
||||
|
||||
async with async_session() as session:
|
||||
user_group_ids = (await session.execute(
|
||||
select(GroupMembership.group_id).where(GroupMembership.user_id == user_id)
|
||||
)).scalars().all()
|
||||
|
||||
shared_direct = (await session.execute(
|
||||
select(ProjectShare).where(ProjectShare.shared_with_user_id == user_id)
|
||||
)).scalars().all()
|
||||
|
||||
shared_group: list[ProjectShare] = []
|
||||
if user_group_ids:
|
||||
shared_group = (await session.execute(
|
||||
select(ProjectShare).where(
|
||||
ProjectShare.shared_with_group_id.in_(user_group_ids)
|
||||
)
|
||||
)).scalars().all()
|
||||
|
||||
seen: dict[int, str] = {}
|
||||
for share in list(shared_direct) + list(shared_group):
|
||||
if share.project_id in owned_ids:
|
||||
continue
|
||||
prev = seen.get(share.project_id)
|
||||
if prev is None or PERMISSION_RANK[share.permission] > PERMISSION_RANK[prev]:
|
||||
seen[share.project_id] = share.permission
|
||||
|
||||
for pid, perm in seen.items():
|
||||
if status:
|
||||
async with async_session() as session:
|
||||
proj = await session.get(Project, pid)
|
||||
if not proj or proj.status != status:
|
||||
continue
|
||||
else:
|
||||
async with async_session() as session:
|
||||
proj = await session.get(Project, pid)
|
||||
if proj:
|
||||
d = proj.to_dict() if hasattr(proj, "to_dict") else {"id": proj.id, "title": proj.title}
|
||||
d["permission"] = perm
|
||||
d["is_shared"] = True
|
||||
result.append(d)
|
||||
|
||||
return result
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
"""Sharing service — create/manage project and note shares."""
|
||||
|
||||
import logging
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from fabledassistant.models import async_session
|
||||
from fabledassistant.models.group import Group, GroupMembership
|
||||
from fabledassistant.models.note import Note
|
||||
from fabledassistant.models.project import Project
|
||||
from fabledassistant.models.share import NoteShare, ProjectShare
|
||||
from fabledassistant.models.user import User
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VALID_PERMISSIONS = {"viewer", "editor", "admin"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Project shares
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def share_project(
|
||||
acting_user_id: int,
|
||||
project_id: int,
|
||||
*,
|
||||
target_user_id: int | None = None,
|
||||
target_group_id: int | None = None,
|
||||
permission: str = "viewer",
|
||||
) -> ProjectShare | None:
|
||||
if permission not in VALID_PERMISSIONS:
|
||||
return None
|
||||
from fabledassistant.services.access import can_admin_project
|
||||
if not await can_admin_project(acting_user_id, project_id):
|
||||
return None
|
||||
async with async_session() as session:
|
||||
share = ProjectShare(
|
||||
project_id=project_id,
|
||||
shared_with_user_id=target_user_id,
|
||||
shared_with_group_id=target_group_id,
|
||||
permission=permission,
|
||||
invited_by=acting_user_id,
|
||||
)
|
||||
session.add(share)
|
||||
await session.commit()
|
||||
await session.refresh(share)
|
||||
return share
|
||||
|
||||
|
||||
async def update_project_share(
|
||||
acting_user_id: int, share_id: int, permission: str
|
||||
) -> ProjectShare | None:
|
||||
if permission not in VALID_PERMISSIONS:
|
||||
return None
|
||||
async with async_session() as session:
|
||||
share = await session.get(ProjectShare, share_id)
|
||||
if not share:
|
||||
return None
|
||||
from fabledassistant.services.access import can_admin_project
|
||||
if not await can_admin_project(acting_user_id, share.project_id):
|
||||
return None
|
||||
share.permission = permission
|
||||
await session.commit()
|
||||
await session.refresh(share)
|
||||
return share
|
||||
|
||||
|
||||
async def remove_project_share(acting_user_id: int, share_id: int) -> bool:
|
||||
async with async_session() as session:
|
||||
share = await session.get(ProjectShare, share_id)
|
||||
if not share:
|
||||
return False
|
||||
from fabledassistant.services.access import can_admin_project
|
||||
if not await can_admin_project(acting_user_id, share.project_id):
|
||||
return False
|
||||
await session.delete(share)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
|
||||
async def list_project_shares(project_id: int) -> list[dict]:
|
||||
async with async_session() as session:
|
||||
shares = (await session.execute(
|
||||
select(ProjectShare).where(ProjectShare.project_id == project_id)
|
||||
)).scalars().all()
|
||||
result = []
|
||||
for s in shares:
|
||||
d = s.to_dict()
|
||||
if s.shared_with_user_id:
|
||||
user = await session.get(User, s.shared_with_user_id)
|
||||
d["username"] = user.username if user else None
|
||||
if s.shared_with_group_id:
|
||||
group = await session.get(Group, s.shared_with_group_id)
|
||||
d["group_name"] = group.name if group else None
|
||||
result.append(d)
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Note shares
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def share_note(
|
||||
acting_user_id: int,
|
||||
note_id: int,
|
||||
*,
|
||||
target_user_id: int | None = None,
|
||||
target_group_id: int | None = None,
|
||||
permission: str = "viewer",
|
||||
) -> NoteShare | None:
|
||||
if permission not in VALID_PERMISSIONS:
|
||||
return None
|
||||
from fabledassistant.services.access import get_note_permission
|
||||
perm = await get_note_permission(acting_user_id, note_id)
|
||||
if perm not in ("admin", "owner"):
|
||||
return None
|
||||
async with async_session() as session:
|
||||
share = NoteShare(
|
||||
note_id=note_id,
|
||||
shared_with_user_id=target_user_id,
|
||||
shared_with_group_id=target_group_id,
|
||||
permission=permission,
|
||||
invited_by=acting_user_id,
|
||||
)
|
||||
session.add(share)
|
||||
await session.commit()
|
||||
await session.refresh(share)
|
||||
return share
|
||||
|
||||
|
||||
async def update_note_share(
|
||||
acting_user_id: int, share_id: int, permission: str
|
||||
) -> NoteShare | None:
|
||||
if permission not in VALID_PERMISSIONS:
|
||||
return None
|
||||
async with async_session() as session:
|
||||
share = await session.get(NoteShare, share_id)
|
||||
if not share:
|
||||
return None
|
||||
from fabledassistant.services.access import get_note_permission
|
||||
perm = await get_note_permission(acting_user_id, share.note_id)
|
||||
if perm not in ("admin", "owner"):
|
||||
return None
|
||||
share.permission = permission
|
||||
await session.commit()
|
||||
await session.refresh(share)
|
||||
return share
|
||||
|
||||
|
||||
async def remove_note_share(acting_user_id: int, share_id: int) -> bool:
|
||||
async with async_session() as session:
|
||||
share = await session.get(NoteShare, share_id)
|
||||
if not share:
|
||||
return False
|
||||
from fabledassistant.services.access import get_note_permission
|
||||
perm = await get_note_permission(acting_user_id, share.note_id)
|
||||
if perm not in ("admin", "owner"):
|
||||
return False
|
||||
await session.delete(share)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
|
||||
async def list_note_shares(note_id: int) -> list[dict]:
|
||||
async with async_session() as session:
|
||||
shares = (await session.execute(
|
||||
select(NoteShare).where(NoteShare.note_id == note_id)
|
||||
)).scalars().all()
|
||||
result = []
|
||||
for s in shares:
|
||||
d = s.to_dict()
|
||||
if s.shared_with_user_id:
|
||||
user = await session.get(User, s.shared_with_user_id)
|
||||
d["username"] = user.username if user else None
|
||||
if s.shared_with_group_id:
|
||||
group = await session.get(Group, s.shared_with_group_id)
|
||||
d["group_name"] = group.name if group else None
|
||||
result.append(d)
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Shared-with-me
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def list_shared_with_me(user_id: int) -> dict:
|
||||
"""All projects and notes shared with the user (directly or via group)."""
|
||||
async with async_session() as session:
|
||||
user_group_ids = (await session.execute(
|
||||
select(GroupMembership.group_id).where(GroupMembership.user_id == user_id)
|
||||
)).scalars().all()
|
||||
|
||||
# --- Projects ---
|
||||
proj_direct = (await session.execute(
|
||||
select(ProjectShare).where(ProjectShare.shared_with_user_id == user_id)
|
||||
)).scalars().all()
|
||||
|
||||
proj_group: list[ProjectShare] = []
|
||||
if user_group_ids:
|
||||
proj_group = (await session.execute(
|
||||
select(ProjectShare).where(
|
||||
ProjectShare.shared_with_group_id.in_(user_group_ids)
|
||||
)
|
||||
)).scalars().all()
|
||||
|
||||
seen_projects: dict[int, str] = {}
|
||||
for share in list(proj_direct) + list(proj_group):
|
||||
prev = seen_projects.get(share.project_id)
|
||||
from fabledassistant.services.access import PERMISSION_RANK
|
||||
if prev is None or PERMISSION_RANK[share.permission] > PERMISSION_RANK[prev]:
|
||||
seen_projects[share.project_id] = share.permission
|
||||
|
||||
projects = []
|
||||
for pid, perm in seen_projects.items():
|
||||
proj = await session.get(Project, pid)
|
||||
if proj:
|
||||
owner = await session.get(User, proj.user_id)
|
||||
projects.append({
|
||||
"id": proj.id,
|
||||
"title": proj.title,
|
||||
"description": proj.description,
|
||||
"status": proj.status,
|
||||
"color": proj.color,
|
||||
"updated_at": proj.updated_at.isoformat(),
|
||||
"owner_username": owner.username if owner else None,
|
||||
"permission": perm,
|
||||
})
|
||||
|
||||
# --- Notes / Tasks ---
|
||||
note_direct = (await session.execute(
|
||||
select(NoteShare).where(NoteShare.shared_with_user_id == user_id)
|
||||
)).scalars().all()
|
||||
|
||||
note_group: list[NoteShare] = []
|
||||
if user_group_ids:
|
||||
note_group = (await session.execute(
|
||||
select(NoteShare).where(
|
||||
NoteShare.shared_with_group_id.in_(user_group_ids)
|
||||
)
|
||||
)).scalars().all()
|
||||
|
||||
seen_notes: dict[int, str] = {}
|
||||
for share in list(note_direct) + list(note_group):
|
||||
prev = seen_notes.get(share.note_id)
|
||||
from fabledassistant.services.access import PERMISSION_RANK
|
||||
if prev is None or PERMISSION_RANK[share.permission] > PERMISSION_RANK[prev]:
|
||||
seen_notes[share.note_id] = share.permission
|
||||
|
||||
notes = []
|
||||
for nid, perm in seen_notes.items():
|
||||
note = await session.get(Note, nid)
|
||||
if note:
|
||||
owner = await session.get(User, note.user_id)
|
||||
notes.append({
|
||||
"id": note.id,
|
||||
"title": note.title,
|
||||
"is_task": note.is_task,
|
||||
"project_id": note.project_id,
|
||||
"updated_at": note.updated_at.isoformat(),
|
||||
"owner_username": owner.username if owner else None,
|
||||
"permission": perm,
|
||||
})
|
||||
|
||||
return {"projects": projects, "notes": notes}
|
||||
Reference in New Issue
Block a user