65 lines
1.9 KiB
TypeScript
65 lines
1.9 KiB
TypeScript
"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 } 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";
|
|
|
|
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_ID_CLIENT_ID!,
|
|
redirect_uri: `${process.env.PUBLIC_URL}/api/callback`,
|
|
scope: "profile:read",
|
|
response_type: "code",
|
|
code_challenge: challenge,
|
|
code_challenge_method: "S256",
|
|
state,
|
|
});
|
|
|
|
redirect(`${process.env.KOTOSOFT_ID_API_URL}/oauth/authorize?${params}`);
|
|
}
|
|
|
|
export async function logout() {
|
|
await deleteSession();
|
|
redirect("/");
|
|
}
|
|
|
|
export async function deleteUserAction(userId: string) {
|
|
await deleteUser(userId);
|
|
await deleteSession();
|
|
redirect("/");
|
|
}
|
|
|
|
export async function updateUserAction() {
|
|
const accessToken = await getAccessToken();
|
|
if (!accessToken) throw new Error("Not authenticated");
|
|
|
|
const kotosoftUser = await fetchKotosoftUser(accessToken);
|
|
|
|
const { getSessionUserId } = await import("@/lib/auth/session");
|
|
const userId = await getSessionUserId();
|
|
if (!userId) throw new Error("Not authenticated");
|
|
|
|
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")
|
|
}
|