/ opencodehub / src / lib / auth-basic.ts
swadhinbiswas Fix: Add date validation in analysis.ts to prevent RangeError · 1/20/2026
a7662cd
44 lines · 1.2 KB
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
import { getDatabase, schema } from "@/db";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import bcrypt from "bcryptjs";
import { eq } from "drizzle-orm";

export async function validateBasicAuth(
  header: string
): Promise<string | null> {
  if (!header.startsWith("Basic ")) return null;

  const token = header.split(" ")[1];
  const decoded = Buffer.from(token, "base64").toString("utf-8");
  const [username, password] = decoded.split(":");

  if (!username || !password) return null;

  const db = getDatabase() as NodePgDatabase<typeof schema>;
  const user = await db.query.users.findFirst({
    where: eq(schema.users.username, username),
  });

  if (!user || !user.passwordHash) return null;

  const isValid = await bcrypt.compare(password, user.passwordHash);
  if (isValid) return user.id;

  // Check Personal Access Token
  const pat = await db.query.personalAccessTokens.findFirst({
    where: (tokens, { and, eq }) =>
      and(eq(tokens.userId, user.id), eq(tokens.token, password)),
  });

  if (pat) {
    // Update last used at
    await db
      .update(schema.personalAccessTokens)
      .set({ lastUsedAt: new Date() })
      .where(eq(schema.personalAccessTokens.id, pat.id));
    return user.id;
  }

  return null;
}