vtt/src/ttfrog/schema.py

179 lines
5.8 KiB
Python
Raw Normal View History

2025-10-05 00:15:37 -07:00
from __future__ import annotations
2025-09-24 01:28:23 -07:00
2025-10-05 00:15:37 -07:00
from datetime import datetime
from typing import List
2025-10-07 23:30:23 -07:00
from grung.types import BackReference, Collection, DateTime, Dict, Field, Password, Pointer, Record, Timestamp
2025-10-07 01:18:36 -07:00
from tinydb import where
class Page(Record):
2025-10-04 01:26:09 -07:00
"""
A page in the wiki. Just about everything in the databse is either a Page or a subclass of a Page.
"""
2025-09-28 14:14:16 -07:00
@classmethod
def fields(cls):
2025-10-07 01:18:36 -07:00
# fmt: off
2025-09-28 14:14:16 -07:00
return [
2025-10-07 01:18:36 -07:00
*super().fields(), # Pick up the UID and whatever other non-optional fields exist
Field("uri", unique=True), # The URI for the page, relative to the app's VIEW_URI
Field("name"), # The portion of the URI after the last /
Field("title"), # The page title
Field("body"), # The main content blob of the page
Collection("members", Page), # The pages that exist below this page's URI
2025-10-04 01:26:09 -07:00
BackReference("parent", value_type=Page), # The page that exists above this page's URI
2025-10-07 01:18:36 -07:00
Pointer("author", value_type=User), # The last user to touch the page.
DateTime("created"), # When the page was created
Timestamp("last_modified"), # The last time the page was modified.
2025-10-07 23:30:23 -07:00
Dict("acl"),
2025-09-28 14:14:16 -07:00
]
2025-10-07 01:18:36 -07:00
# fmt: on
2025-09-28 14:14:16 -07:00
def before_insert(self, db):
2025-10-04 01:26:09 -07:00
"""
Make the following adjustments before saving this record:
* Derive the name from the title, or the title from the name
* Derive the URI from the hierarchy of the parent.
"""
super().before_insert(db)
2025-10-05 00:15:37 -07:00
now = datetime.utcnow()
if not self.doc_id and self.created < now:
self.created = now
2025-10-04 01:26:09 -07:00
if not self.name and not self.title:
raise Exception("Must provide either a name or a title!")
if not self.name:
self.name = self.title.title().replace(" ", "")
2025-09-28 14:14:16 -07:00
if not self.title:
2025-10-04 01:26:09 -07:00
self.title = self.name
2025-10-04 01:26:09 -07:00
self.uri = (self.parent.uri + "/" if self.parent and self.parent.uri != "/" else "") + self.name
def after_insert(self, db):
2025-10-04 01:26:09 -07:00
"""
After saving this record, ensure that any page in the members collection is updated with the
correct URI. This ensures that if a page is moved from one collection to another, the URI is updated.
"""
super().after_insert(db)
2025-10-05 00:15:37 -07:00
if not hasattr(self, "members"):
2025-10-04 01:26:09 -07:00
return
for child in self.members:
obj = BackReference.dereference(child, db)
2025-10-04 01:26:09 -07:00
obj.uri = f"{self.uri}/{obj.name}"
child = db.save(obj)
2025-10-07 01:18:36 -07:00
def add_member(self, child: Record):
from ttfrog import app
app.check_state()
self.members = list(set(self.members + [app.db.save(child)]))
app.db.save(self)
return self.get_child(child)
def get_child(self, obj: Record):
2025-10-04 01:26:09 -07:00
for page in self.members:
if page.uid == obj.uid:
return page
return None
2025-10-04 01:26:09 -07:00
2025-10-07 23:30:23 -07:00
def set_permissions(self, entity: Entity, permissions: List) -> str:
2025-10-07 01:18:36 -07:00
from ttfrog import app
app.check_state()
2025-10-07 23:30:23 -07:00
perms = "".join(permissions)
self.acl[entity.reference] = perms
2025-10-07 01:18:36 -07:00
app.db.save(self)
2025-10-05 00:15:37 -07:00
return perms
2025-10-07 23:30:23 -07:00
def get_acl_for_entity(self, entity) -> (str, str | None):
2025-10-07 01:18:36 -07:00
"""
Search upward through the page hierarchy looking for one with an ACL that either
has a grant for the entity we care about, or at least one group in which the entity is a member.
"""
from ttfrog import app
2025-10-05 00:15:37 -07:00
2025-10-07 01:18:36 -07:00
app.check_state()
2025-10-06 17:50:10 -07:00
def find_acl(obj):
2025-10-07 01:18:36 -07:00
if hasattr(obj, "acl"):
2025-10-07 23:30:23 -07:00
if entity.reference in obj.acl:
return {entity.reference: obj.acl[entity.reference]}
group_grants = {}
for ref, grant in obj.acl.items():
if ref.startswith("Group::"):
group = app.db.Group.get(where("uid") == ref.split("::")[1], recurse=False)
if entity.reference in group.members:
group_grants[ref] = grant
2025-10-07 01:18:36 -07:00
if group_grants:
return group_grants
2025-10-07 23:30:23 -07:00
if hasattr(obj, "parent"):
return find_acl(obj.parent)
return {"": ""}
2025-10-06 17:50:10 -07:00
2025-10-07 01:18:36 -07:00
return find_acl(self)
2025-10-05 00:15:37 -07:00
2025-10-07 01:18:36 -07:00
class Entity(Page):
def has_permission(self, record: Record, requested: str) -> bool | None:
2025-10-07 23:30:23 -07:00
for entity, grants in record.get_acl_for_entity(self).items():
if requested in grants:
2025-10-05 00:15:37 -07:00
return True
return False
2025-10-07 01:18:36 -07:00
def can_read(self, record: Record):
return self.has_permission(record, Permissions.READ)
2025-10-05 00:15:37 -07:00
2025-10-07 01:18:36 -07:00
def can_write(self, record: Record):
return self.has_permission(record, Permissions.WRITE)
2025-10-04 01:26:09 -07:00
2025-10-07 01:18:36 -07:00
def can_delete(self, record: Record):
return self.has_permission(record, Permissions.DELETE)
2025-10-05 00:15:37 -07:00
class User(Entity):
2025-10-04 01:26:09 -07:00
"""
A website user, editable as a wiki page.
"""
2025-10-07 01:18:36 -07:00
2025-10-05 00:15:37 -07:00
def check_credentials(self, username: str, password: str) -> bool:
return username == self.name and self._metadata.fields["password"].compare(password, self.password)
2025-10-04 01:26:09 -07:00
@classmethod
def fields(cls):
return [
field
for field in [
*super().fields(),
2025-10-05 00:15:37 -07:00
Field("email", unique=True),
Password("password"),
]
if field.name != "members"
2025-10-04 01:26:09 -07:00
]
2025-10-05 00:15:37 -07:00
class Group(Entity):
2025-10-04 01:26:09 -07:00
"""
A set of users, editable as a wiki page.
"""
class NPC(Page):
"""
An NPC, editable as a wiki page.
"""
2025-10-05 00:15:37 -07:00
class Permissions(Record):
READ = "r"
WRITE = "w"
DELETE = "d"
@classmethod
def fields(cls):
return [*super().fields(), Pointer("entity", Entity), Field("grants")]