馃 distributed transcription service
thistle.dunkirk.sh
1import db from "../db/schema";
2
3const SESSION_DURATION = 7 * 24 * 60 * 60; // 7 days in seconds
4
5export type UserRole = "user" | "admin";
6
7export interface User {
8 id: number;
9 email: string;
10 name: string | null;
11 avatar: string;
12 created_at: number;
13 role: UserRole;
14 last_login: number | null;
15}
16
17export interface Session {
18 id: string;
19 user_id: number;
20 ip_address: string | null;
21 user_agent: string | null;
22 created_at: number;
23 expires_at: number;
24}
25
26export function createSession(
27 userId: number,
28 ipAddress?: string,
29 userAgent?: string,
30): string {
31 const sessionId = crypto.randomUUID();
32 const expiresAt = Math.floor(Date.now() / 1000) + SESSION_DURATION;
33
34 db.run(
35 "INSERT INTO sessions (id, user_id, ip_address, user_agent, expires_at) VALUES (?, ?, ?, ?, ?)",
36 [sessionId, userId, ipAddress ?? null, userAgent ?? null, expiresAt],
37 );
38
39 return sessionId;
40}
41
42export function getSession(sessionId: string): Session | null {
43 const now = Math.floor(Date.now() / 1000);
44
45 const session = db
46 .query<Session, [string, number]>(
47 "SELECT id, user_id, ip_address, user_agent, created_at, expires_at FROM sessions WHERE id = ? AND expires_at > ?",
48 )
49 .get(sessionId, now);
50
51 return session ?? null;
52}
53
54export function getUserBySession(sessionId: string): User | null {
55 const session = getSession(sessionId);
56 if (!session) return null;
57
58 const user = db
59 .query<User, [number]>(
60 "SELECT id, email, name, avatar, created_at, role, last_login FROM users WHERE id = ?",
61 )
62 .get(session.user_id);
63
64 return user ?? null;
65}
66
67export function getUserByEmail(email: string): User | null {
68 const user = db
69 .query<User, [string]>(
70 "SELECT id, email, name, avatar, created_at, role, last_login FROM users WHERE email = ?",
71 )
72 .get(email);
73
74 return user ?? null;
75}
76
77export function deleteSession(sessionId: string): void {
78 db.run("DELETE FROM sessions WHERE id = ?", [sessionId]);
79}
80
81export function cleanupExpiredSessions(): void {
82 const now = Math.floor(Date.now() / 1000);
83 db.run("DELETE FROM sessions WHERE expires_at <= ?", [now]);
84}
85
86export async function createUser(
87 email: string,
88 password: string,
89 name?: string,
90): Promise<User> {
91 // Generate deterministic avatar from email
92 const encoder = new TextEncoder();
93 const data = encoder.encode(email.toLowerCase());
94 const hashBuffer = await crypto.subtle.digest("SHA-256", data);
95 const hashArray = Array.from(new Uint8Array(hashBuffer));
96 const avatar = hashArray
97 .map((b) => b.toString(16).padStart(2, "0"))
98 .join("")
99 .substring(0, 16);
100
101 const result = db.run(
102 "INSERT INTO users (email, password_hash, name, avatar) VALUES (?, ?, ?, ?)",
103 [email, password, name ?? null, avatar],
104 );
105
106 const user = db
107 .query<User, [number]>(
108 "SELECT id, email, name, avatar, created_at, role, last_login FROM users WHERE id = ?",
109 )
110 .get(Number(result.lastInsertRowid));
111
112 if (!user) {
113 throw new Error("Failed to create user");
114 }
115
116 return user;
117}
118
119export async function authenticateUser(
120 email: string,
121 password: string,
122): Promise<User | null> {
123 const result = db
124 .query<
125 {
126 id: number;
127 email: string;
128 name: string | null;
129 avatar: string;
130 password_hash: string;
131 created_at: number;
132 role: UserRole;
133 last_login: number | null;
134 },
135 [string]
136 >(
137 "SELECT id, email, name, avatar, password_hash, created_at, role, last_login FROM users WHERE email = ?",
138 )
139 .get(email);
140
141 if (!result) {
142 // Dummy comparison to prevent timing-based account enumeration
143 const dummyHash = "0".repeat(64);
144 password === dummyHash;
145 return null;
146 }
147
148 if (password !== result.password_hash) return null;
149
150 // Update last_login
151 const now = Math.floor(Date.now() / 1000);
152 db.run("UPDATE users SET last_login = ? WHERE id = ?", [now, result.id]);
153
154 return {
155 id: result.id,
156 email: result.email,
157 name: result.name,
158 avatar: result.avatar,
159 created_at: result.created_at,
160 role: result.role,
161 last_login: now,
162 };
163}
164
165export function getUserSessionsForUser(userId: number): Session[] {
166 const now = Math.floor(Date.now() / 1000);
167
168 const sessions = db
169 .query<Session, [number, number]>(
170 "SELECT id, user_id, ip_address, user_agent, created_at, expires_at FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY created_at DESC",
171 )
172 .all(userId, now);
173
174 return sessions;
175}
176
177export function getSessionFromRequest(req: Request): string | null {
178 const cookie = req.headers.get("cookie");
179 if (!cookie) return null;
180
181 const match = cookie.match(/session=([^;]+)/);
182 return match?.[1] ?? null;
183}
184
185export function deleteUser(userId: number): void {
186 db.run("DELETE FROM users WHERE id = ?", [userId]);
187}
188
189export function updateUserEmail(userId: number, newEmail: string): void {
190 db.run("UPDATE users SET email = ? WHERE id = ?", [newEmail, userId]);
191}
192
193export function updateUserName(userId: number, newName: string): void {
194 db.run("UPDATE users SET name = ? WHERE id = ?", [newName, userId]);
195}
196
197export function updateUserAvatar(userId: number, avatar: string): void {
198 db.run("UPDATE users SET avatar = ? WHERE id = ?", [avatar, userId]);
199}
200
201export async function updateUserPassword(
202 userId: number,
203 newPassword: string,
204): Promise<void> {
205 db.run("UPDATE users SET password_hash = ? WHERE id = ?", [
206 newPassword,
207 userId,
208 ]);
209 db.run("DELETE FROM sessions WHERE user_id = ?", [userId]);
210}
211
212export function isUserAdmin(userId: number): boolean {
213 const result = db
214 .query<{ role: UserRole }, [number]>("SELECT role FROM users WHERE id = ?")
215 .get(userId);
216
217 return result?.role === "admin";
218}
219
220export function updateUserRole(userId: number, role: UserRole): void {
221 db.run("UPDATE users SET role = ? WHERE id = ?", [role, userId]);
222}
223
224export function getAllUsers(): Array<{
225 id: number;
226 email: string;
227 name: string | null;
228 avatar: string;
229 created_at: number;
230 role: UserRole;
231}> {
232 return db
233 .query<
234 {
235 id: number;
236 email: string;
237 name: string | null;
238 avatar: string;
239 created_at: number;
240 role: UserRole;
241 last_login: number | null;
242 },
243 []
244 >(
245 "SELECT id, email, name, avatar, created_at, role, last_login FROM users ORDER BY created_at DESC",
246 )
247 .all();
248}
249
250export function getAllTranscriptions(): Array<{
251 id: string;
252 user_id: number;
253 user_email: string;
254 user_name: string | null;
255 original_filename: string;
256 status: string;
257 created_at: number;
258 error_message: string | null;
259}> {
260 return db
261 .query<
262 {
263 id: string;
264 user_id: number;
265 user_email: string;
266 user_name: string | null;
267 original_filename: string;
268 status: string;
269 created_at: number;
270 error_message: string | null;
271 },
272 []
273 >(
274 `SELECT
275 t.id,
276 t.user_id,
277 u.email as user_email,
278 u.name as user_name,
279 t.original_filename,
280 t.status,
281 t.created_at,
282 t.error_message
283 FROM transcriptions t
284 LEFT JOIN users u ON t.user_id = u.id
285 ORDER BY t.created_at DESC`,
286 )
287 .all();
288}
289
290export function deleteTranscription(transcriptionId: string): void {
291 const transcription = db
292 .query<{ id: string; filename: string }, [string]>(
293 "SELECT id, filename FROM transcriptions WHERE id = ?",
294 )
295 .get(transcriptionId);
296
297 if (!transcription) {
298 throw new Error("Transcription not found");
299 }
300
301 // Delete database record
302 db.run("DELETE FROM transcriptions WHERE id = ?", [transcriptionId]);
303
304 // Delete files (audio file and transcript files)
305 try {
306 const audioPath = `./uploads/${transcription.filename}`;
307 const transcriptPath = `./transcripts/${transcriptionId}.txt`;
308 const vttPath = `./transcripts/${transcriptionId}.vtt`;
309
310 if (Bun.file(audioPath).size) {
311 Bun.write(audioPath, "").then(() => {
312 // File deleted by overwriting with empty content, then unlink
313 import("node:fs").then((fs) => {
314 fs.unlinkSync(audioPath);
315 });
316 });
317 }
318
319 if (Bun.file(transcriptPath).size) {
320 import("node:fs").then((fs) => {
321 fs.unlinkSync(transcriptPath);
322 });
323 }
324
325 if (Bun.file(vttPath).size) {
326 import("node:fs").then((fs) => {
327 fs.unlinkSync(vttPath);
328 });
329 }
330 } catch {
331 // Files might not exist, ignore errors
332 }
333}
334
335export function getSessionsForUser(userId: number): Session[] {
336 const now = Math.floor(Date.now() / 1000);
337 return db
338 .query<Session, [number, number]>(
339 "SELECT id, user_id, ip_address, user_agent, created_at, expires_at FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY created_at DESC",
340 )
341 .all(userId, now);
342}
343
344export function deleteSessionById(sessionId: string, userId: number): boolean {
345 const result = db.run("DELETE FROM sessions WHERE id = ? AND user_id = ?", [
346 sessionId,
347 userId,
348 ]);
349 return result.changes > 0;
350}
351
352export function deleteAllUserSessions(userId: number): void {
353 db.run("DELETE FROM sessions WHERE user_id = ?", [userId]);
354}
355
356export function updateUserEmailAddress(userId: number, newEmail: string): void {
357 db.run("UPDATE users SET email = ? WHERE id = ?", [newEmail, userId]);
358}
359
360export interface UserWithStats {
361 id: number;
362 email: string;
363 name: string | null;
364 avatar: string;
365 created_at: number;
366 role: UserRole;
367 last_login: number | null;
368 transcription_count: number;
369}
370
371export function getAllUsersWithStats(): UserWithStats[] {
372 return db
373 .query<UserWithStats, []>(
374 `SELECT
375 u.id,
376 u.email,
377 u.name,
378 u.avatar,
379 u.created_at,
380 u.role,
381 u.last_login,
382 COUNT(t.id) as transcription_count
383 FROM users u
384 LEFT JOIN transcriptions t ON u.id = t.user_id
385 GROUP BY u.id
386 ORDER BY u.created_at DESC`,
387 )
388 .all();
389}