1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
August 20, 2024