Spaces:
Sleeping
Sleeping
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head> | |
<meta charset="utf-8"> | |
<meta name="generator" content="quarto-1.6.40"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> | |
<title>OAuth – fasthtml</title> | |
<style> | |
code{white-space: pre-wrap;} | |
span.smallcaps{font-variant: small-caps;} | |
div.columns{display: flex; gap: min(4vw, 1.5em);} | |
div.column{flex: auto; overflow-x: auto;} | |
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;} | |
ul.task-list{list-style: none;} | |
ul.task-list li input[type="checkbox"] { | |
width: 0.8em; | |
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */ | |
vertical-align: middle; | |
} | |
/* CSS for syntax highlighting */ | |
pre > code.sourceCode { white-space: pre; position: relative; } | |
pre > code.sourceCode > span { line-height: 1.25; } | |
pre > code.sourceCode > span:empty { height: 1.2em; } | |
.sourceCode { overflow: visible; } | |
code.sourceCode > span { color: inherit; text-decoration: inherit; } | |
div.sourceCode { margin: 1em 0; } | |
pre.sourceCode { margin: 0; } | |
@media screen { | |
div.sourceCode { overflow: auto; } | |
} | |
@media print { | |
pre > code.sourceCode { white-space: pre-wrap; } | |
pre > code.sourceCode > span { display: inline-block; text-indent: -5em; padding-left: 5em; } | |
} | |
pre.numberSource code | |
{ counter-reset: source-line 0; } | |
pre.numberSource code > span | |
{ position: relative; left: -4em; counter-increment: source-line; } | |
pre.numberSource code > span > a:first-child::before | |
{ content: counter(source-line); | |
position: relative; left: -1em; text-align: right; vertical-align: baseline; | |
border: none; display: inline-block; | |
-webkit-touch-callout: none; -webkit-user-select: none; | |
-khtml-user-select: none; -moz-user-select: none; | |
-ms-user-select: none; user-select: none; | |
padding: 0 4px; width: 4em; | |
} | |
pre.numberSource { margin-left: 3em; padding-left: 4px; } | |
div.sourceCode | |
{ } | |
@media screen { | |
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; } | |
} | |
</style> | |
<script src="../site_libs/quarto-nav/quarto-nav.js"></script> | |
<script src="../site_libs/quarto-nav/headroom.min.js"></script> | |
<script src="../site_libs/clipboard/clipboard.min.js"></script> | |
<script src="../site_libs/quarto-search/autocomplete.umd.js"></script> | |
<script src="../site_libs/quarto-search/fuse.min.js"></script> | |
<script src="../site_libs/quarto-search/quarto-search.js"></script> | |
<meta name="quarto:offset" content="../"> | |
<link href="../favicon.ico" rel="icon"> | |
<script src="../site_libs/quarto-html/quarto.js"></script> | |
<script src="../site_libs/quarto-html/popper.min.js"></script> | |
<script src="../site_libs/quarto-html/tippy.umd.min.js"></script> | |
<script src="../site_libs/quarto-html/anchor.min.js"></script> | |
<link href="../site_libs/quarto-html/tippy.css" rel="stylesheet"> | |
<link href="../site_libs/quarto-html/quarto-syntax-highlighting-549806ee2085284f45b00abea8c6df48.css" rel="stylesheet" id="quarto-text-highlighting-styles"> | |
<script src="../site_libs/bootstrap/bootstrap.min.js"></script> | |
<link href="../site_libs/bootstrap/bootstrap-icons.css" rel="stylesheet"> | |
<link href="../site_libs/bootstrap/bootstrap-e463c5e664eae906a5c2eb38a07ecc3d.min.css" rel="stylesheet" append-hash="true" id="quarto-bootstrap" data-mode="light"> | |
<script id="quarto-search-options" type="application/json">{ | |
"location": "navbar", | |
"copy-button": false, | |
"collapse-after": 3, | |
"panel-placement": "end", | |
"type": "overlay", | |
"limit": 50, | |
"keyboard-shortcut": [ | |
"f", | |
"/", | |
"s" | |
], | |
"show-item-context": false, | |
"language": { | |
"search-no-results-text": "No results", | |
"search-matching-documents-text": "matching documents", | |
"search-copy-link-title": "Copy link to search", | |
"search-hide-matches-text": "Hide additional matches", | |
"search-more-match-text": "more match in this document", | |
"search-more-matches-text": "more matches in this document", | |
"search-clear-button-title": "Clear", | |
"search-text-placeholder": "", | |
"search-detached-cancel-button-title": "Cancel", | |
"search-submit-button-title": "Submit", | |
"search-label": "Search" | |
} | |
}</script> | |
<link rel="stylesheet" href="../styles.css"> | |
<meta property="og:title" content="OAuth – fasthtml"> | |
<meta property="og:description" content="The fastest way to create an HTML app"> | |
<meta property="og:image" content="https://www.fastht.ml/docs/explains/imgs/gh-oauth.png"> | |
<meta property="og:site_name" content="fasthtml"> | |
<meta property="og:image:alt" content="Setting up an OAuth app in GitHub"> | |
<meta property="og:image:height" content="1019"> | |
<meta property="og:image:width" content="850"> | |
<meta name="twitter:title" content="OAuth – fasthtml"> | |
<meta name="twitter:description" content="The fastest way to create an HTML app"> | |
<meta name="twitter:image" content="https://www.fastht.ml/docs/og-image.png"> | |
<meta name="twitter:creator" content="@jeremyphoward"> | |
<meta name="twitter:site" content="@answerdotai"> | |
<meta name="twitter:card" content="summary_large_image"> | |
<link rel="canonical" href="https://www.fastht.ml/docs/explains/oauth.html"> | |
</head> | |
<body class="nav-sidebar floating nav-fixed"> | |
<div id="quarto-search-results"></div> | |
<header id="quarto-header" class="headroom fixed-top"> | |
<nav class="navbar navbar-expand-lg " data-bs-theme="dark"> | |
<div class="navbar-container container-fluid"> | |
<div class="navbar-brand-container mx-auto"> | |
<a href="../index.html" class="navbar-brand navbar-brand-logo"> | |
<img src="../logo.svg" alt="" class="navbar-logo"> | |
</a> | |
</div> | |
<div id="quarto-search" class="" title="Search"></div> | |
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" role="menu" aria-expanded="false" aria-label="Toggle navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }"> | |
<span class="navbar-toggler-icon"></span> | |
</button> | |
<div class="collapse navbar-collapse" id="navbarCollapse"> | |
<ul class="navbar-nav navbar-nav-scroll me-auto"> | |
<li class="nav-item"> | |
<a class="nav-link" href="https://fastht.ml"> | |
<span class="menu-text">Home</span></a> | |
</li> | |
<li class="nav-item"> | |
<a class="nav-link" href="https://fastht.ml/about"> | |
<span class="menu-text">Learn</span></a> | |
</li> | |
</ul> | |
<ul class="navbar-nav navbar-nav-scroll ms-auto"> | |
<li class="nav-item compact"> | |
<a class="nav-link" href="https://github.com/answerdotai/fasthtml"> <i class="bi bi-github" role="img"> | |
</i> | |
<span class="menu-text"></span></a> | |
</li> | |
<li class="nav-item compact"> | |
<a class="nav-link" href="https://x.com/answerdotai"> <i class="bi bi-twitter" role="img" aria-label="Fast.ai Twitter"> | |
</i> | |
<span class="menu-text"></span></a> | |
</li> | |
</ul> | |
</div> <!-- /navcollapse --> | |
<div class="quarto-navbar-tools"> | |
</div> | |
</div> <!-- /container-fluid --> | |
</nav> | |
<nav class="quarto-secondary-nav"> | |
<div class="container-fluid d-flex"> | |
<button type="button" class="quarto-btn-toggle btn" data-bs-toggle="collapse" role="button" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }"> | |
<i class="bi bi-layout-text-sidebar-reverse"></i> | |
</button> | |
<nav class="quarto-page-breadcrumbs" aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="../explains/background_tasks.html">Explanations</a></li><li class="breadcrumb-item"><a href="../explains/oauth.html">OAuth</a></li></ol></nav> | |
<a class="flex-grow-1" role="navigation" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }"> | |
</a> | |
</div> | |
</nav> | |
</header> | |
<!-- content --> | |
<div id="quarto-content" class="quarto-container page-columns page-rows-contents page-layout-article page-navbar"> | |
<!-- sidebar --> | |
<nav id="quarto-sidebar" class="sidebar collapse collapse-horizontal quarto-sidebar-collapse-item sidebar-navigation floating overflow-auto"> | |
<div class="sidebar-menu-container"> | |
<ul class="list-unstyled mt-1"> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../index.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Get Started</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item sidebar-item-section"> | |
<div class="sidebar-item-container"> | |
<a href="../tutorials/index.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Tutorials</span></a> | |
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-1" role="navigation" aria-expanded="true" aria-label="Toggle section"> | |
<i class="bi bi-chevron-right ms-2"></i> | |
</a> | |
</div> | |
<ul id="quarto-sidebar-section-1" class="collapse list-unstyled sidebar-section depth1 show"> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../tutorials/by_example.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">FastHTML By Example</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../tutorials/quickstart_for_web_devs.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Web Devs Quickstart</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../tutorials/e2e.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">JS App Walkthrough</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../tutorials/best_practice.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">FastHTML Best Practices</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../tutorials/jupyter_and_fasthtml.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Using Jupyter to write FastHTML</span></a> | |
</div> | |
</li> | |
</ul> | |
</li> | |
<li class="sidebar-item sidebar-item-section"> | |
<div class="sidebar-item-container"> | |
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-2" role="navigation" aria-expanded="true"> | |
<span class="menu-text">Explanations</span></a> | |
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-2" role="navigation" aria-expanded="true" aria-label="Toggle section"> | |
<i class="bi bi-chevron-right ms-2"></i> | |
</a> | |
</div> | |
<ul id="quarto-sidebar-section-2" class="collapse list-unstyled sidebar-section depth1 show"> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../explains/background_tasks.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Background Tasks</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../explains/explaining_xt_components.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text"><strong>FT</strong> Components</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../explains/faq.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">FAQ</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../explains/minidataapi.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">MiniDataAPI Spec</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../explains/oauth.html" class="sidebar-item-text sidebar-link active"> | |
<span class="menu-text">OAuth</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../explains/routes.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Routes</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../explains/stripe.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Stripe</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../explains/websockets.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">WebSockets</span></a> | |
</div> | |
</li> | |
</ul> | |
</li> | |
<li class="sidebar-item sidebar-item-section"> | |
<div class="sidebar-item-container"> | |
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-3" role="navigation" aria-expanded="true"> | |
<span class="menu-text">Reference</span></a> | |
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-3" role="navigation" aria-expanded="true" aria-label="Toggle section"> | |
<i class="bi bi-chevron-right ms-2"></i> | |
</a> | |
</div> | |
<ul id="quarto-sidebar-section-3" class="collapse list-unstyled sidebar-section depth1 show"> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../ref/concise_guide.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Concise reference</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../ref/best_practice.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">FastHTML Best Practices</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../ref/defining_xt_component.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Custom Components</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../ref/handlers.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Handling handlers</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../ref/live_reload.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Live Reloading</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../ref/response_types.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Response Types</span></a> | |
</div> | |
</li> | |
</ul> | |
</li> | |
<li class="sidebar-item sidebar-item-section"> | |
<div class="sidebar-item-container"> | |
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-4" role="navigation" aria-expanded="true"> | |
<span class="menu-text">Source</span></a> | |
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-4" role="navigation" aria-expanded="true" aria-label="Toggle section"> | |
<i class="bi bi-chevron-right ms-2"></i> | |
</a> | |
</div> | |
<ul id="quarto-sidebar-section-4" class="collapse list-unstyled sidebar-section depth1 show"> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../api/core.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Core</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../api/components.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Components</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../api/xtend.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Component extensions</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../api/js.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Javascript examples</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../api/pico.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Pico.css components</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../api/svg.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">SVG</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../api/jupyter.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Jupyter compatibility</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../api/oauth.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">OAuth</span></a> | |
</div> | |
</li> | |
<li class="sidebar-item"> | |
<div class="sidebar-item-container"> | |
<a href="../api/cli.html" class="sidebar-item-text sidebar-link"> | |
<span class="menu-text">Command Line Tools</span></a> | |
</div> | |
</li> | |
</ul> | |
</li> | |
</ul> | |
</div> | |
</nav> | |
<div id="quarto-sidebar-glass" class="quarto-sidebar-collapse-item" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item"></div> | |
<!-- margin-sidebar --> | |
<div id="quarto-margin-sidebar" class="sidebar margin-sidebar"> | |
<nav id="TOC" role="doc-toc" class="toc-active"> | |
<h2 id="toc-title">On this page</h2> | |
<ul> | |
<li><a href="#creating-an-client" id="toc-creating-an-client" class="nav-link active" data-scroll-target="#creating-an-client">Creating an Client</a></li> | |
<li><a href="#using-the-oauth-class" id="toc-using-the-oauth-class" class="nav-link" data-scroll-target="#using-the-oauth-class">Using the OAuth class</a></li> | |
<li><a href="#explaining-oauth-with-a-from-scratch-implementation" id="toc-explaining-oauth-with-a-from-scratch-implementation" class="nav-link" data-scroll-target="#explaining-oauth-with-a-from-scratch-implementation">Explaining OAuth with a from-scratch implementation</a></li> | |
<li><a href="#a-minimal-login-flow-github" id="toc-a-minimal-login-flow-github" class="nav-link" data-scroll-target="#a-minimal-login-flow-github">A Minimal Login Flow (GitHub)</a> | |
<ul class="collapse"> | |
<li><a href="#revoking-tokens-google" id="toc-revoking-tokens-google" class="nav-link" data-scroll-target="#revoking-tokens-google">Revoking Tokens (Google)</a></li> | |
<li><a href="#using-state-hugging-face" id="toc-using-state-hugging-face" class="nav-link" data-scroll-target="#using-state-hugging-face">Using State (Hugging Face)</a></li> | |
<li><a href="#a-work-in-progress" id="toc-a-work-in-progress" class="nav-link" data-scroll-target="#a-work-in-progress">A Work in Progress</a></li> | |
</ul></li> | |
</ul> | |
<div class="toc-actions"><ul><li><a href="https://github.com/AnswerDotAI/fasthtml/issues/new" class="toc-action"><i class="bi bi-github"></i>Report an issue</a></li></ul></div><div class="quarto-alternate-formats"><h2>Other Formats</h2><ul><li><a href="oauth.html.md"><i class="bi bi-file-code"></i>CommonMark</a></li></ul></div></nav> | |
</div> | |
<!-- main --> | |
<main class="content" id="quarto-document-content"> | |
<header id="title-block-header" class="quarto-title-block default"><nav class="quarto-page-breadcrumbs quarto-title-breadcrumbs d-none d-lg-block" aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="../explains/background_tasks.html">Explanations</a></li><li class="breadcrumb-item"><a href="../explains/oauth.html">OAuth</a></li></ol></nav> | |
<div class="quarto-title"> | |
<h1 class="title">OAuth</h1> | |
</div> | |
<div class="quarto-title-meta"> | |
</div> | |
</header> | |
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> | |
<p>OAuth is an open standard for ‘access delegation’, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords. It is the mechanism that enables “Log in with Google” on many sites, saving you from having to remember and manage yet another password. Like many auth-related topics, there’s a lot of depth and complexity to the OAuth standard, but once you understand the basic usage it can be a very convenient alternative to managing your own user accounts.</p> | |
<p>On this page you’ll see how to use OAuth with FastHTML to implement some common pieces of functionality.</p> | |
<section id="creating-an-client" class="level2"> | |
<h2 class="anchored" data-anchor-id="creating-an-client">Creating an Client</h2> | |
<p>FastHTML has Client classes for managing settings and state for different OAuth providers. Currently implemented are: GoogleAppClient, GitHubAppClient, HuggingFaceClient and DiscordAppClient - see the <a href="https://github.com/AnswerDotAI/fasthtml/blob/main/nbs/api/08_oauth.ipynb">source</a> if you need to add other providers. You’ll need a <code>client_id</code> and <code>client_secret</code> from the provider (see the from-scratch example later in this page for an example of registering with GitHub) to create the client. We recommend storing these in environment variables, rather than hardcoding them in your code.</p> | |
<div id="cell-5" class="cell"> | |
<div class="sourceCode cell-code" id="cb1"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> os</span> | |
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> fasthtml.oauth <span class="im">import</span> GoogleAppClient</span> | |
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>client <span class="op">=</span> GoogleAppClient(os.getenv(<span class="st">"AUTH_CLIENT_ID"</span>),</span> | |
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a> os.getenv(<span class="st">"AUTH_CLIENT_SECRET"</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
</div> | |
<p>The client is used to obtain a login link and to manage communications between your app and the OAuth provider (<code>client.login_link(redirect_uri="/redirect")</code>).</p> | |
</section> | |
<section id="using-the-oauth-class" class="level2"> | |
<h2 class="anchored" data-anchor-id="using-the-oauth-class">Using the OAuth class</h2> | |
<p>Once you’ve set up a client, adding OAuth to a FastHTML app can be as simple as:</p> | |
<div id="cell-9" class="cell"> | |
<div class="sourceCode cell-code" id="cb2"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> fasthtml.oauth <span class="im">import</span> OAuth</span> | |
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> fasthtml.common <span class="im">import</span> FastHTML, RedirectResponse</span> | |
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> Auth(OAuth):</span> | |
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a> <span class="kw">def</span> get_auth(<span class="va">self</span>, info, ident, session, state):</span> | |
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a> email <span class="op">=</span> info.email <span class="kw">or</span> <span class="st">''</span></span> | |
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> info.email_verified <span class="kw">and</span> email.split(<span class="st">'@'</span>)[<span class="op">-</span><span class="dv">1</span>]<span class="op">==</span><span class="st">'answer.ai'</span>:</span> | |
<span id="cb2-8"><a href="#cb2-8" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> RedirectResponse(<span class="st">'/'</span>, status_code<span class="op">=</span><span class="dv">303</span>)</span> | |
<span id="cb2-9"><a href="#cb2-9" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb2-10"><a href="#cb2-10" aria-hidden="true" tabindex="-1"></a>app <span class="op">=</span> FastHTML()</span> | |
<span id="cb2-11"><a href="#cb2-11" aria-hidden="true" tabindex="-1"></a>oauth <span class="op">=</span> Auth(app, client)</span> | |
<span id="cb2-12"><a href="#cb2-12" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb2-13"><a href="#cb2-13" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(<span class="st">'/'</span>)</span> | |
<span id="cb2-14"><a href="#cb2-14" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> home(auth): <span class="cf">return</span> P(<span class="st">'Logged in!'</span>), A(<span class="st">'Log out'</span>, href<span class="op">=</span><span class="st">'/logout'</span>)</span> | |
<span id="cb2-15"><a href="#cb2-15" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb2-16"><a href="#cb2-16" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(<span class="st">'/login'</span>)</span> | |
<span id="cb2-17"><a href="#cb2-17" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> login(req): <span class="cf">return</span> Div(P(<span class="st">"Not logged in"</span>), A(<span class="st">'Log in'</span>, href<span class="op">=</span>oauth.login_link(req)))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
</div> | |
<p>There’s a fair bit going on here, so let’s unpack what’s happening in that code:</p> | |
<ul> | |
<li>OAuth (and by extension our custom Auth class) has a number of default arguments, including some key URLs: <code>redir_path='/redirect', error_path='/error', logout_path='/logout', login_path='/login'</code>. It will create and handle the redirect and logout paths, and it’s up to you to handle <code>/login</code> (where unsuccessful login attempts will be redirected) and <code>/error</code> (for oauth errors).</li> | |
<li>When we run <code>oauth = Auth(app, client)</code> it adds the redirect and logout paths to the app and also adds some beforeware. This beforeware runs on any requests (apart from any specified with the <code>skip</code> parameter).</li> | |
</ul> | |
<p>The added beforeware specifies some app behaviour:</p> | |
<ul> | |
<li>If someone who isn’t logged in attempts to visit our homepage (<code>/</code>) here, they will be redirected to <code>/login</code>.</li> | |
<li>If they are logged in, it calls a <code>check_invalid</code> method. This defaults to False, which let’s the user continue to the page they requested. The behaviour can be modified by defining your own <code>check_invalid</code> method in the Auth class - for example, you could have this forcibly log out users who have recently been banned.</li> | |
</ul> | |
<p>So how does someone log in? If they visit (or are redirected to) the login page at <code>/login</code>, we show them a login link. This sends them to the OAuth provider, where they’ll go through the steps of selecting their account, giving permissions etc. Once done they will be redirected back to <code>/redirect</code>. Behind the scenes a code that comes as part of their request gets turned into user info, which is then passed to the key function <code>get_auth(self, info, ident, session, state)</code>. Here is where you’d handle looking up or adding a user in a database, checking for some condition (for example, this code checks if the email is an answer.ai email address) or choosing the destination based on state. The arguments are:</p> | |
<ul> | |
<li><code>self</code>: the Auth object, which you can use to access the client (<code>self.cli</code>)</li> | |
<li><code>info</code>: the information provided by the OAuth provider, typically including a unique user id, email address, username and other metadata.</li> | |
<li><code>ident</code>: a unique identifier for this user. What this looks like varies between providers. This is useful for managing a database of users, for example.</li> | |
<li><code>session</code>: the current session, that you can store information in securely</li> | |
<li><code>state</code>: you can optionally pass in some state when creating the login link. This persists and is returned after the user goes through the Oath steps, which is useful for returning them to the same page they left. It can also be used as added security against CSRF attacks.</li> | |
</ul> | |
<p>In our example, we check the email in <code>info</code> (we use a GoogleAppClient, not all providers will include an email). If we aren’t happy, and get_auth returns False or nothing (as in the case here for non-answerai people) then the user is redirected back to the login page. But if everything looks good we return a redirect to the homepage, and an <code>auth</code> key is added to the session and the scope containing the users identity <code>ident</code>. So, for example, in the homepage route we could use <code>auth</code> to look up this particular user’s profile info and customize the page accordingly. This auth will persist in their session until they clear the browser cache, so by default they’ll stay logged in. To log them out, remove it ( <code>session.pop('auth', None)</code>) or send them to <code>/logout</code> which will do that for you.</p> | |
</section> | |
<section id="explaining-oauth-with-a-from-scratch-implementation" class="level2"> | |
<h2 class="anchored" data-anchor-id="explaining-oauth-with-a-from-scratch-implementation">Explaining OAuth with a from-scratch implementation</h2> | |
<p>Hopefully the example above is enough to get you started. You can also check out the (fairly minimal) <a href="https://github.com/AnswerDotAI/fasthtml/blob/main/nbs/api/08_oauth.ipynb">source code</a> where this is implemented, and the <a href="https://github.com/AnswerDotAI/fasthtml-example/blob/main/oauth_example">examples here</a>.</p> | |
<p>If you’re wanting to learn more about how this works, and to see where you might add additional functionality, the rest of this page will walk through some examples <strong>without</strong> the OAuth convenience class, to illustrate the concepts. This was written before said OAuth class was available, and is kept here for educational purposes - we recommend you stick with the new approach shown above in most cases.</p> | |
</section> | |
<section id="a-minimal-login-flow-github" class="level2"> | |
<h2 class="anchored" data-anchor-id="a-minimal-login-flow-github">A Minimal Login Flow (GitHub)</h2> | |
<p>Let’s begin by building a minimal ‘Sign in with GitHub’ flow. This will demonstrate the basic steps of OAuth.</p> | |
<p>OAuth requires a “provider” (in this case, GitHub) to authenticate the user. So the first step when setting up our app is to register with GitHub to set things up.</p> | |
<p>Go to https://github.com/settings/developers and click “New OAuth App”. Fill in the form with the following values, then click ‘Register application’.</p> | |
<ul> | |
<li>Application name: Your app name</li> | |
<li>Homepage URL: http://localhost:8000 (or whatever URL you’re using - you can change this later)</li> | |
<li>Authorization callback URL: http://localhost:8000/auth_redirect (you can modify this later too)</li> | |
</ul> | |
<div style="text-align:center;margin:50px 0 45px;"> | |
<img src="imgs/gh-oauth.png" alt="Setting up an OAuth app in GitHub" width="500"> | |
</div> | |
<p>After you register, you’ll see a screen where you can view the client ID and generate a client secret. Store these values in a safe place. You’ll use them to create a <a href="https://www.fastht.ml/docs/api/oauth.html#githubappclient"><code>GitHubAppClient</code></a> object in FastHTML.</p> | |
<p>This <code>client</code> object is responsible for handling the parts of the OAuth flow which depend on direct communication between your app and GitHub, as opposed to interactions which go through the user’s browser via redirects.</p> | |
<p>Here is how to setup the client object:</p> | |
<div class="sourceCode" id="cb3"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>client <span class="op">=</span> GitHubAppClient(</span> | |
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a> client_id<span class="op">=</span><span class="st">"your_client_id"</span>,</span> | |
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a> client_secret<span class="op">=</span><span class="st">"your_client_secret"</span></span> | |
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
<p>You should also save the path component of the authorization callback URL which you provided on registration.</p> | |
<p>This route is where GitHub will redirect the user’s browser in order to send an authorization code to your app. You should save only the URL’s path component rather than the entire URL because you want your code to work automatically in deployment, when the host and port part of the URL change from <code>localhost:8000</code> to your real DNS name.</p> | |
<p>Save the special authorization callback path under an obvious name:</p> | |
<div class="sourceCode" id="cb4"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>auth_callback_path <span class="op">=</span> <span class="st">"/auth_redirect"</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
<div class="callout callout-style-default callout-note callout-titled"> | |
<div class="callout-header d-flex align-content-center"> | |
<div class="callout-icon-container"> | |
<i class="callout-icon"></i> | |
</div> | |
<div class="callout-title-container flex-fill"> | |
Note | |
</div> | |
</div> | |
<div class="callout-body-container callout-body"> | |
<p>It’s recommended to store the client ID, and secret, in environment variables, rather than hardcoding them in your code.</p> | |
</div> | |
</div> | |
<p>When the user visit a normal page of your app, if they are not already logged in, then you’ll want to redirect them to your app’s login page, which will live at the <code>/login</code> path. We accomplish that by using this piece of “beforeware”, which defines logic which runs before other work for all routes except ones we specify to be skipped:</p> | |
<div class="sourceCode" id="cb5"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> before(req, session):</span> | |
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a> auth <span class="op">=</span> req.scope[<span class="st">'auth'</span>] <span class="op">=</span> session.get(<span class="st">'user_id'</span>, <span class="va">None</span>)</span> | |
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> <span class="kw">not</span> auth: <span class="cf">return</span> RedirectResponse(<span class="st">'/login'</span>, status_code<span class="op">=</span><span class="dv">303</span>)</span> | |
<span id="cb5-4"><a href="#cb5-4" aria-hidden="true" tabindex="-1"></a> counts.xtra(name<span class="op">=</span>auth)</span> | |
<span id="cb5-5"><a href="#cb5-5" aria-hidden="true" tabindex="-1"></a>bware <span class="op">=</span> Beforeware(before, skip<span class="op">=</span>[<span class="st">'/login'</span>, auth_callback_path])</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
<p>We configure the beforeware to skip <code>/login</code> because that’s where the user goes to login, and we also skip the special authorization callback path because that is used by OAuth itself to receive information from GitHub.</p> | |
<p>It’s only at your login page that we start the OAuth flow. To start the OAuth flow, you need to give the user a link to GitHub’s login for your app. You’ll need the <code>client</code> object to generate that link, and the client object will in turn need the full authorization callback URL, which we need to build from the authorization callback path, so it is a multi-step process to produce this GitHub login link.</p> | |
<p>Here is an implementation of your own <code>/login</code> route handler. It generates the GitHub login link and presents it to the user:</p> | |
<div class="sourceCode" id="cb6"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(<span class="st">'/login'</span>)</span> | |
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> login(request)</span> | |
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a> redir <span class="op">=</span> redir_url(request,auth_callback_path)</span> | |
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a> login_link <span class="op">=</span> client.login_link(redir)</span> | |
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> P(A(<span class="st">'Login with GitHub'</span>, href<span class="op">=</span>login_link)) </span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
<p>Once the user follows that link, GitHub will ask them to grant permission to your app to access their GitHub account. If they agree, GitHub will redirect them back to your app’s authorization callback URL, carrying an authorization code which your app can use to generate an access token. To receive this code, you need to set up a route in FastHTML that listens for requests at the authorization callback path. For example:</p> | |
<div class="sourceCode" id="cb7"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(auth_callback_path)</span> | |
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> auth_redirect(code:<span class="bu">str</span>):</span> | |
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> P(<span class="ss">f"code: </span><span class="sc">{</span>code<span class="sc">}</span><span class="ss">"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
<p>This authorization code is temporary, and is used by your app to directly ask the provider for user information like an access token.</p> | |
<p>To recap, you can think of the exchange so far as:</p> | |
<ul> | |
<li>User to us: “I want to log in with you, app.”</li> | |
<li>Us to User: “Okay but first, here’s a special link to log in with GitHub”</li> | |
<li>User to GitHub: “I want to log in with you, GitHub, to use this app.”</li> | |
<li>GitHub to User: “OK, redirecting you back to the app’s URL (with an auth code)”</li> | |
<li>User to Us: “Hi again, app. Here’s the GitHub auth code you need to ask GitHub for info about me” (delivered via <code>/auth_redirect?code=...</code>)</li> | |
</ul> | |
<p>The final steps we need to implement are as follows:</p> | |
<ul> | |
<li>Us to GitHUb: “A user just gave me this auth code. May I have the user info (e.g., an access token)?”</li> | |
<li>GitHub to us: “Since you have an auth code, here’s the user info”</li> | |
</ul> | |
<p>It’s critical for us to derive the user info from the auth code immediately in the authorization callback, because the auth code may be used only once. So we use it that once in order to get information like an access token, which will remain valid for longer.</p> | |
<p>To go from the auth code to user info, you use <code>info = client.retr_info(code,redirect_uri)</code>. From the user info, you can extract the <code>user_id</code>, which is a unique identifier for the user:</p> | |
<div class="sourceCode" id="cb8"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(auth_callback_path)</span> | |
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> auth_redirect(code:<span class="bu">str</span>, request):</span> | |
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a> redir <span class="op">=</span> redir_url(request, auth_callback_path)</span> | |
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a> user_info <span class="op">=</span> client.retr_info(code, redir)</span> | |
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a> user_id <span class="op">=</span> info[client.id_key]</span> | |
<span id="cb8-6"><a href="#cb8-6" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> P(<span class="ss">f"User id: </span><span class="sc">{</span>user_id<span class="sc">}</span><span class="ss">"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
<p>But we want the user ID not to print it but to remember the user.</p> | |
<p>So let us store it in the <code>session</code> object, to remember who is logged in:</p> | |
<div class="sourceCode" id="cb9"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(auth_callback_path)</span> | |
<span id="cb9-2"><a href="#cb9-2" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> auth_redirect(code:<span class="bu">str</span>, request, session):</span> | |
<span id="cb9-3"><a href="#cb9-3" aria-hidden="true" tabindex="-1"></a> redir <span class="op">=</span> redir_url(request, auth_callback_path)</span> | |
<span id="cb9-4"><a href="#cb9-4" aria-hidden="true" tabindex="-1"></a> user_info <span class="op">=</span> client.retr_info(code, redir)</span> | |
<span id="cb9-5"><a href="#cb9-5" aria-hidden="true" tabindex="-1"></a> user_id <span class="op">=</span> user_info[client.id_key] <span class="co"># get their ID</span></span> | |
<span id="cb9-6"><a href="#cb9-6" aria-hidden="true" tabindex="-1"></a> session[<span class="st">'user_id'</span>] <span class="op">=</span> user_id <span class="co"># save ID in the session</span></span> | |
<span id="cb9-7"><a href="#cb9-7" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> RedirectResponse(<span class="st">'/'</span>, status_code<span class="op">=</span><span class="dv">303</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
<p>The session object is derived from values visible to the user’s browser, but it is cryptographically signed so the user can’t read it themselves. This makes it safe to store even information we don’t want to expose to the user.</p> | |
<p>For larger quantities of data, we’d want to save that information in a database and use the session to hold keys to lookup information from that database.</p> | |
<p>Here’s a minimal app that puts all these pieces together. It uses the user info to get the user_id. It stores that in the session object. It then uses the user_id as a key into a database, which tracks how frequently every user has hit an increment button.</p> | |
<div class="sourceCode" id="cb10"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> os</span> | |
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> fasthtml.common <span class="im">import</span> <span class="op">*</span></span> | |
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> fasthtml.oauth <span class="im">import</span> GitHubAppClient, redir_url</span> | |
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a>db <span class="op">=</span> database(<span class="st">'data/counts.db'</span>)</span> | |
<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a>counts <span class="op">=</span> db.t.counts</span> | |
<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a><span class="cf">if</span> counts <span class="kw">not</span> <span class="kw">in</span> db.t: counts.create(<span class="bu">dict</span>(name<span class="op">=</span><span class="bu">str</span>, count<span class="op">=</span><span class="bu">int</span>), pk<span class="op">=</span><span class="st">'name'</span>)</span> | |
<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a>Count <span class="op">=</span> counts.dataclass()</span> | |
<span id="cb10-9"><a href="#cb10-9" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb10-10"><a href="#cb10-10" aria-hidden="true" tabindex="-1"></a><span class="co"># Auth client setup for GitHub</span></span> | |
<span id="cb10-11"><a href="#cb10-11" aria-hidden="true" tabindex="-1"></a>client <span class="op">=</span> GitHubAppClient(os.getenv(<span class="st">"AUTH_CLIENT_ID"</span>), </span> | |
<span id="cb10-12"><a href="#cb10-12" aria-hidden="true" tabindex="-1"></a> os.getenv(<span class="st">"AUTH_CLIENT_SECRET"</span>))</span> | |
<span id="cb10-13"><a href="#cb10-13" aria-hidden="true" tabindex="-1"></a>auth_callback_path <span class="op">=</span> <span class="st">"/auth_redirect"</span></span> | |
<span id="cb10-14"><a href="#cb10-14" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb10-15"><a href="#cb10-15" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> before(req, session):</span> | |
<span id="cb10-16"><a href="#cb10-16" aria-hidden="true" tabindex="-1"></a> <span class="co"># if not logged in, we send them to our login page</span></span> | |
<span id="cb10-17"><a href="#cb10-17" aria-hidden="true" tabindex="-1"></a> <span class="co"># logged in means:</span></span> | |
<span id="cb10-18"><a href="#cb10-18" aria-hidden="true" tabindex="-1"></a> <span class="co"># - 'user_id' in the session object, </span></span> | |
<span id="cb10-19"><a href="#cb10-19" aria-hidden="true" tabindex="-1"></a> <span class="co"># - 'auth' in the request object</span></span> | |
<span id="cb10-20"><a href="#cb10-20" aria-hidden="true" tabindex="-1"></a> auth <span class="op">=</span> req.scope[<span class="st">'auth'</span>] <span class="op">=</span> session.get(<span class="st">'user_id'</span>, <span class="va">None</span>)</span> | |
<span id="cb10-21"><a href="#cb10-21" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> <span class="kw">not</span> auth: <span class="cf">return</span> RedirectResponse(<span class="st">'/login'</span>, status_code<span class="op">=</span><span class="dv">303</span>)</span> | |
<span id="cb10-22"><a href="#cb10-22" aria-hidden="true" tabindex="-1"></a> counts.xtra(name<span class="op">=</span>auth)</span> | |
<span id="cb10-23"><a href="#cb10-23" aria-hidden="true" tabindex="-1"></a>bware <span class="op">=</span> Beforeware(before, skip<span class="op">=</span>[<span class="st">'/login'</span>, auth_callback_path])</span> | |
<span id="cb10-24"><a href="#cb10-24" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb10-25"><a href="#cb10-25" aria-hidden="true" tabindex="-1"></a>app <span class="op">=</span> FastHTML(before<span class="op">=</span>bware)</span> | |
<span id="cb10-26"><a href="#cb10-26" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb10-27"><a href="#cb10-27" aria-hidden="true" tabindex="-1"></a><span class="co"># User asks us to Login</span></span> | |
<span id="cb10-28"><a href="#cb10-28" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(<span class="st">'/login'</span>)</span> | |
<span id="cb10-29"><a href="#cb10-29" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> login(request):</span> | |
<span id="cb10-30"><a href="#cb10-30" aria-hidden="true" tabindex="-1"></a> redir <span class="op">=</span> redir_url(request,auth_callback_path)</span> | |
<span id="cb10-31"><a href="#cb10-31" aria-hidden="true" tabindex="-1"></a> login_link <span class="op">=</span> client.login_link(redir)</span> | |
<span id="cb10-32"><a href="#cb10-32" aria-hidden="true" tabindex="-1"></a> <span class="co"># we tell user to login at github</span></span> | |
<span id="cb10-33"><a href="#cb10-33" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> P(A(<span class="st">'Login with GitHub'</span>, href<span class="op">=</span>login_link)) </span> | |
<span id="cb10-34"><a href="#cb10-34" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb10-35"><a href="#cb10-35" aria-hidden="true" tabindex="-1"></a><span class="co"># User comes back to us with an auth code from Github</span></span> | |
<span id="cb10-36"><a href="#cb10-36" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(auth_callback_path)</span> | |
<span id="cb10-37"><a href="#cb10-37" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> auth_redirect(code:<span class="bu">str</span>, request, session):</span> | |
<span id="cb10-38"><a href="#cb10-38" aria-hidden="true" tabindex="-1"></a> redir <span class="op">=</span> redir_url(request, auth_callback_path)</span> | |
<span id="cb10-39"><a href="#cb10-39" aria-hidden="true" tabindex="-1"></a> user_info <span class="op">=</span> client.retr_info(code, redir)</span> | |
<span id="cb10-40"><a href="#cb10-40" aria-hidden="true" tabindex="-1"></a> user_id <span class="op">=</span> user_info[client.id_key] <span class="co"># get their ID</span></span> | |
<span id="cb10-41"><a href="#cb10-41" aria-hidden="true" tabindex="-1"></a> session[<span class="st">'user_id'</span>] <span class="op">=</span> user_id <span class="co"># save ID in the session</span></span> | |
<span id="cb10-42"><a href="#cb10-42" aria-hidden="true" tabindex="-1"></a> <span class="co"># create a db entry for the user</span></span> | |
<span id="cb10-43"><a href="#cb10-43" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> user_id <span class="kw">not</span> <span class="kw">in</span> counts: counts.insert(name<span class="op">=</span>user_id, count<span class="op">=</span><span class="dv">0</span>)</span> | |
<span id="cb10-44"><a href="#cb10-44" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> RedirectResponse(<span class="st">'/'</span>, status_code<span class="op">=</span><span class="dv">303</span>)</span> | |
<span id="cb10-45"><a href="#cb10-45" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb10-46"><a href="#cb10-46" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(<span class="st">'/'</span>)</span> | |
<span id="cb10-47"><a href="#cb10-47" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> home(auth):</span> | |
<span id="cb10-48"><a href="#cb10-48" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> Div(</span> | |
<span id="cb10-49"><a href="#cb10-49" aria-hidden="true" tabindex="-1"></a> P(<span class="st">"Count demo"</span>),</span> | |
<span id="cb10-50"><a href="#cb10-50" aria-hidden="true" tabindex="-1"></a> P(<span class="ss">f"Count: "</span>, Span(counts[auth].count, <span class="bu">id</span><span class="op">=</span><span class="st">'count'</span>)),</span> | |
<span id="cb10-51"><a href="#cb10-51" aria-hidden="true" tabindex="-1"></a> Button(<span class="st">'Increment'</span>, hx_get<span class="op">=</span><span class="st">'/increment'</span>, hx_target<span class="op">=</span><span class="st">'#count'</span>),</span> | |
<span id="cb10-52"><a href="#cb10-52" aria-hidden="true" tabindex="-1"></a> P(A(<span class="st">'Logout'</span>, href<span class="op">=</span><span class="st">'/logout'</span>))</span> | |
<span id="cb10-53"><a href="#cb10-53" aria-hidden="true" tabindex="-1"></a> )</span> | |
<span id="cb10-54"><a href="#cb10-54" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb10-55"><a href="#cb10-55" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(<span class="st">'/increment'</span>)</span> | |
<span id="cb10-56"><a href="#cb10-56" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> increment(auth):</span> | |
<span id="cb10-57"><a href="#cb10-57" aria-hidden="true" tabindex="-1"></a> c <span class="op">=</span> counts[auth]</span> | |
<span id="cb10-58"><a href="#cb10-58" aria-hidden="true" tabindex="-1"></a> c.count <span class="op">+=</span> <span class="dv">1</span></span> | |
<span id="cb10-59"><a href="#cb10-59" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> counts.upsert(c).count</span> | |
<span id="cb10-60"><a href="#cb10-60" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb10-61"><a href="#cb10-61" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(<span class="st">'/logout'</span>)</span> | |
<span id="cb10-62"><a href="#cb10-62" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> logout(session):</span> | |
<span id="cb10-63"><a href="#cb10-63" aria-hidden="true" tabindex="-1"></a> session.pop(<span class="st">'user_id'</span>, <span class="va">None</span>)</span> | |
<span id="cb10-64"><a href="#cb10-64" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> RedirectResponse(<span class="st">'/login'</span>, status_code<span class="op">=</span><span class="dv">303</span>)</span> | |
<span id="cb10-65"><a href="#cb10-65" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb10-66"><a href="#cb10-66" aria-hidden="true" tabindex="-1"></a>serve()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
<p>Some things to note:</p> | |
<ul> | |
<li>The <a href="https://www.fastht.ml/docs/explains/stripe.html#before"><code>before</code></a> function is used to check if the user is authenticated. If not, they are redirected to the login page.</li> | |
<li>To log the user out, we remove the user ID from the session.</li> | |
<li>Calling <code>counts.xtra(name=auth)</code> ensures that only the row corresponding to the current user is accessible when responding to a request. This is often nicer than trying to remember to filter the data in every route, and lowers the risk of accidentally leaking data.</li> | |
<li>In the <code>auth_redirect</code> route, we store the user ID in the session and create a new row in the <code>user_counts</code> table if it doesn’t already exist.</li> | |
</ul> | |
<p>You can find more heavily-commented version of this code in the <a href="https://github.com/AnswerDotAI/fasthtml-example/tree/main/oauth_example">oauth directory in fasthtml-example</a>, along with an even more minimal example. More examples may be added in the future.</p> | |
<section id="revoking-tokens-google" class="level3"> | |
<h3 class="anchored" data-anchor-id="revoking-tokens-google">Revoking Tokens (Google)</h3> | |
<p>When the user in the example above logs out, we remove their user ID from the session. However, the user is still logged in to GitHub. If they click ‘Login with GitHub’ again, they’ll be redirected back to our site without having to log in again. This is because GitHub remembers that they’ve already granted our app permission to access their account. Most of the time this is convenient, but for testing or security purposes you may want a way to revoke this permission.</p> | |
<p>As a user, you can usually revoke access to an app from the provider’s website (for example, <a href="https://github.com/settings/applications">https://github.com/settings/applications</a>). But as a developer, you can also revoke access programmatically - at least with some providers. This requires keeping track of the access token (stored in <code>client.token["access_token"]</code> after you call <code>retr_info</code>), and sending a request to the provider’s revoke URL:</p> | |
<div class="sourceCode" id="cb11"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a>auth_revoke_url <span class="op">=</span> <span class="st">"https://accounts.google.com/o/oauth2/revoke"</span></span> | |
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> revoke_token(token):</span> | |
<span id="cb11-3"><a href="#cb11-3" aria-hidden="true" tabindex="-1"></a> response <span class="op">=</span> requests.post(auth_revoke_url, params<span class="op">=</span>{<span class="st">"token"</span>: token})</span> | |
<span id="cb11-4"><a href="#cb11-4" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> response.status_code <span class="op">==</span> <span class="dv">200</span> <span class="co"># True if successful</span></span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
<p>Not all providers support token revocation, and it is not built into FastHTML clients at the moment.</p> | |
</section> | |
<section id="using-state-hugging-face" class="level3"> | |
<h3 class="anchored" data-anchor-id="using-state-hugging-face">Using State (Hugging Face)</h3> | |
<p>Imagine a user (not logged in) comes to your AI image editing site, starts testing things out, and then realizes they need to sign in before they can click “Run (Pro)” on the edit they’re working on. They click “Sign in with Hugging Face”, log in, and are redirected back to your site. But now they’ve lost their in-progress edit and are left just looking at the homepage! This is an example of a case where you might want to keep track of some additional state. Another strong use case for being able to pass some uniqie state through the OAuth flow is to prevent something called a <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery">CSRF attack</a>. To add a state string to the OAuth flow, include a <code>state</code> argument when creating the login link:</p> | |
<div class="sourceCode" id="cb12"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a><span class="co"># in login page:</span></span> | |
<span id="cb12-2"><a href="#cb12-2" aria-hidden="true" tabindex="-1"></a>link <span class="op">=</span> A(<span class="st">'Login with GitHub'</span>, href<span class="op">=</span>client.login_link(state<span class="op">=</span><span class="st">'current_prompt: add a unicorn'</span>))</span> | |
<span id="cb12-3"><a href="#cb12-3" aria-hidden="true" tabindex="-1"></a></span> | |
<span id="cb12-4"><a href="#cb12-4" aria-hidden="true" tabindex="-1"></a><span class="co"># in auth_redirect:</span></span> | |
<span id="cb12-5"><a href="#cb12-5" aria-hidden="true" tabindex="-1"></a><span class="at">@app.get</span>(<span class="st">'/auth_redirect'</span>)</span> | |
<span id="cb12-6"><a href="#cb12-6" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> auth_redirect(code:<span class="bu">str</span>, session, state:<span class="bu">str</span><span class="op">=</span><span class="va">None</span>):</span> | |
<span id="cb12-7"><a href="#cb12-7" aria-hidden="true" tabindex="-1"></a> <span class="bu">print</span>(<span class="ss">f"state: </span><span class="sc">{</span>state<span class="sc">}</span><span class="ss">"</span>) <span class="co"># Use as needed</span></span> | |
<span id="cb12-8"><a href="#cb12-8" aria-hidden="true" tabindex="-1"></a> ...</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div> | |
<p>The state string is passed through the OAuth flow and back to your site.</p> | |
</section> | |
<section id="a-work-in-progress" class="level3"> | |
<h3 class="anchored" data-anchor-id="a-work-in-progress">A Work in Progress</h3> | |
<p>This page (and OAuth support in FastHTML) is a work in progress. Questions, PRs, and feedback are welcome!</p> | |
</section> | |
</section> | |
</main> <!-- /main --> | |
<script id="quarto-html-after-body" type="application/javascript"> | |
window.document.addEventListener("DOMContentLoaded", function (event) { | |
const toggleBodyColorMode = (bsSheetEl) => { | |
const mode = bsSheetEl.getAttribute("data-mode"); | |
const bodyEl = window.document.querySelector("body"); | |
if (mode === "dark") { | |
bodyEl.classList.add("quarto-dark"); | |
bodyEl.classList.remove("quarto-light"); | |
} else { | |
bodyEl.classList.add("quarto-light"); | |
bodyEl.classList.remove("quarto-dark"); | |
} | |
} | |
const toggleBodyColorPrimary = () => { | |
const bsSheetEl = window.document.querySelector("link#quarto-bootstrap"); | |
if (bsSheetEl) { | |
toggleBodyColorMode(bsSheetEl); | |
} | |
} | |
toggleBodyColorPrimary(); | |
const icon = ""; | |
const anchorJS = new window.AnchorJS(); | |
anchorJS.options = { | |
placement: 'right', | |
icon: icon | |
}; | |
anchorJS.add('.anchored'); | |
const isCodeAnnotation = (el) => { | |
for (const clz of el.classList) { | |
if (clz.startsWith('code-annotation-')) { | |
return true; | |
} | |
} | |
return false; | |
} | |
const onCopySuccess = function(e) { | |
// button target | |
const button = e.trigger; | |
// don't keep focus | |
button.blur(); | |
// flash "checked" | |
button.classList.add('code-copy-button-checked'); | |
var currentTitle = button.getAttribute("title"); | |
button.setAttribute("title", "Copied!"); | |
let tooltip; | |
if (window.bootstrap) { | |
button.setAttribute("data-bs-toggle", "tooltip"); | |
button.setAttribute("data-bs-placement", "left"); | |
button.setAttribute("data-bs-title", "Copied!"); | |
tooltip = new bootstrap.Tooltip(button, | |
{ trigger: "manual", | |
customClass: "code-copy-button-tooltip", | |
offset: [0, -8]}); | |
tooltip.show(); | |
} | |
setTimeout(function() { | |
if (tooltip) { | |
tooltip.hide(); | |
button.removeAttribute("data-bs-title"); | |
button.removeAttribute("data-bs-toggle"); | |
button.removeAttribute("data-bs-placement"); | |
} | |
button.setAttribute("title", currentTitle); | |
button.classList.remove('code-copy-button-checked'); | |
}, 1000); | |
// clear code selection | |
e.clearSelection(); | |
} | |
const getTextToCopy = function(trigger) { | |
const codeEl = trigger.previousElementSibling.cloneNode(true); | |
for (const childEl of codeEl.children) { | |
if (isCodeAnnotation(childEl)) { | |
childEl.remove(); | |
} | |
} | |
return codeEl.innerText; | |
} | |
const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', { | |
text: getTextToCopy | |
}); | |
clipboard.on('success', onCopySuccess); | |
if (window.document.getElementById('quarto-embedded-source-code-modal')) { | |
const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', { | |
text: getTextToCopy, | |
container: window.document.getElementById('quarto-embedded-source-code-modal') | |
}); | |
clipboardModal.on('success', onCopySuccess); | |
} | |
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//); | |
var mailtoRegex = new RegExp(/^mailto:/); | |
var filterRegex = new RegExp("https:\/\/www\.fastht\.ml\/docs\/"); | |
var isInternal = (href) => { | |
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href); | |
} | |
// Inspect non-navigation links and adorn them if external | |
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)'); | |
for (var i=0; i<links.length; i++) { | |
const link = links[i]; | |
if (!isInternal(link.href)) { | |
// undo the damage that might have been done by quarto-nav.js in the case of | |
// links that we want to consider external | |
if (link.dataset.originalHref !== undefined) { | |
link.href = link.dataset.originalHref; | |
} | |
} | |
} | |
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) { | |
const config = { | |
allowHTML: true, | |
maxWidth: 500, | |
delay: 100, | |
arrow: false, | |
appendTo: function(el) { | |
return el.parentElement; | |
}, | |
interactive: true, | |
interactiveBorder: 10, | |
theme: 'quarto', | |
placement: 'bottom-start', | |
}; | |
if (contentFn) { | |
config.content = contentFn; | |
} | |
if (onTriggerFn) { | |
config.onTrigger = onTriggerFn; | |
} | |
if (onUntriggerFn) { | |
config.onUntrigger = onUntriggerFn; | |
} | |
window.tippy(el, config); | |
} | |
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]'); | |
for (var i=0; i<noterefs.length; i++) { | |
const ref = noterefs[i]; | |
tippyHover(ref, function() { | |
// use id or data attribute instead here | |
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href'); | |
try { href = new URL(href).hash; } catch {} | |
const id = href.replace(/^#\/?/, ""); | |
const note = window.document.getElementById(id); | |
if (note) { | |
return note.innerHTML; | |
} else { | |
return ""; | |
} | |
}); | |
} | |
const xrefs = window.document.querySelectorAll('a.quarto-xref'); | |
const processXRef = (id, note) => { | |
// Strip column container classes | |
const stripColumnClz = (el) => { | |
el.classList.remove("page-full", "page-columns"); | |
if (el.children) { | |
for (const child of el.children) { | |
stripColumnClz(child); | |
} | |
} | |
} | |
stripColumnClz(note) | |
if (id === null || id.startsWith('sec-')) { | |
// Special case sections, only their first couple elements | |
const container = document.createElement("div"); | |
if (note.children && note.children.length > 2) { | |
container.appendChild(note.children[0].cloneNode(true)); | |
for (let i = 1; i < note.children.length; i++) { | |
const child = note.children[i]; | |
if (child.tagName === "P" && child.innerText === "") { | |
continue; | |
} else { | |
container.appendChild(child.cloneNode(true)); | |
break; | |
} | |
} | |
if (window.Quarto?.typesetMath) { | |
window.Quarto.typesetMath(container); | |
} | |
return container.innerHTML | |
} else { | |
if (window.Quarto?.typesetMath) { | |
window.Quarto.typesetMath(note); | |
} | |
return note.innerHTML; | |
} | |
} else { | |
// Remove any anchor links if they are present | |
const anchorLink = note.querySelector('a.anchorjs-link'); | |
if (anchorLink) { | |
anchorLink.remove(); | |
} | |
if (window.Quarto?.typesetMath) { | |
window.Quarto.typesetMath(note); | |
} | |
if (note.classList.contains("callout")) { | |
return note.outerHTML; | |
} else { | |
return note.innerHTML; | |
} | |
} | |
} | |
for (var i=0; i<xrefs.length; i++) { | |
const xref = xrefs[i]; | |
tippyHover(xref, undefined, function(instance) { | |
instance.disable(); | |
let url = xref.getAttribute('href'); | |
let hash = undefined; | |
if (url.startsWith('#')) { | |
hash = url; | |
} else { | |
try { hash = new URL(url).hash; } catch {} | |
} | |
if (hash) { | |
const id = hash.replace(/^#\/?/, ""); | |
const note = window.document.getElementById(id); | |
if (note !== null) { | |
try { | |
const html = processXRef(id, note.cloneNode(true)); | |
instance.setContent(html); | |
} finally { | |
instance.enable(); | |
instance.show(); | |
} | |
} else { | |
// See if we can fetch this | |
fetch(url.split('#')[0]) | |
.then(res => res.text()) | |
.then(html => { | |
const parser = new DOMParser(); | |
const htmlDoc = parser.parseFromString(html, "text/html"); | |
const note = htmlDoc.getElementById(id); | |
if (note !== null) { | |
const html = processXRef(id, note); | |
instance.setContent(html); | |
} | |
}).finally(() => { | |
instance.enable(); | |
instance.show(); | |
}); | |
} | |
} else { | |
// See if we can fetch a full url (with no hash to target) | |
// This is a special case and we should probably do some content thinning / targeting | |
fetch(url) | |
.then(res => res.text()) | |
.then(html => { | |
const parser = new DOMParser(); | |
const htmlDoc = parser.parseFromString(html, "text/html"); | |
const note = htmlDoc.querySelector('main.content'); | |
if (note !== null) { | |
// This should only happen for chapter cross references | |
// (since there is no id in the URL) | |
// remove the first header | |
if (note.children.length > 0 && note.children[0].tagName === "HEADER") { | |
note.children[0].remove(); | |
} | |
const html = processXRef(null, note); | |
instance.setContent(html); | |
} | |
}).finally(() => { | |
instance.enable(); | |
instance.show(); | |
}); | |
} | |
}, function(instance) { | |
}); | |
} | |
let selectedAnnoteEl; | |
const selectorForAnnotation = ( cell, annotation) => { | |
let cellAttr = 'data-code-cell="' + cell + '"'; | |
let lineAttr = 'data-code-annotation="' + annotation + '"'; | |
const selector = 'span[' + cellAttr + '][' + lineAttr + ']'; | |
return selector; | |
} | |
const selectCodeLines = (annoteEl) => { | |
const doc = window.document; | |
const targetCell = annoteEl.getAttribute("data-target-cell"); | |
const targetAnnotation = annoteEl.getAttribute("data-target-annotation"); | |
const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation)); | |
const lines = annoteSpan.getAttribute("data-code-lines").split(","); | |
const lineIds = lines.map((line) => { | |
return targetCell + "-" + line; | |
}) | |
let top = null; | |
let height = null; | |
let parent = null; | |
if (lineIds.length > 0) { | |
//compute the position of the single el (top and bottom and make a div) | |
const el = window.document.getElementById(lineIds[0]); | |
top = el.offsetTop; | |
height = el.offsetHeight; | |
parent = el.parentElement.parentElement; | |
if (lineIds.length > 1) { | |
const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]); | |
const bottom = lastEl.offsetTop + lastEl.offsetHeight; | |
height = bottom - top; | |
} | |
if (top !== null && height !== null && parent !== null) { | |
// cook up a div (if necessary) and position it | |
let div = window.document.getElementById("code-annotation-line-highlight"); | |
if (div === null) { | |
div = window.document.createElement("div"); | |
div.setAttribute("id", "code-annotation-line-highlight"); | |
div.style.position = 'absolute'; | |
parent.appendChild(div); | |
} | |
div.style.top = top - 2 + "px"; | |
div.style.height = height + 4 + "px"; | |
div.style.left = 0; | |
let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter"); | |
if (gutterDiv === null) { | |
gutterDiv = window.document.createElement("div"); | |
gutterDiv.setAttribute("id", "code-annotation-line-highlight-gutter"); | |
gutterDiv.style.position = 'absolute'; | |
const codeCell = window.document.getElementById(targetCell); | |
const gutter = codeCell.querySelector('.code-annotation-gutter'); | |
gutter.appendChild(gutterDiv); | |
} | |
gutterDiv.style.top = top - 2 + "px"; | |
gutterDiv.style.height = height + 4 + "px"; | |
} | |
selectedAnnoteEl = annoteEl; | |
} | |
}; | |
const unselectCodeLines = () => { | |
const elementsIds = ["code-annotation-line-highlight", "code-annotation-line-highlight-gutter"]; | |
elementsIds.forEach((elId) => { | |
const div = window.document.getElementById(elId); | |
if (div) { | |
div.remove(); | |
} | |
}); | |
selectedAnnoteEl = undefined; | |
}; | |
// Handle positioning of the toggle | |
window.addEventListener( | |
"resize", | |
throttle(() => { | |
elRect = undefined; | |
if (selectedAnnoteEl) { | |
selectCodeLines(selectedAnnoteEl); | |
} | |
}, 10) | |
); | |
function throttle(fn, ms) { | |
let throttle = false; | |
let timer; | |
return (...args) => { | |
if(!throttle) { // first call gets through | |
fn.apply(this, args); | |
throttle = true; | |
} else { // all the others get throttled | |
if(timer) clearTimeout(timer); // cancel #2 | |
timer = setTimeout(() => { | |
fn.apply(this, args); | |
timer = throttle = false; | |
}, ms); | |
} | |
}; | |
} | |
// Attach click handler to the DT | |
const annoteDls = window.document.querySelectorAll('dt[data-target-cell]'); | |
for (const annoteDlNode of annoteDls) { | |
annoteDlNode.addEventListener('click', (event) => { | |
const clickedEl = event.target; | |
if (clickedEl !== selectedAnnoteEl) { | |
unselectCodeLines(); | |
const activeEl = window.document.querySelector('dt[data-target-cell].code-annotation-active'); | |
if (activeEl) { | |
activeEl.classList.remove('code-annotation-active'); | |
} | |
selectCodeLines(clickedEl); | |
clickedEl.classList.add('code-annotation-active'); | |
} else { | |
// Unselect the line | |
unselectCodeLines(); | |
clickedEl.classList.remove('code-annotation-active'); | |
} | |
}); | |
} | |
const findCites = (el) => { | |
const parentEl = el.parentElement; | |
if (parentEl) { | |
const cites = parentEl.dataset.cites; | |
if (cites) { | |
return { | |
el, | |
cites: cites.split(' ') | |
}; | |
} else { | |
return findCites(el.parentElement) | |
} | |
} else { | |
return undefined; | |
} | |
}; | |
var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]'); | |
for (var i=0; i<bibliorefs.length; i++) { | |
const ref = bibliorefs[i]; | |
const citeInfo = findCites(ref); | |
if (citeInfo) { | |
tippyHover(citeInfo.el, function() { | |
var popup = window.document.createElement('div'); | |
citeInfo.cites.forEach(function(cite) { | |
var citeDiv = window.document.createElement('div'); | |
citeDiv.classList.add('hanging-indent'); | |
citeDiv.classList.add('csl-entry'); | |
var biblioDiv = window.document.getElementById('ref-' + cite); | |
if (biblioDiv) { | |
citeDiv.innerHTML = biblioDiv.innerHTML; | |
} | |
popup.appendChild(citeDiv); | |
}); | |
return popup.innerHTML; | |
}); | |
} | |
} | |
}); | |
</script> | |
</div> <!-- /content --> | |
<footer class="footer"><div class="nav-footer"><div class="nav-footer-center"><div class="toc-actions d-sm-block d-md-none"><ul><li><a href="https://github.com/AnswerDotAI/fasthtml/issues/new" class="toc-action"><i class="bi bi-github"></i>Report an issue</a></li></ul></div></div></div></footer></body></html> |