GitHub

Example: Accounts

Your own registration, password hashing, sessions and protected pages.

  • 135 lines of Python
  • 3 pages
  • 3 server functions
  • 3487 B page JS (gzip)
This example needs its server (database, sessions or server functions). Run it locally:
Terminal
pyweb dev examples/auth/app.pyweb

#Source

examples/auth/app.pyweb
"""Accounts: password hashing, signed-cookie sessions, protected pages."""

from pyweb import App, RPCError, redirect, server, session
from pyweb.auth import hash_password, verify_password
from pyweb.ui import Badge, Button, Card, CardContent, CardDescription, CardFooter, CardHeader

app = App(title="Accounts", stylesheets=["/static/app.css"])

# In-memory user store keeps the example self-contained; use a database
# table (see examples/blog) in a real app.
USERS = {}


@server
def register(email: str, name: str, password: str) -> bool:
    email = email.strip().lower()
    if "@" not in email or len(password) < 8:
        raise RPCError("validation_error", "Use a valid email and a password of 8+ characters.")
    if email in USERS:
        raise RPCError("conflict", "That email is already registered.")
    USERS[email] = {"name": name.strip() or email, "hash": hash_password(password)}
    session.login(email, name=USERS[email]["name"])
    return True


@server
def login(email: str, password: str) -> bool:
    user = USERS.get(email.strip().lower())
    if user is None or not verify_password(password, user["hash"]):
        return False
    session.login(email.strip().lower(), name=user["name"])
    return True


@server
def logout() -> None:
    session.logout()


@app.page("/", title="Sign in")
def Login():
    if session.user():
        return redirect("/account")
    email = ""
    password = ""
    error = ""

    def submit():
        if login(email, password):
            window.location.href = "/account"
        else:
            error = "Wrong email or password."

    <main class="narrow">
        <Card animate="fade-up">
            <CardHeader>
                <h1 data-part="title">Sign in</h1>
                <CardDescription>Welcome back.</CardDescription>
            </CardHeader>
            <CardContent>
                <form class="stack" onsubmit={submit}>
                    <label class="pw-field">Email <input id="email" class="pw-control" type="email" bind={email} /></label>
                    <label class="pw-field">Password
                        <input id="password" class="pw-control" type="password" bind={password} />
                    </label>
                    <p class="error" id="error" role="alert">{error}</p>
                    <Button id="login" type="submit">Sign in</Button>
                </form>
            </CardContent>
            <CardFooter>
                <p class="muted">No account? <a href="/register">Create one</a>.</p>
            </CardFooter>
        </Card>
    </main>


@app.page("/register", title="Create account")
def Register():
    email = ""
    name = ""
    password = ""
    error = ""

    def submit():
        try:
            register(email, name, password)
            window.location.href = "/account"
        except RPCError as e:
            error = str(e)

    <main class="narrow">
        <Card animate="fade-up">
            <CardHeader>
                <h1 data-part="title">Create account</h1>
                <CardDescription>It takes ten seconds.</CardDescription>
            </CardHeader>
            <CardContent>
                <form class="stack" onsubmit={submit}>
                    <label class="pw-field">Name <input id="name" class="pw-control" bind={name} /></label>
                    <label class="pw-field">Email <input id="email" class="pw-control" type="email" bind={email} /></label>
                    <label class="pw-field">Password
                        <input id="password" class="pw-control" type="password" bind={password}
                               placeholder="8+ characters" />
                    </label>
                    <p class="error" id="error" role="alert">{error}</p>
                    <Button id="register" type="submit">Create account</Button>
                </form>
            </CardContent>
        </Card>
    </main>


@app.page("/account", title="Your account")
def Account():
    user = session.user()
    if not user:
        return redirect("/")
    name = user["name"]
    email = user["sub"]

    def sign_out():
        logout()
        window.location.href = "/"

    <main class="narrow">
        <Card animate="fade-up">
            <CardHeader>
                <h1 data-part="title">Hello, {name}</h1>
                <CardDescription>Signed in as {email} <Badge tone="success">active session</Badge></CardDescription>
            </CardHeader>
            <CardFooter>
                <Button id="logout" variant="outline" onclick={sign_out}>Sign out</Button>
            </CardFooter>
        </Card>
    </main>

#What runs where

Output of pyweb inspect: every page variable, handler and server function, where it runs and why.

Output
page Login  route=/
  browser  email          reactive state: bound to an input (line 62); literal initial value
  browser  password       reactive state: bound to an input (line 64); literal initial value
  browser  error          reactive state: assigned in submit(); literal initial value
  browser  submit         event handler (compiled to JavaScript)
page Register  route=/register
  browser  email          reactive state: bound to an input (line 100); literal initial value
  browser  name           reactive state: bound to an input (line 99); literal initial value
  browser  password       reactive state: bound to an input (line 102); literal initial value
  browser  error          reactive state: assigned in submit(); literal initial value
  browser  submit         event handler (compiled to JavaScript)
page Account  route=/account
  server   user           computed per request; never read by browser code, never sent
  server   name           computed per request on the server; value sent because browser code reads it
  server   email          computed per request on the server; value sent because browser code reads it
  browser  sign_out       event handler (compiled to JavaScript)
rpc POST /__pyweb/rpc/register  (email: str, name: str, password: str) -> bool
rpc POST /__pyweb/rpc/login  (email: str, password: str) -> bool
rpc POST /__pyweb/rpc/logout  () -> None

#Generated JavaScript

The browser modules the compiler wrote (before minification). They import the shared runtime.

JavaScript
// Login.js
import { h as $h, t as $t, dyn as $dyn, list as $list, when as $when, signal as $signal, computed as $computed, mount as $mount, onMount as $onMount, py as $py, rpc as $rpc, slot as $slot, onCleanup as $onCleanup, spreadProps as $spreadProps } from "./runtime.js";
// card.pyweb
const { Card, CardHeader, CardDescription, CardContent, CardFooter } = (() => {
  function Card($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"class": "pw-card", "data-pw-ui": "card", "data-part": "card", "$spread3": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardHeader($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"data-part": "header", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardDescription($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("p", {"data-part": "description", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardContent($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"data-part": "content", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardFooter($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"data-part": "footer", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  return { Card, CardHeader, CardDescription, CardContent, CardFooter };
})();
// button.pyweb
const { Button } = (() => {
  function Button($p) {
    const variant = $p["variant"] || (() => "default");
    const size = $p["size"] || (() => "md");
    const type = $p["type"] || (() => "button");
    const href = $p["href"] || (() => null);
    const loading = $p["loading"] || (() => false);
    const disabled = $p["disabled"] || (() => false);
    const onclick = $p["onclick"] || (() => null);
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    const busy = $computed(() => ($py.truth(loading()) ? "true" : null));
    const part = $computed(() => $py.or($py.m(attrs(), "get", "data-part"), () => "button"));
    return [$when(() => $py.truth(href()), () => [$h("a", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "href": () => href(), "aria-disabled": () => ($py.truth(disabled()) ? "true" : null), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread7": () => attrs()}, () => [$dyn(() => children())])], () => [$h("button", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "type": () => type(), "disabled": () => $py.or(disabled(), () => loading()), "aria-busy": () => busy(), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread8": () => attrs()}, () => [
          $when(() => $py.truth(loading()), () => [$h("span", {"class": "pw-spinner", "aria-hidden": "true"})]),
          $dyn(() => children())
        ])])];
  }
  return { Button };
})();
function Login($s) {
  const email = $signal("email" in $s ? $s["email"] : "", "email");
  const password = $signal("password" in $s ? $s["password"] : "", "password");
  const error = $signal("error" in $s ? $s["error"] : "", "error");
  async function submit() {
    if ($py.truth((await $rpc("login", {"email": email(), "password": password()})))) {
      window.location.href = "/account";
    } else {
      error("Wrong email or password.");
    }
  }
  return [$h("main", {"class": "narrow"}, () => [Card({"children": () => [
        CardHeader({"children": () => [
          $h("h1", {"data-part": "title"}, () => [$t("Sign in")]),
          CardDescription({"children": () => [$t("Welcome back.")]})
        ]}),
        CardContent({"children": () => [$h("form", {"class": "stack", "onsubmit": submit}, () => [
            $h("label", {"class": "pw-field"}, () => [
              $t("Email "),
              $h("input", {"id": "email", "class": "pw-control", "type": "email", "$bind": email})
            ]),
            $h("label", {"class": "pw-field"}, () => [
              $t("Password"),
              $h("input", {"id": "password", "class": "pw-control", "type": "password", "$bind": password})
            ]),
            $h("p", {"class": "error", "id": "error", "role": "alert"}, () => [$dyn(() => error())]),
            Button({"type": () => "submit", "children": () => [$t("Sign in")], "$rest": () => ({"id": "login"})})
          ])]}),
        CardFooter({"children": () => [$h("p", {"class": "muted"}, () => [
            $t("No account? "),
            $h("a", {"href": "/register"}, () => [$t("Create one")]),
            $t(".")
          ])]})
      ], "$rest": () => ({"data-pw-motion": JSON.stringify({"animate": "fade-up"})})})])];
}
$mount("Login", Login);


// Register.js
import { h as $h, t as $t, dyn as $dyn, list as $list, when as $when, signal as $signal, computed as $computed, mount as $mount, onMount as $onMount, py as $py, rpc as $rpc, slot as $slot, onCleanup as $onCleanup, spreadProps as $spreadProps } from "./runtime.js";
// card.pyweb
const { Card, CardHeader, CardDescription, CardContent } = (() => {
  function Card($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"class": "pw-card", "data-pw-ui": "card", "data-part": "card", "$spread3": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardHeader($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"data-part": "header", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardDescription($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("p", {"data-part": "description", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardContent($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"data-part": "content", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  return { Card, CardHeader, CardDescription, CardContent };
})();
// button.pyweb
const { Button } = (() => {
  function Button($p) {
    const variant = $p["variant"] || (() => "default");
    const size = $p["size"] || (() => "md");
    const type = $p["type"] || (() => "button");
    const href = $p["href"] || (() => null);
    const loading = $p["loading"] || (() => false);
    const disabled = $p["disabled"] || (() => false);
    const onclick = $p["onclick"] || (() => null);
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    const busy = $computed(() => ($py.truth(loading()) ? "true" : null));
    const part = $computed(() => $py.or($py.m(attrs(), "get", "data-part"), () => "button"));
    return [$when(() => $py.truth(href()), () => [$h("a", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "href": () => href(), "aria-disabled": () => ($py.truth(disabled()) ? "true" : null), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread7": () => attrs()}, () => [$dyn(() => children())])], () => [$h("button", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "type": () => type(), "disabled": () => $py.or(disabled(), () => loading()), "aria-busy": () => busy(), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread8": () => attrs()}, () => [
          $when(() => $py.truth(loading()), () => [$h("span", {"class": "pw-spinner", "aria-hidden": "true"})]),
          $dyn(() => children())
        ])])];
  }
  return { Button };
})();
function Register($s) {
  const email = $signal("email" in $s ? $s["email"] : "", "email");
  const name = $signal("name" in $s ? $s["name"] : "", "name");
  const password = $signal("password" in $s ? $s["password"] : "", "password");
  const error = $signal("error" in $s ? $s["error"] : "", "error");
  async function submit() {
    let e;
    try {
      (await $rpc("register", {"email": email(), "name": name(), "password": password()}));
      window.location.href = "/account";
    } catch ($err) {
      if ($py.exc($err, ["RPCError"])) {
        e = $err;
        error($py.str(e));
      } else { throw $err; }
    }
  }
  return [$h("main", {"class": "narrow"}, () => [Card({"children": () => [
        CardHeader({"children": () => [
          $h("h1", {"data-part": "title"}, () => [$t("Create account")]),
          CardDescription({"children": () => [$t("It takes ten seconds.")]})
        ]}),
        CardContent({"children": () => [$h("form", {"class": "stack", "onsubmit": submit}, () => [
            $h("label", {"class": "pw-field"}, () => [
              $t("Name "),
              $h("input", {"id": "name", "class": "pw-control", "$bind": name})
            ]),
            $h("label", {"class": "pw-field"}, () => [
              $t("Email "),
              $h("input", {"id": "email", "class": "pw-control", "type": "email", "$bind": email})
            ]),
            $h("label", {"class": "pw-field"}, () => [
              $t("Password"),
              $h("input", {"id": "password", "class": "pw-control", "type": "password", "$bind": password, "placeholder": "8+ characters"})
            ]),
            $h("p", {"class": "error", "id": "error", "role": "alert"}, () => [$dyn(() => error())]),
            Button({"type": () => "submit", "children": () => [$t("Create account")], "$rest": () => ({"id": "register"})})
          ])]})
      ], "$rest": () => ({"data-pw-motion": JSON.stringify({"animate": "fade-up"})})})])];
}
$mount("Register", Register);


// Account.js
import { h as $h, t as $t, dyn as $dyn, list as $list, when as $when, signal as $signal, computed as $computed, mount as $mount, onMount as $onMount, py as $py, rpc as $rpc, slot as $slot, onCleanup as $onCleanup, spreadProps as $spreadProps } from "./runtime.js";
// card.pyweb
const { Card, CardHeader, CardDescription, CardFooter } = (() => {
  function Card($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"class": "pw-card", "data-pw-ui": "card", "data-part": "card", "$spread3": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardHeader($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"data-part": "header", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardDescription($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("p", {"data-part": "description", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardFooter($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"data-part": "footer", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  return { Card, CardHeader, CardDescription, CardFooter };
})();
// display.pyweb
const { Badge } = (() => {
  function Badge($p) {
    const variant = $p["variant"] || (() => "soft");
    const tone = $p["tone"] || (() => null);
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("span", {"class": "pw-badge", "data-part": "badge", "data-variant": () => variant(), "data-tone": () => tone(), "$spread4": () => attrs()}, () => [$dyn(() => children())])];
  }
  return { Badge };
})();
// button.pyweb
const { Button } = (() => {
  function Button($p) {
    const variant = $p["variant"] || (() => "default");
    const size = $p["size"] || (() => "md");
    const type = $p["type"] || (() => "button");
    const href = $p["href"] || (() => null);
    const loading = $p["loading"] || (() => false);
    const disabled = $p["disabled"] || (() => false);
    const onclick = $p["onclick"] || (() => null);
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    const busy = $computed(() => ($py.truth(loading()) ? "true" : null));
    const part = $computed(() => $py.or($py.m(attrs(), "get", "data-part"), () => "button"));
    return [$when(() => $py.truth(href()), () => [$h("a", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "href": () => href(), "aria-disabled": () => ($py.truth(disabled()) ? "true" : null), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread7": () => attrs()}, () => [$dyn(() => children())])], () => [$h("button", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "type": () => type(), "disabled": () => $py.or(disabled(), () => loading()), "aria-busy": () => busy(), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread8": () => attrs()}, () => [
          $when(() => $py.truth(loading()), () => [$h("span", {"class": "pw-spinner", "aria-hidden": "true"})]),
          $dyn(() => children())
        ])])];
  }
  return { Button };
})();
function Account($s) {
  const name = $s["name"];
  const email = $s["email"];
  async function sign_out() {
    (await $rpc("logout", {}));
    window.location.href = "/";
  }
  return [$h("main", {"class": "narrow"}, () => [Card({"children": () => [
        CardHeader({"children": () => [
          $h("h1", {"data-part": "title"}, () => [
            $t("Hello, "),
            $t($py.text(name))
          ]),
          CardDescription({"children": () => [
            $t("Signed in as "),
            $t($py.text(email)),
            $t(" "),
            Badge({"tone": () => "success", "children": () => [$t("active session")]})
          ]})
        ]}),
        CardFooter({"children": () => [Button({"variant": () => "outline", "onclick": () => sign_out, "children": () => [$t("Sign out")], "$rest": () => ({"id": "logout"})})]})
      ], "$rest": () => ({"data-pw-motion": JSON.stringify({"animate": "fade-up"})})})])];
}
$mount("Account", Account);
Edit this page on GitHub