receipter-pro / backend /invites.py
M8ion deploy
Deploy backend
45dc2a1
Raw History Blame Contribute Delete
6.21 kB
"""
Invite links: someone who can manage the team invites an email address to a role; the
person opens the link, signs in or signs up with that address, and joins.
Firestore layout:
orgs/{org_id}/invites/{token} — {email, role, invited_by, created_at, expires_at, status}
invite_tokens/{token} — {org_id} (so a link can be opened without knowing the org)
Status is "pending", "accepted" or "revoked". An invite past expires_at can't be used.
"""
from __future__ import annotations
import html
import re
import secrets
from datetime import datetime, timedelta, timezone
from backend import firestore_client as db
from backend import mailboxes, mailer_client, orgs, settings
from backend.core.constants import INVITE_TTL_DAYS
_EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
def _now() -> datetime:
return datetime.now(timezone.utc)
def _path(org_id: str, token: str) -> str:
return f"orgs/{org_id}/invites/{token}"
def _expired(invite: dict) -> bool:
return datetime.fromisoformat(invite["expires_at"]) <= _now()
def create_invite(org_id: str, actor_uid: str, email: str, role: str) -> dict:
email = (email or "").strip().lower()
if not _EMAIL.match(email):
raise ValueError("Enter a valid email address")
orgs._check_grant(org_id, actor_uid, role)
if any(m.get("email", "").lower() == email for m in orgs.list_members(org_id).values()):
raise ValueError(f"{email} is already in this organisation")
for token, existing in _pending(org_id).items():
if existing["email"] == email:
revoke_invite(org_id, actor_uid, token)
token = secrets.token_urlsafe(24)
invite = {
"email": email,
"role": role,
"invited_by": actor_uid,
"created_at": _now().isoformat(),
"expires_at": (_now() + timedelta(days=INVITE_TTL_DAYS)).isoformat(),
"status": "pending",
}
db.set_doc(_path(org_id, token), invite)
db.set_doc(f"invite_tokens/{token}", {"org_id": org_id})
return {"token": token, **invite}
def _pending(org_id: str) -> dict[str, dict]:
prefix = f"orgs/{org_id}/invites/"
return {
path[len(prefix):]: data
for path, data in db.query_prefix(prefix).items()
if data["status"] == "pending" and not _expired(data)
}
def list_invites(org_id: str, actor_uid: str) -> list[dict]:
orgs.require_permission(org_id, actor_uid, "manage_team")
return sorted(({"token": t, **d} for t, d in _pending(org_id).items()), key=lambda d: d["created_at"])
def revoke_invite(org_id: str, actor_uid: str, token: str) -> None:
orgs.require_permission(org_id, actor_uid, "manage_team")
invite = db.get_doc(_path(org_id, token))
if invite is None:
raise orgs.NotFoundError("No such invite")
invite["status"] = "revoked"
db.set_doc(_path(org_id, token), invite)
def _lookup(token: str) -> tuple[str, dict]:
index = db.get_doc(f"invite_tokens/{token}")
invite = db.get_doc(_path(index["org_id"], token)) if index else None
if invite is None:
raise orgs.NotFoundError("This invite link isn't valid")
return index["org_id"], invite
def describe(token: str) -> dict:
"""What the invite page shows before the person accepts."""
org_id, invite = _lookup(token)
role_name = next((r["name"] for r in orgs.list_roles(org_id) if r["key"] == invite["role"]), invite["role"])
state = invite["status"] if invite["status"] != "pending" else ("expired" if _expired(invite) else "pending")
return {
"org_id": org_id,
"org_name": orgs.get_org(org_id)["name"],
"email": invite["email"],
"role": invite["role"],
"role_name": role_name,
"status": state,
"expires_at": invite["expires_at"],
}
def accept(token: str, uid: str, email: str) -> str:
"""Joins uid to the invite's org. The signed-in address must be the invited one.
Returns the org_id."""
org_id, invite = _lookup(token)
if invite["status"] != "pending":
raise ValueError(f"This invite has been {invite['status']}")
if _expired(invite):
raise ValueError("This invite has expired. Ask for a new one.")
if (email or "").strip().lower() != invite["email"]:
raise orgs.PermissionError_(f"This invite is for {invite['email']}. Sign in with that address to accept it.")
orgs.join(org_id, uid, invite["role"], invite["email"])
invite["status"] = "accepted"
invite["accepted_by"] = uid
db.set_doc(_path(org_id, token), invite)
return org_id
def send_invite_email(org_id: str, invite: dict, link: str, inviter: str) -> bool:
"""Best effort: sends the link from the org's default (or first) verified mailbox.
Returns False when there is no mailbox to send from or the send fails; the link can
still be copied and shared by hand."""
boxes = {cid: m for cid, m in mailboxes.list_mailboxes(org_id).items() if m.get("status") == "verified"}
if not boxes:
return False
preferred = settings.email_settings(org_id)["default_mailbox_id"]
cid = preferred if preferred in boxes else next(iter(boxes))
org_name = orgs.get_org(org_id)["name"]
role_name = next((r["name"] for r in orgs.list_roles(org_id) if r["key"] == invite["role"]), invite["role"])
org_html, role_html, inviter_html = (html.escape(v) for v in (org_name, role_name, inviter or "Someone"))
body = (
f"<p>{inviter_html} invited you to join <strong>{org_html}</strong> on M8ion as {role_html}.</p>"
f'<p><a href="{html.escape(link)}">Accept the invite</a></p>'
f"<p>The link works for {INVITE_TTL_DAYS} days. Sign in or sign up with this address ({invite['email']}).</p>"
)
try:
mailer = mailer_client.get_mailer(boxes[cid]["kind"], mailboxes.get_decrypted_credentials(org_id, cid))
try:
mailer.send(to_addr=invite["email"], subject=f"Join {org_name} on M8ion", body=body)
finally:
close = getattr(mailer, "close", None)
if close:
close()
except Exception: # noqa: BLE001 — a failed courtesy email must not fail the invite
return False
return True