import { ValTownAdapter } from "https://esm.town/v/stevekrouse/lucia_adapter";
import { createUser, getUser, verifyPassword } from "https://esm.town/v/stevekrouse/lucia_sqlite";
import { Hono } from "npm:hono";
import { getCookie } from "npm:hono/cookie";
import { HTTPException } from "npm:hono/http-exception";
import { jsxRenderer } from "npm:hono/jsx-renderer";
import { Lucia, Session, User, verifyRequestOrigin } from "npm:lucia@3.0.1";
import { createDate, isWithinExpirationDate, TimeSpan } from "npm:oslo";
const userTable = "lucia_users_1";
const sessionTable = "lucia_sessions_1";
const adapter = new ValTownAdapter({ userTable, sessionTable });
export const lucia = new Lucia(adapter, {
sessionCookie: {
attributes: {
sameSite: "none",
},
},
getUserAttributes: (attributes) => {
return {
username: attributes.username,
};
},
});
declare module "npm:lucia" {
interface Register {
Lucia: typeof lucia;
DatabaseUserAttributes: DatabaseUserAttributes;
}
}
interface DatabaseUserAttributes {
username: string;
}
export const luciaMiddleware = (handler: (req: Request) => Response | Promise<Response>) => {
const app = new Hono<{
Variables: {
user: User | null;
session: Session | null;
};
}>();
app.use("*", async (c, next) => {
const sessionId = getCookie(c, lucia.sessionCookieName) ?? null;
if (!sessionId) {
c.set("user", null);
c.set("session", null);
return next();
}
const { session, user } = await lucia.validateSession(sessionId);
if (session && session.fresh) {
c.header("Set-Cookie", lucia.createSessionCookie(session.id).serialize(), {
append: true,
});
}
if (!session) {
c.header("Set-Cookie", lucia.createBlankSessionCookie().serialize(), {
append: true,
});
}
c.set("user", user);
c.set("session", session);
return next();
});
app.get("/auth/signup", c =>
c.render(
<div>
<h1 style="text-align: center;">Sign up</h1>
<form
method="post"
action="/auth/signup"
style="display: flex; flex-direction: column; gap: 0.5rem; align-items: center;"
>
<div>
<input id="username" name="username" autocomplete="off" placeholder="Username" />
</div>
<div>
<input id="password" name="password" type="password" autocomplete="off" placeholder="Password" />
</div>
<input type="submit" value="Sign up" />
</form>
</div>,
));
app.post("/auth/signup", async c => {
const body = await c.req.parseBody();
if (typeof body.username !== "string" || typeof body.password !== "string") {
return new Response("Invalid login", {
status: 400,
});
}
const username = body.username;
const password = body.password;
if (