New API + API Token Updates
This commit is contained in:
44
src/lib/api-auth.ts
Normal file
44
src/lib/api-auth.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { db } from "../db";
|
||||
import { apiTokens, users } from "../db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import crypto from "node:crypto";
|
||||
|
||||
export function hashToken(token: string): string {
|
||||
return crypto.createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
export async function validateApiToken(token: string) {
|
||||
const hashedToken = hashToken(token);
|
||||
|
||||
const result = await db
|
||||
.select({
|
||||
user: users,
|
||||
tokenData: apiTokens,
|
||||
})
|
||||
.from(apiTokens)
|
||||
.innerJoin(users, eq(apiTokens.userId, users.id))
|
||||
.where(eq(apiTokens.token, hashedToken))
|
||||
.get();
|
||||
|
||||
if (!result) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Update last used at
|
||||
await db
|
||||
.update(apiTokens)
|
||||
.set({ lastUsedAt: new Date() })
|
||||
.where(eq(apiTokens.id, result.tokenData.id));
|
||||
|
||||
const scopes = result.tokenData.scopes.split(",").map((s) => s.trim());
|
||||
|
||||
return {
|
||||
user: result.user,
|
||||
scopes,
|
||||
};
|
||||
}
|
||||
|
||||
export function generateApiToken(): string {
|
||||
const buffer = crypto.randomBytes(32);
|
||||
return "ch_" + buffer.toString("hex");
|
||||
}
|
||||
Reference in New Issue
Block a user