import type { BUN_SQLITE_WGUI_USERS, BunSQLiteTables, } from "@/db/types/db"; import loginUser from "@/src/functions/backend/auth/login-user"; import type { ApiReqParams } from "@/src/types"; import BunSQLite from "@moduletrace/bun-sqlite"; import type { APIResponseObject, BunextAPIRouteHandler, } from "@moduletrace/bunext/types"; export const handler: BunextAPIRouteHandler = async ({ body, }) => { try { const { login } = body as ApiReqParams; if (!login?.email_or_username) { throw new Error(`Please enter your email or username`); } if (!login?.password) { throw new Error(`Please enter your password`); } const target_user = ( await BunSQLite.select< BUN_SQLITE_WGUI_USERS, (typeof BunSQLiteTables)[number] >({ table: "users", query: { query: { email: { value: login.email_or_username, }, username: { value: login.email_or_username, }, }, searchOperator: "OR", }, }) )?.singleRes; if (!target_user?.id || !target_user.password) { throw new Error(`Invalid email or password`); } let password_matches = false; try { password_matches = await Bun.password.verify( login.password, target_user.password, ); } catch (error) { password_matches = false; } if (!password_matches) { throw new Error(`Invalid email or password`); } return await loginUser({ user_id: target_user.id, }); } catch (error: any) { return { success: false, msg: error.message, }; } };