refactor(db): migrate app pages and APIs from Prisma facade to Drizzle (5)
Co-authored-by: Cursor <[email protected]>
This commit is contained in:
1 parent
9aa4f331bf
commit
30b54e99e7
40 files changed
+1183
-784
No files matched your search
+30
-24
@@ -1,7 +1,8 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { and, eq, gt, isNull, or } from "drizzle-orm";
|
||||
import { personalTokenScope } from "@/lib/auth/personal-token-scope";
|
||||
import { databaseUserId } from "@/lib/auth/session-user";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { db, PersonalAccessTokens } from "@/lib/db";
|
||||
|
||||
/**
|
||||
* Bearer-token auth for the public REST API, backed by personal_access_tokens
|
||||
@@ -24,21 +25,28 @@ export async function bearerUserId(req: Request): Promise<number | null> {
|
||||
if (!raw) return null;
|
||||
|
||||
try {
|
||||
const row = await prisma.personalAccessTokens.findFirst({
|
||||
where: {
|
||||
token: hashToken(raw),
|
||||
OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }],
|
||||
},
|
||||
select: { id: true, tokenableId: true },
|
||||
});
|
||||
const [row] = await db
|
||||
.select({
|
||||
id: PersonalAccessTokens.id,
|
||||
tokenableId: PersonalAccessTokens.tokenableId,
|
||||
})
|
||||
.from(PersonalAccessTokens)
|
||||
.where(
|
||||
and(
|
||||
eq(PersonalAccessTokens.token, hashToken(raw)),
|
||||
or(
|
||||
isNull(PersonalAccessTokens.expiresAt),
|
||||
gt(PersonalAccessTokens.expiresAt, new Date()),
|
||||
),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (!row) return null;
|
||||
// Best-effort last-used stamp (don't fail the request if it errors).
|
||||
prisma.personalAccessTokens
|
||||
.update({
|
||||
where: { id: row.id },
|
||||
data: { lastUsedAt: new Date() },
|
||||
select: { id: true },
|
||||
})
|
||||
void db
|
||||
.update(PersonalAccessTokens)
|
||||
.set({ lastUsedAt: new Date() })
|
||||
.where(eq(PersonalAccessTokens.id, row.id))
|
||||
.catch(() => {});
|
||||
return databaseUserId(row.tokenableId);
|
||||
} catch {
|
||||
@@ -52,17 +60,15 @@ export async function issueToken(
|
||||
name = "api",
|
||||
): Promise<string | null> {
|
||||
const plaintext = randomBytes(32).toString("hex");
|
||||
const now = new Date();
|
||||
try {
|
||||
await prisma.personalAccessTokens.create({
|
||||
data: {
|
||||
...personalTokenScope(userId),
|
||||
name: name.slice(0, 100),
|
||||
token: hashToken(plaintext),
|
||||
abilities: '["*"]',
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
select: { id: true },
|
||||
await db.insert(PersonalAccessTokens).values({
|
||||
...personalTokenScope(userId),
|
||||
name: name.slice(0, 100),
|
||||
token: hashToken(plaintext),
|
||||
abilities: '["*"]',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
return plaintext;
|
||||
} catch {
|
||||
|
||||
Reference in new issue
Block a user