Files
wireguard-ui/src/pages/api/auth/login.ts
T
2026-09-12 13:56:36 +01:00

96 lines
2.7 KiB
TypeScript

import type {
BUN_SQLITE_WGUI_SSO_LOGIN_CODES,
BUN_SQLITE_WGUI_USERS,
BunSQLiteTables,
} from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import loginUser from "@/src/functions/backend/auth/login-user";
import type { ApiReqParams, SSOAuth } from "@/src/types";
import { getCookie } from "@/src/utils/cookies";
import { decrypt } from "@/src/utils/crypt";
import EJSON from "@/src/utils/ejson";
import BunSQLite from "@moduletrace/bun-sqlite";
import type {
APIResponseObject,
BunextAPIRouteHandler,
} from "@moduletrace/bunext/types";
export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
req,
body,
}) => {
try {
const { sso_code } = body as ApiReqParams;
const sso_cookie = getCookie(req, AppData["SSOAuthCookieName"]);
if (!sso_cookie) {
throw new Error(`No SSO session found!`);
}
if (!sso_code) {
throw new Error(`No SSO code sent!`);
}
const decrypted_sso_json = await decrypt(sso_cookie);
const decrypted_sso_object = EJSON.parse(decrypted_sso_json) as SSOAuth;
const target_sso = (
await BunSQLite.select<
BUN_SQLITE_WGUI_SSO_LOGIN_CODES,
(typeof BunSQLiteTables)[number]
>({
table: "sso_login_codes",
query: {
query: {
code: {
value: sso_code,
},
},
},
})
).singleRes;
if (!target_sso?.code) {
throw new Error(`Invalid Code!`);
}
const now = Date.now();
const time_elapsed = now - Number(target_sso.updated_at);
const expirty_time = AppData["SSOCodeExpiryMinutes"] * 60 * 1000;
if (time_elapsed > expirty_time) {
throw new Error(`Code Expired. Please Login again.`);
}
const target_user = (
await BunSQLite.select<
BUN_SQLITE_WGUI_USERS,
(typeof BunSQLiteTables)[number]
>({
table: "users",
query: {
query: {
email: decrypted_sso_object.email
? { value: decrypted_sso_object.email }
: undefined,
},
},
})
).singleRes;
if (!target_user?.id) {
throw new Error(`This device wasn't used to get this SSO code`);
}
return await loginUser({
user_id: target_user.id,
});
} catch (error: any) {
return {
success: false,
msg: error.message,
};
}
};