C.W.K.
Stream
Lesson 05 of 06 · published

Logout & Session Lifecycle

~15 min · logout, session-lifecycle, killswitch

Level 0Greenhorn
0 XP0/53 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

Sessions need to die: explicitly (logout button), automatically (expiry), or en masse (Revoke All from the killswitch). Each path is one line of SQL plus a cookie clear.

Session sliding vs fixed expiry — pick one

PatternBehaviorProCon
Fixed (recommended)Created at T, expires at T+30d, periodPredictable; easy to reason aboutActive users get logged out at the wall
SlidingEach request bumps expires_at to now+30dActive users stay logged inInactive sessions linger if any request fires (e.g. a tab keeping a poller alive)

Code

Explicit logout — one DELETE + cookie clear·python
@app.post("/logout")
async def logout(request: Request):
    token = request.cookies.get("session")
    if token:
        db.execute("DELETE FROM security_sessions WHERE token = ?", (token,))
        db.commit()
    response = RedirectResponse("/login", status_code=302)
    response.delete_cookie("session")
    return response
Periodic expired-session sweep·python
def reap_expired_sessions():
    now = int(time.time())
    cur = db.execute("DELETE FROM security_sessions WHERE expires_at < ?", (now,))
    db.commit()
    return cur.rowcount

# Run on app startup, or as a daily cron, or before every login attempt
The killswitch endpoint — Revoke All in three lines·python
@app.post("/admin/security/revoke-all")
async def revoke_all(request: Request):
    require_admin(request)        # Track 8 — admin AuthZ
    cur = db.execute("DELETE FROM security_sessions")
    db.commit()
    return {"revoked": cur.rowcount}

External links

Exercise

Add /logout and /admin/security/revoke-all to your app. Test: login with PIN, hit /logout (cookie cleared, redirect to /login). Login again from two browsers, hit /admin/security/revoke-all from one — both browsers fail on the next request. That is the killswitch demonstrated end-to-end.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.