78 lines
2.5 KiB
TypeScript
78 lines
2.5 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, 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_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(): Promise<ActionResult> {
|
|
return runAction(async () => {
|
|
await deleteSession();
|
|
redirect("/");
|
|
});
|
|
}
|
|
|
|
export async function deleteUserAction(): Promise<ActionResult> {
|
|
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<ActionResult> {
|
|
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");
|
|
});
|
|
} |