receipter-pro / backend /unsubscribe_api.py
M8ion deploy
Deploy backend
45dc2a1
Raw History Blame Contribute Delete
1.5 kB
"""
The public side of unsubscribing: the page an email's Unsubscribe link opens, and the one-click
POST that mail apps send on the reader's behalf. Nothing here needs a sign-in; the signed link
is the proof. The page asks for a click (GET never unsubscribes) so link scanners that open
every link in a message do not remove people by accident.
"""
from __future__ import annotations
import html
from fastapi import APIRouter
from fastapi.responses import HTMLResponse
from backend import unsubscribe
router = APIRouter()
@router.get("/u/{token}", response_class=HTMLResponse)
def unsubscribe_page(token: str):
try:
_, email = unsubscribe.parse_token(token)
except ValueError as exc:
return HTMLResponse(unsubscribe.page("Link not valid", f"<p>{html.escape(str(exc))}.</p>"), status_code=400)
return unsubscribe.page(
"Unsubscribe",
f"<p>Stop emails to <b>{html.escape(email)}</b>?</p>"
f'<form method="post"><button style="font:inherit;padding:10px 18px;cursor:pointer">Unsubscribe</button></form>',
)
@router.post("/u/{token}", response_class=HTMLResponse)
def unsubscribe_now(token: str):
try:
email = unsubscribe.unsubscribe_with_token(token)
except ValueError as exc:
return HTMLResponse(unsubscribe.page("Link not valid", f"<p>{html.escape(str(exc))}.</p>"), status_code=400)
return unsubscribe.page("You are unsubscribed", f"<p>{html.escape(email)} will not get more emails from this sender.</p>")