공개 키 등록 구현

This commit is contained in:
static
2024-12-28 01:05:31 +09:00
parent dec17ecba8
commit c00dbe7024
8 changed files with 82 additions and 4 deletions

View File

@@ -2,6 +2,14 @@ import { and, eq } from "drizzle-orm";
import db from "./drizzle";
import { client, userClient } from "./schema";
export const createClient = async (pubKey: string, userId: number) => {
await db.transaction(async (tx) => {
const insertRes = await tx.insert(client).values({ pubKey }).returning({ id: client.id });
const { id: clientId } = insertRes[0]!;
await tx.insert(userClient).values({ userId, clientId });
});
};
export const getClientByPubKey = async (pubKey: string) => {
const clients = await db.select().from(client).where(eq(client.pubKey, pubKey)).execute();
return clients[0] ?? null;

View File

@@ -1,3 +1,4 @@
import { error } from "@sveltejs/kit";
import jwt from "jsonwebtoken";
import env from "$lib/server/loadenv";
@@ -36,3 +37,22 @@ export const verifyToken = (token: string) => {
return TokenError.INVALID;
}
};
export const authenticate = (request: Request) => {
const accessToken = request.headers.get("Authorization");
if (!accessToken?.startsWith("Bearer ")) {
error(401, "Token required");
}
const tokenData = verifyToken(accessToken.slice(7));
if (tokenData === TokenError.EXPIRED) {
error(401, "Token expired");
} else if (tokenData === TokenError.INVALID || tokenData.type !== "access") {
error(401, "Invalid token");
}
return {
userId: tokenData.userId,
clientId: tokenData.clientId,
};
};

View File

@@ -0,0 +1,10 @@
import { error } from "@sveltejs/kit";
import { createClient, getClientByPubKey } from "$lib/server/db/client";
export const registerPubKey = async (userId: number, pubKey: string) => {
if (await getClientByPubKey(pubKey)) {
error(409, "Public key already registered");
}
await createClient(pubKey, userId);
};