/api/client/status Endpoint 추가

This commit is contained in:
static
2024-12-29 23:56:35 +09:00
parent 95bad90f36
commit ee752494cd
3 changed files with 42 additions and 1 deletions

View File

@@ -1,4 +1,4 @@
import { and, eq, gt, lte } from "drizzle-orm";
import { and, eq, gt, lte, count } from "drizzle-orm";
import db from "./drizzle";
import { client, userClient, userClientChallenge } from "./schema";
@@ -25,6 +25,15 @@ export const getAllUserClients = async (userId: number) => {
return await db.select().from(userClient).where(eq(userClient.userId, userId)).execute();
};
export const countActiveUserClients = async (userId: number) => {
const userClients = await db
.select({ count: count() })
.from(userClient)
.where(and(eq(userClient.userId, userId), eq(userClient.state, "active")))
.execute();
return userClients[0]?.count ?? null;
};
export const getUserClient = async (userId: number, clientId: number) => {
const userClients = await db
.select()

View File

@@ -7,11 +7,13 @@ import {
getClientByPubKey,
createUserClient,
getAllUserClients,
countActiveUserClients,
getUserClient,
createUserClientChallenge,
getUserClientChallenge,
setUserClientStateToPending,
} from "$lib/server/db/client";
import { getActiveMek } from "$lib/server/db/mek";
import env from "$lib/server/loadenv";
export const getUserClientList = async (userId: number) => {
@@ -65,6 +67,22 @@ export const registerUserClient = async (userId: number, ip: string, pubKey: str
return await generateChallenge(userId, ip, clientId, pubKey);
};
export const getUserClientStatus = async (userId: number, clientId: number) => {
const userClient = await getUserClient(userId, clientId);
if (!userClient) {
error(500, "Invalid access token");
}
const activeMek = await getActiveMek(userId);
const activeUserClientCount = await countActiveUserClients(userId);
const isInitialMekNeeded = !activeMek && activeUserClientCount === 0;
return {
state: userClient.state,
isInitialMekNeeded,
};
};
export const verifyUserClient = async (userId: number, ip: string, answer: string) => {
const challenge = await getUserClientChallenge(answer, ip);
if (!challenge) {

View File

@@ -0,0 +1,14 @@
import { error, json } from "@sveltejs/kit";
import { authenticate } from "$lib/server/modules/auth";
import { getUserClientStatus } from "$lib/server/services/client";
import type { RequestHandler } from "@sveltejs/kit";
export const GET: RequestHandler = async ({ cookies }) => {
const { userId, clientId } = authenticate(cookies);
if (!clientId) {
error(403, "Forbidden");
}
const { state, isInitialMekNeeded } = await getUserClientStatus(userId, clientId);
return json({ id: clientId, state, isInitialMekNeeded });
};