import { raw, sql } from "https://esm.town/v/pomdtr/sql";
import { sqlite } from "https://esm.town/v/std/sqlite?v=4";
import { zip } from "npm:lodash-es";
import { generateId, Scrypt } from "npm:lucia";
export async function createTables(userTable: string, sessionTable: string) {
return sqlite.batch([
`CREATE TABLE ${userTable} (
id TEXT NOT NULL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
hashed_password TEXT NOT NULL
);`,
`CREATE TABLE ${sessionTable} (
id TEXT NOT NULL PRIMARY KEY,
expires_at INTEGER NOT NULL,
user_id TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES ${userTable}(id)
);`,
]);
}
async function safeExecute({ userTable, sessionTable, query, error }: {
userTable: string;
sessionTable: string;
query: any;
error?: string;
}) {
try {
return await sqlite.execute(query);
} catch (e) {
if (e.message === `SQLITE_UNKNOWN: SQLite error: no such table: ${userTable}`) {
console.log(`Creating tables for ${userTable} and ${sessionTable}`);
await createTables(userTable, sessionTable);
return sqlite.execute(query);
}
throw e;
}
}
export async function createUser({ userTable, sessionTable, username, password }: {
userTable: string;
sessionTable: string;
username: string;
password: string;
}) {
const userId = generateId(15);
const hashedPassword = await new Scrypt().hash(password);
await safeExecute({
userTable,
sessionTable,
query: sql`INSERT INTO ${
raw(userTable)
} (id, username, hashed_password) VALUES (${userId}, ${username}, ${hashedPassword})`,
});
return userId;
}
export async function getUser(
{ userTable, sessionTable, username },
): Promise<{ id: string; username: string; hashed_password: string } | null> {
const { rows, columns } = await safeExecute({
userTable,
sessionTable,
query: sql`SELECT * from ${raw(userTable)} where username = ${username}`,
});
if (rows.length == 0) {
return null;
}
return Object.fromEntries(zip(columns, rows[0])) as any;
}
export async function verifyPassword(hashed_password: string, password: string): Promise<boolean> {
return new Scrypt().verify(hashed_password, password);
}