"use server"; import { generatePkce, generateState } from "@/lib/auth/pkce"; import { pkceConfig } from "@/lib/cookieConfig"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; import { deleteSession, getSessionUserId } from "@/lib/auth/session"; import { deleteUser, updateUser } from "./repository"; import { getAccessToken } from "@/lib/auth/tokens"; import { fetchKotosoftUser } from "@/lib/kotosoft/client"; import { revalidatePath } from "next/cache"; import { getCurrentUser, getUser } from "../user"; import { runAction } from "@/lib/run-action"; import { AppError, type ActionResult } from "@/lib/action-result"; export async function login() { const { verifier, challenge } = generatePkce(); const state = generateState(); const store = await cookies(); store.set("pkce_verifier", verifier, pkceConfig); store.set("oauth_state", state, pkceConfig); const params = new URLSearchParams({ client_id: process.env.KOTOSOFT_CLIENT_ID!, redirect_uri: `${process.env.PUBLIC_URL}/api/callback`, scope: "profile:read", response_type: "code", code_challenge: challenge, code_challenge_method: "S256", state, }); //Frontend public url, not api. And wtf I need to dubplicate it all redirect(`${process.env.KOTOSOFT_ID_API_PUBLIC_URL}/oauth/authorize?${params}`); } export async function logout(): Promise { return runAction(async () => { await deleteSession(); redirect("/"); }); } export async function deleteUserAction(): Promise { return runAction(async () => { const user = await getCurrentUser(); if (!user) throw new AppError("Not authenticated"); await deleteUser(user.id); await deleteSession(); redirect("/"); }); } export async function updateUserAction(): Promise { return runAction(async () => { const accessToken = await getAccessToken(); if (!accessToken) throw new AppError("Not authenticated"); const kotosoftUser = await fetchKotosoftUser(accessToken); const userId = await getSessionUserId(); if (!userId) throw new AppError("Not authenticated"); const user = await getUser(userId); if (user?.kotosoftId !== kotosoftUser.id) throw new AppError("Your session does not match your Kotosoft ID account"); await updateUser(userId, { email: kotosoftUser.email, firstName: kotosoftUser.first_name, secondName: kotosoftUser.second_name, sex: kotosoftUser.sex as "MALE" | "FEMALE", birthDate: kotosoftUser.birth_date, }); revalidatePath("/account"); }); }