CSC-105

LibraryAccounts in your app

Accounts in your app

Some apps need to know who's using them: so someone's groups follow them from phone to laptop, so a shared list shows who added what, or so a post really comes from the person whose name is on it. An account gives each person a username, a password and a profile, kept by your app's server.

When you need it

Every person has to make an account before they can try your app, and you keep everyone's account safe until Demo Day. So use the smallest thing that works:

Your app needsUse
Each person's data, on their own phoneNo account: localStorage
A name on what people share, like a leaderboardA name they type once, kept in localStorage and sent with what they share
Private data, data on every device, or posts only their author can changeAccounts, with a username and a password

A name with no password is often enough for a test. Anyone can type any name, so keep anything private out of it.

Accounts need a server and a database, so your agent adds those too, as A server for your app shows.

How it works

Your server keeps two tables:

  • users: each person's username, their password as a hash, and their profile.
  • sessions: who's signed in, and on which browser. Signing in makes a long random id, saves it here, and gives it to the browser in a cookie. The browser sends the cookie back with every request, so your server knows who's asking.

Bun has all of it built in, so your app needs no packages:

// server.ts
import { Database } from "bun:sqlite"
import homepage from "./index.html"

const db = new Database(`${process.env.DATA_DIR ?? "./data"}/app.sqlite`, { create: true, strict: true })
db.run("PRAGMA journal_mode = WAL")
db.run("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT NOT NULL UNIQUE, password TEXT NOT NULL, name TEXT NOT NULL, bio TEXT NOT NULL DEFAULT '', created TEXT NOT NULL)")
db.run("CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires INTEGER NOT NULL)")

const MONTH = 30 * 24 * 60 * 60 // in seconds
// Set like this, the cookie works at your app's address and in the Studio's App tab.
const COOKIE = { httpOnly: true, path: "/", sameSite: "none", secure: true, partitioned: true, maxAge: MONTH } as const

type User = { id: number; username: string; password: string; name: string; bio: string }

/** What the page and other people see of someone: never the whole row, which holds their password's hash. */
const profile = ({ username, name, bio }: User) => ({ username, name, bio })
const problem = (error: string, status = 400) => Response.json({ error }, { status })
const usernameOf = (value: unknown) => String(value ?? "").trim().toLowerCase()

/** Who sent this request, or null. A request from another site never counts. */
function signedIn(req: Bun.BunRequest) {
  const session = req.cookies.get("session")
  if (!session || req.headers.get("sec-fetch-site") === "cross-site") return null
  return db
    .query("SELECT users.* FROM sessions JOIN users ON users.id = sessions.user_id WHERE sessions.id = $session AND sessions.expires > $now")
    .get({ session, now: Date.now() }) as User | null
}

function startSession(req: Bun.BunRequest, user: User, status = 200) {
  const id = crypto.randomUUID()
  db.query("INSERT INTO sessions (id, user_id, expires) VALUES ($id, $user, $expires)").run({ id, user: user.id, expires: Date.now() + MONTH * 1000 })
  req.cookies.set("session", id, COOKIE)
  return Response.json(profile(user), { status })
}

Bun.serve({
  routes: {
    "/": homepage,
    "/health": new Response("ok"),
    "/api/signup": {
      POST: async (req) => {
        const { username, password } = await req.json()
        const handle = usernameOf(username)
        if (!/^[a-z0-9_.]{3,20}$/.test(handle)) return problem("Pick a username of 3 to 20 letters or numbers.")
        if (typeof password !== "string" || password.length < 8) return problem("Use a password of at least 8 characters.")
        if (db.query("SELECT 1 FROM users WHERE username = $handle").get({ handle })) return problem("That username is taken.", 409)
        const user = db
          .query("INSERT INTO users (username, password, name, created) VALUES ($handle, $hash, $handle, $created) RETURNING *")
          .get({ handle, hash: await Bun.password.hash(password), created: new Date().toISOString() }) as User
        return startSession(req, user, 201)
      },
    },
    "/api/signin": {
      POST: async (req) => {
        const { username, password } = await req.json()
        const user = db.query("SELECT * FROM users WHERE username = $handle").get({ handle: usernameOf(username) }) as User | null
        const right = user && typeof password === "string" && (await Bun.password.verify(password, user.password))
        return right ? startSession(req, user) : problem("That username or password is wrong.", 401)
      },
    },
    "/api/signout": {
      POST: (req) => {
        db.query("DELETE FROM sessions WHERE id = $id").run({ id: req.cookies.get("session") ?? "" })
        req.cookies.set("session", "", { ...COOKIE, maxAge: 0 })
        return Response.json({ ok: true })
      },
    },
    "/api/me": {
      GET: (req) => {
        const user = signedIn(req)
        return user ? Response.json(profile(user)) : problem("Sign in first.", 401)
      },
    },
  },
})
  • Usernames are lowercase, so Maya and maya are one person.
  • Passwords are hashed with Bun.password. A hash can check a password, but it can't be turned back into one.
  • A wrong sign-in never says which part was wrong, so no one can find out who has an account.
  • Only your own pages count. A request from another site is never signed in, so no other page can act for your users.
  • Signing out deletes the session, so the old cookie stops working, even in a browser that kept it.

The sign-in screen

One short form does both: Sign in, and Create account for someone new.

<form id="sign-in">
  <label>Username <input name="username" autocomplete="username" required /></label>
  <label>Password <input name="password" type="password" autocomplete="current-password" minlength="8" required /></label>
  <p class="error" role="alert"></p>
  <button>Sign in</button>
  <button type="button" id="switch">New here? Create an account</button>
</form>
// app.js: showApp and showSignIn switch screens; creating is true after "Create an account"
const me = await fetch("api/me").then((response) => (response.ok ? response.json() : null))
me ? showApp(me) : showSignIn()

form.addEventListener("submit", async (event) => {
  event.preventDefault()
  const response = await fetch(creating ? "api/signup" : "api/signin", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(Object.fromEntries(new FormData(form))),
  })
  const result = await response.json()
  if (response.ok) showApp(result)
  else form.querySelector(".error").textContent = result.error
})
  • Let people look first. Show what your app does, with sample data, and ask for an account when they have something to save. Every screen before the core task loses testers.
  • Let the phone help. With autocomplete, phones fill in a saved password. Switch the password's to "new-password" for Create account, and phones offer a strong one.
  • Say what went wrong in plain words, and keep what they typed: "That username is taken."
  • Show who's signed in, with their name or initials in a corner, and put Sign out where people look for it, such as their profile or settings.

Each person's data

Every row someone makes keeps their id, and every query that reads or changes it checks that id. The server decides who sees what, never the page.

"/api/notes": {
  GET: (req) => {
    const user = signedIn(req)
    if (!user) return problem("Sign in first.", 401)
    return Response.json(db.query("SELECT id, text, created FROM notes WHERE user_id = $user ORDER BY id DESC").all({ user: user.id }))
  },
},
"/api/notes/:id": {
  DELETE: (req) => {
    const user = signedIn(req)
    if (!user) return problem("Sign in first.", 401)
    const gone = db.query("DELETE FROM notes WHERE id = $id AND user_id = $user").run({ id: Number(req.params.id), user: user.id })
    return gone.changes ? Response.json({ ok: true }) : problem("That note isn't yours, or it's gone.", 404)
  },
},

Without AND user_id = $user, anyone signed in could delete anyone's note by changing a number. When people share something, like a group, a table of members says who belongs, and the server checks it the same way.

Profiles

  • A username to sign in, and a name to show. The username stays the same. The name is what others see, and people can change it anytime: "Maya R." or "Coach Davis".
  • Only what your app uses. A bio, a class year or a favorite trail, if your app shows it. Each is a column in users, added the way A server for your app shows, and in profile, so people can see it.
  • A picture is optional. Initials in a colored circle look good and cost nothing. A photo is a file your server saves under DATA_DIR, named by the person's id, after checking it's a picture of a few megabytes at most.

People change their own profile, and no one else's:

"/api/me": {
  GET: …, // as above
  PATCH: async (req) => {
    const user = signedIn(req)
    if (!user) return problem("Sign in first.", 401)
    const { name, bio } = await req.json()
    if (typeof name !== "string" || !name.trim()) return problem("Write the name people should see.")
    const updated = db
      .query("UPDATE users SET name = $name, bio = $bio WHERE id = $id RETURNING *")
      .get({ id: user.id, name: name.trim().slice(0, 60), bio: String(bio ?? "").trim().slice(0, 300) }) as User
    return Response.json(profile(updated))
  },
},

When someone forgets

Your app can't send email, so there's no "Forgot password?" link. You reset it instead: you're your app's owner, and you know your testers. Your app makes them a temporary password, and you tell it to them in person or by text. They sign in with it, then change it.

const OWNER = "maya" // your own username in your app: only you can reset passwords

"/api/reset": {
  POST: async (req) => {
    if (signedIn(req)?.username !== OWNER) return problem("Only the app's owner can reset a password.", 403)
    const { username } = await req.json()
    const password = crypto.randomUUID().slice(0, 8)
    const user = db
      .query("UPDATE users SET password = $hash WHERE username = $handle RETURNING id")
      .get({ handle: usernameOf(username), hash: await Bun.password.hash(password) }) as { id: number } | null
    if (!user) return problem("No one has that username.", 404)
    db.query("DELETE FROM sessions WHERE user_id = $id").run({ id: user.id })
    return Response.json({ password })
  },
},
  • Make your own account first, at your real address and in the preview, before anyone else can take your username.
  • A reset signs them out everywhere, so the old password and any session stop working.
  • Show the reset form only on your own profile. The server checks it's you either way.

Trying it

The App tab shows your app inside the Studio's page, where browsers hold back ordinary cookies. That's why COOKIE has sameSite, secure and partitioned. A sign-in there stays in the App tab, apart from one at your app's own address. If it won't stay, Open in a new tab, in the bar above your app, works as your real address does.

Your agent tries sign-in with a test account in the preview. The App tab shares its sign-in, so after your agent looks, you may find yourself signed in as its test account, or signed out.

The preview's accounts are its own. Accounts made there aren't online, and accounts made online aren't in the preview. Anyone with the preview's address can open it, so use made-up names and passwords there.

Before a test, open your real address on your own phone, create an account, and go on to the core task, the way your testers will.

Once people have accounts, they stay. Change a table the way A server for your app shows, never by starting over.

Limits and privacy

  • No email. Your server can't send any, so there's no email to confirm, and you reset forgotten passwords yourself. Someone signed in can change their password by typing the old one first. Skip security questions: their answers are easy to guess or look up.
  • No "Sign in with Google" or Furman. Your server can't reach them to check who someone is.
  • Ask only for what your app uses. A username and a password are enough: no email, phone number, birthday or student ID.
  • A new password for your app. Say so on the sign-up screen: "Use a password you don't use anywhere else."
  • Passwords stay hashed: never in a log, a reply, your repo or your docs.
  • Let people leave. Delete my account removes their account, their sessions and what they made.