You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
1.1 KiB
TypeScript
32 lines
1.1 KiB
TypeScript
import "server-only";
|
|
import { cache } from "react";
|
|
import { headers } from "next/headers";
|
|
import { redirect } from "next/navigation";
|
|
import { auth } from "@/lib/auth";
|
|
|
|
export type CurrentUser = {
|
|
id: string;
|
|
name: string;
|
|
username: string | null;
|
|
};
|
|
|
|
// `cache` React: session divalidasi sekali per request walau dipanggil beberapa komponen.
|
|
// Jangan diganti `"use cache"`: cache lintas request membuat user logout tetap dianggap login.
|
|
export const getCurrentUser = cache(async (): Promise<CurrentUser> => {
|
|
const session = await auth.api.getSession({ headers: await headers() });
|
|
if (!session) redirect("/login");
|
|
|
|
return {
|
|
id: session.user.id,
|
|
name: session.user.name,
|
|
username: session.user.username ?? null,
|
|
};
|
|
});
|
|
|
|
// Dipakai halaman login: session divalidasi (bukan cuma cek cookie) supaya
|
|
// cookie kedaluwarsa tidak memicu redirect bolak-balik dengan getCurrentUser().
|
|
export async function redirectIfLoggedIn(): Promise<void> {
|
|
const session = await auth.api.getSession({ headers: await headers() });
|
|
if (session) redirect("/");
|
|
}
|