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
import { sqlite } from "https://esm.town/v/std/sqlite?v=4";
import { sql, raw } from "https://esm.town/v/pomdtr/sql";
import {zip} from "npm:lodash-es"
import {Scrypt, generateId} 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,
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 user(id)
);`,
]);
}
export async function createUser(table: string, username: string, password: string) {
if (
username.length < 3
|| username.length > 31
|| !/^[a-z0-9_-]+$/.test(username)
) {
throw new Error("invalid username");
}
if (password.length < 6 || password.length > 255) {
throw new Error("invalid password");
}
const userId = generateId(15);
const hashedPassword = await new Scrypt().hash(password);
await sqlite.execute(
sql`INSERT INTO ${raw(table)} (id, username, hashed_password) VALUES (${userId}, ${username}, ${hashedPassword})`,
);
return userId;
}
export async function getUser(
table: string,
username: string,
): Promise<{ id: string; username: string; hashed_password: string } | null> {
const { rows, columns } = await sqlite.execute(sql`SELECT * from ${raw(table)} 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!
March 5, 2024