Functional Weave
Code in Rust

auth.account-link@1.0.0

impl/python.py

2,613 bytes · the Python implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import Optional, Sequence

from .auth_account_link_types import IdentityLink, LinkAccount, LinkDecision, OAuthIdentity
from .auth_normalise_email import normalise_email  ← from auth.normalise-email ^1.0.0 · built alongside by fune


def _decision(action: str, reason: str, account_id: Optional[str], email: Optional[str]) -> LinkDecision:
    return LinkDecision(action=action, reason=reason, account_id=account_id, email=email)


def decide_account_link(
    identity: OAuthIdentity, accounts: Sequence[LinkAccount], links: Sequence[IdentityLink]
) -> LinkDecision:
    """What to do with an OAuth sign-in, given the accounts and links the app
    already has. The rules run in a fixed order, so the same inputs always get
    the same answer; see the README for the attack each rule stops."""
    if not isinstance(identity.provider, str) or identity.provider == "":
        raise ValueError("identity.provider must be a non-empty string")
    if not isinstance(identity.subject, str) or identity.subject == "":
        raise ValueError("identity.subject must be a non-empty string")

    email = None if identity.email is None else normalise_email(identity.email)

    # The provider's subject is the identity; once linked, the email no longer matters.
    existing = next((l for l in links if l.provider == identity.provider and l.subject == identity.subject), None)
    if existing is not None:
        if any(a.id == existing.account_id for a in accounts):
            return _decision("sign-in", "existing_link", existing.account_id, email)
        return _decision("refuse", "linked_account_missing", existing.account_id, email)

    if email is None:
        return _decision("refuse", "no_email", None, None)

    matches = [a for a in accounts if normalise_email(a.email) == email]
    if not matches:
        if identity.email_verified is True:
            return _decision("create", "new_account", None, email)
        return _decision("require-verification", "unverified_new_email", None, email)
    if len(matches) > 1:
        return _decision("refuse", "ambiguous_email", None, email)

    account = matches[0]
    if identity.email_verified is not True:
        return _decision("refuse", "unverified_email", account.id, email)
    if any(l.account_id == account.id and l.provider == identity.provider and l.subject != identity.subject for l in links):
        return _decision("refuse", "provider_already_linked", account.id, email)
    if account.email_verified is not True:
        return _decision("require-verification", "account_email_unverified", account.id, email)
    return _decision("link", "verified_email_match", account.id, email)