Fix Middleware
Fix Layout sesuai role, dan superadmin bisa menambahkan menu ke user jika diperlukan Penambahan menu di user & role : menu access
This commit is contained in:
@@ -2163,18 +2163,20 @@ enum StatusPeminjaman {
|
||||
// ========================================= USER ========================================= //
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
username String @unique
|
||||
nomor String @unique
|
||||
role Role @relation(fields: [roleId], references: [id])
|
||||
roleId String @default("1")
|
||||
instansi String?
|
||||
UserSession UserSession? // Nama instansi (Puskesmas, Sekolah, dll)
|
||||
isActive Boolean @default(true)
|
||||
lastLogin DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
id String @id @default(cuid())
|
||||
username String @unique
|
||||
nomor String @unique
|
||||
role Role @relation(fields: [roleId], references: [id])
|
||||
roleId String @default("1")
|
||||
instansi String?
|
||||
UserSession UserSession? // Nama instansi (Puskesmas, Sekolah, dll)
|
||||
isActive Boolean @default(true)
|
||||
lastLogin DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
sessionInvalid Boolean @default(false)
|
||||
UserMenuAccess UserMenuAccess[]
|
||||
}
|
||||
|
||||
model Role {
|
||||
@@ -2210,6 +2212,18 @@ model UserSession {
|
||||
userId String @unique
|
||||
}
|
||||
|
||||
model UserMenuAccess {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
menuId String // ID menu (misal: "Landing Page", "Kesehatan")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
user User @relation(fields: [userId], references: [id])
|
||||
|
||||
@@unique([userId, menuId]) // Satu user tidak bisa punya akses menu yang sama dua kali
|
||||
}
|
||||
|
||||
// ========================================= DATA PENDIDIKAN ========================================= //
|
||||
model DataPendidikan {
|
||||
id String @id @default(cuid())
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { apiFetchOtpData, apiFetchVerifyOtp } from '@/app/api/auth/_lib/api_fetch_auth';
|
||||
import colors from '@/con/colors';
|
||||
import { Box, Button, Loader, Paper, PinInput, Stack, Text, Title } from '@mantine/core';
|
||||
import { Box, Button, Center, Loader, Paper, PinInput, Stack, Text, Title } from '@mantine/core';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
@@ -98,10 +98,10 @@ export default function Validasi() {
|
||||
router.replace('/waiting-room');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// ✅ Switch statement lebih clean
|
||||
let redirectPath: string;
|
||||
|
||||
|
||||
switch (roleId) {
|
||||
case 0:
|
||||
case 1:
|
||||
@@ -117,7 +117,7 @@ export default function Validasi() {
|
||||
redirectPath = '/admin';
|
||||
console.warn('Unknown roleId:', roleId);
|
||||
}
|
||||
|
||||
|
||||
console.log('Redirecting to:', redirectPath);
|
||||
router.replace(redirectPath);
|
||||
|
||||
@@ -151,6 +151,7 @@ export default function Validasi() {
|
||||
authStore.setUser({
|
||||
id: 'pending',
|
||||
name: username,
|
||||
roleId: 1,
|
||||
});
|
||||
cleanupStorage();
|
||||
router.replace('/waiting-room');
|
||||
@@ -219,14 +220,16 @@ export default function Validasi() {
|
||||
<Text c={colors['blue-button']} ta="center" fz="sm" fw="bold">
|
||||
Masukkan Kode Verifikasi
|
||||
</Text>
|
||||
<PinInput
|
||||
length={4}
|
||||
value={otp}
|
||||
onChange={setOtp}
|
||||
onComplete={handleVerify}
|
||||
inputMode="numeric"
|
||||
size="lg"
|
||||
/>
|
||||
<Center>
|
||||
<PinInput
|
||||
length={4}
|
||||
value={otp}
|
||||
onChange={setOtp}
|
||||
onComplete={handleVerify}
|
||||
inputMode="numeric"
|
||||
size="lg"
|
||||
/>
|
||||
</Center>
|
||||
</Box>
|
||||
|
||||
<Button
|
||||
|
||||
22
src/app/admin/(dashboard)/user&role/_com/dynamicNavbar.ts
Normal file
22
src/app/admin/(dashboard)/user&role/_com/dynamicNavbar.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
// src/app/admin/(dashboard)/user&role/_com/dynamicNavbar.ts
|
||||
import { navBar, role1, role2, role3 } from '@/app/admin/_com/list_PageAdmin';
|
||||
|
||||
export function getNavbar({
|
||||
roleId,
|
||||
menuIds,
|
||||
}: {
|
||||
roleId: number; // pastikan number
|
||||
menuIds?: string[] | null; // opsional
|
||||
}) {
|
||||
// Prioritas: menuIds > roleId
|
||||
if (menuIds && menuIds.length > 0) {
|
||||
return navBar.filter(section => menuIds.includes(section.id));
|
||||
}
|
||||
|
||||
// Fallback ke role-based
|
||||
if (roleId === 0) return navBar;
|
||||
if (roleId === 1) return role1;
|
||||
if (roleId === 2) return role2;
|
||||
if (roleId === 3) return role3;
|
||||
return [];
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
'use client'
|
||||
import colors from '@/con/colors';
|
||||
import { Stack, Tabs, TabsList, TabsPanel, TabsTab, Title } from '@mantine/core';
|
||||
import { IconForms, IconUser } from '@tabler/icons-react';
|
||||
import { IconBrush, IconForms, IconUser } from '@tabler/icons-react';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
|
||||
@@ -23,6 +23,12 @@ function LayoutTabs({ children }: { children: React.ReactNode }) {
|
||||
href: "/admin/user&role/role",
|
||||
icon: <IconForms size={18} stroke={1.8} />,
|
||||
},
|
||||
{
|
||||
label: "Menu Access",
|
||||
value: "menu-access",
|
||||
href: "/admin/user&role/menu-access",
|
||||
icon: <IconBrush size={18} stroke={1.8} />,
|
||||
}
|
||||
];
|
||||
|
||||
const currentTab = tabs.find(tab => tab.href === pathname);
|
||||
|
||||
124
src/app/admin/(dashboard)/user&role/menu-access/page.tsx
Normal file
124
src/app/admin/(dashboard)/user&role/menu-access/page.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
// src/app/admin/user&role/menu-access/page.tsx
|
||||
|
||||
'use client'
|
||||
|
||||
import { navBar } from '@/app/admin/_com/list_PageAdmin'
|
||||
import { Button, Checkbox, Group, Paper, Select, Stack, Text, Title } from '@mantine/core'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useProxy } from 'valtio/utils'
|
||||
import user from '../../_state/user/user-state'
|
||||
|
||||
|
||||
// ✅ Helper: ekstrak semua menu ID dari struktur navBar
|
||||
const extractMenuIds = (navSections: typeof navBar) => {
|
||||
return navSections.map(section => ({
|
||||
value: section.id, // "Landing Page", "Kesehatan", dll
|
||||
label: section.name // "Landing Page", "Kesehatan", dll
|
||||
}));
|
||||
};
|
||||
|
||||
function MenuAccessPage() {
|
||||
const stateUser = useProxy(user.userState)
|
||||
const [selectedUserId, setSelectedUserId] = useState<string | null>(null)
|
||||
const [userMenus, setUserMenus] = useState<string[]>([])
|
||||
|
||||
// ✅ Gunakan helper untuk ekstrak menu
|
||||
const availableMenus = extractMenuIds(navBar);
|
||||
|
||||
// Ambil data menu akses user
|
||||
const loadUserMenuAccess = async () => {
|
||||
if (!selectedUserId) return
|
||||
|
||||
try {
|
||||
// ✅ Perbaiki URL: gunakan query string bukan dynamic route
|
||||
const res = await fetch(`/api/admin/user-menu-access?userId=${selectedUserId}`)
|
||||
const data = await res.json()
|
||||
|
||||
if (data.success) {
|
||||
setUserMenus(data.menuIds || [])
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Gagal memuat menu akses:', error)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedUserId) {
|
||||
loadUserMenuAccess()
|
||||
}
|
||||
}, [selectedUserId])
|
||||
|
||||
const handleToggleMenu = (menuId: string) => {
|
||||
setUserMenus(prev =>
|
||||
prev.includes(menuId)
|
||||
? prev.filter(id => id !== menuId)
|
||||
: [...prev, menuId]
|
||||
)
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!selectedUserId) return
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/admin/user-menu-access', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ userId: selectedUserId, menuIds: userMenus }),
|
||||
})
|
||||
|
||||
const data = await res.json()
|
||||
if (data.success) {
|
||||
alert('Menu akses berhasil disimpan')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Gagal menyimpan menu akses:', error)
|
||||
alert('Terjadi kesalahan')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
<Title order={2}>Tampilan Menu</Title>
|
||||
<Paper p="xl" shadow="md" radius="md">
|
||||
<Stack gap="lg">
|
||||
<Group>
|
||||
<Text fw={500}>Pilih User:</Text>
|
||||
<Select
|
||||
placeholder="Pilih user"
|
||||
data={stateUser.findMany.data.map(u => ({
|
||||
value: u.id,
|
||||
label: `${u.username} (${u.nomor})`,
|
||||
}))}
|
||||
value={selectedUserId}
|
||||
onChange={setSelectedUserId}
|
||||
w={300}
|
||||
/>
|
||||
</Group>
|
||||
|
||||
{selectedUserId && (
|
||||
<>
|
||||
<Text fw={500}>Menu yang Bisa Diakses:</Text>
|
||||
<Stack>
|
||||
{availableMenus.map(menu => (
|
||||
<Checkbox
|
||||
key={menu.value}
|
||||
label={menu.label}
|
||||
checked={userMenus.includes(menu.value)}
|
||||
onChange={() => handleToggleMenu(menu.value)}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
|
||||
<Button onClick={handleSave} mt="md">
|
||||
Simpan Perubahan
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
export default MenuAccessPage
|
||||
@@ -95,7 +95,24 @@ function ListUser({ search }: { search: string }) {
|
||||
});
|
||||
|
||||
if (success) {
|
||||
// Reload data setelah berhasil update
|
||||
// Cek apakah role berubah
|
||||
const res = await fetch('/api/user/updt', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
id: userId,
|
||||
roleId: newRoleId,
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if (data.roleChanged) {
|
||||
// Tampilkan notifikasi
|
||||
alert(`User ${username} akan logout otomatis!`);
|
||||
}
|
||||
|
||||
stateUser.findMany.load(page, 10, search);
|
||||
}
|
||||
|
||||
@@ -114,7 +131,9 @@ function ListUser({ search }: { search: string }) {
|
||||
}
|
||||
};
|
||||
|
||||
const filteredData = data || [];
|
||||
const filteredData = (data || []).filter(
|
||||
(item) => item.roleId !== "0" // asumsikan id role SUPERADMIN = "0"
|
||||
);
|
||||
|
||||
if (loading || !data) {
|
||||
return (
|
||||
@@ -158,10 +177,12 @@ function ListUser({ search }: { search: string }) {
|
||||
<TableTd style={{ width: '20%' }}>
|
||||
<Select
|
||||
placeholder="Pilih role"
|
||||
data={stateRole.findMany.data.map((r) => ({
|
||||
label: r.name,
|
||||
value: r.id,
|
||||
}))}
|
||||
data={stateRole.findMany.data
|
||||
.filter(r => r.id !== "0") // ❌ Sembunyikan SUPERADMIN
|
||||
.map(r => ({
|
||||
label: r.name,
|
||||
value: r.id,
|
||||
}))}
|
||||
value={item.roleId}
|
||||
onChange={(val) => {
|
||||
if (!val) return;
|
||||
|
||||
@@ -392,6 +392,11 @@ export const navBar = [
|
||||
id: "Role",
|
||||
name: "Role",
|
||||
path: "/admin/user&role/role"
|
||||
},
|
||||
{
|
||||
id: "Menu Access",
|
||||
name: "Menu Access",
|
||||
path: "/admin/user&role/menu-access"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -785,4 +790,4 @@ export const role3 = [
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
]
|
||||
@@ -1,263 +1,3 @@
|
||||
// /* eslint-disable react-hooks/exhaustive-deps */
|
||||
// 'use client'
|
||||
|
||||
// import colors from "@/con/colors";
|
||||
// import {
|
||||
// ActionIcon,
|
||||
// AppShell,
|
||||
// AppShellHeader,
|
||||
// AppShellMain,
|
||||
// AppShellNavbar,
|
||||
// Burger,
|
||||
// Flex,
|
||||
// Group,
|
||||
// Image,
|
||||
// NavLink,
|
||||
// ScrollArea,
|
||||
// Text,
|
||||
// Tooltip,
|
||||
// rem
|
||||
// } from "@mantine/core";
|
||||
// import { useDisclosure } from "@mantine/hooks";
|
||||
// import {
|
||||
// IconChevronLeft,
|
||||
// IconChevronRight,
|
||||
// IconLogout2
|
||||
// } from "@tabler/icons-react";
|
||||
// import _ from "lodash";
|
||||
// import Link from "next/link";
|
||||
// import { useRouter, useSelectedLayoutSegments } from "next/navigation";
|
||||
// import { navBar } from "./_com/list_PageAdmin";
|
||||
|
||||
// export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
// const [opened, { toggle }] = useDisclosure();
|
||||
// const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true);
|
||||
// const router = useRouter();
|
||||
// const segments = useSelectedLayoutSegments().map((s) => _.lowerCase(s));
|
||||
|
||||
// return (
|
||||
// <AppShell
|
||||
// suppressHydrationWarning
|
||||
// header={{ height: 64 }}
|
||||
// navbar={{
|
||||
// width: { base: 260, sm: 280, lg: 300 },
|
||||
// breakpoint: 'sm',
|
||||
// collapsed: {
|
||||
// mobile: !opened,
|
||||
// desktop: !desktopOpened,
|
||||
// },
|
||||
// }}
|
||||
// padding="md"
|
||||
// >
|
||||
// <AppShellHeader
|
||||
// style={{
|
||||
// background: "linear-gradient(90deg, #ffffff, #f9fbff)",
|
||||
// borderBottom: `1px solid ${colors["blue-button"]}20`,
|
||||
// padding: '0 16px',
|
||||
// }}
|
||||
// px={{ base: 'sm', sm: 'md' }}
|
||||
// py={{ base: 'xs', sm: 'sm' }}
|
||||
// >
|
||||
// <Group w="100%" h="100%" justify="space-between" wrap="nowrap">
|
||||
// <Flex align="center" gap="sm">
|
||||
// <Image
|
||||
// src="/assets/images/darmasaba-icon.png"
|
||||
// alt="Logo Darmasaba"
|
||||
// w={{ base: 32, sm: 40 }}
|
||||
// h={{ base: 32, sm: 40 }}
|
||||
// radius="md"
|
||||
// loading="lazy"
|
||||
// style={{
|
||||
// minWidth: '32px',
|
||||
// height: 'auto',
|
||||
// }}
|
||||
// />
|
||||
// <Text
|
||||
// fw={700}
|
||||
// c={colors["blue-button"]}
|
||||
// fz={{ base: 'md', sm: 'xl' }}
|
||||
// >
|
||||
// Admin Darmasaba
|
||||
// </Text>
|
||||
// </Flex>
|
||||
|
||||
// <Group gap="xs">
|
||||
// {!desktopOpened && (
|
||||
// <Tooltip label="Buka Navigasi" position="bottom" withArrow>
|
||||
// <ActionIcon
|
||||
// variant="light"
|
||||
// radius="xl"
|
||||
// size="lg"
|
||||
// onClick={toggleDesktop}
|
||||
// color={colors["blue-button"]}
|
||||
// >
|
||||
// <IconChevronRight />
|
||||
// </ActionIcon>
|
||||
// </Tooltip>
|
||||
// )}
|
||||
|
||||
// <Burger
|
||||
// opened={opened}
|
||||
// onClick={toggle}
|
||||
// hiddenFrom="sm"
|
||||
// size="md"
|
||||
// color={colors["blue-button"]}
|
||||
// mr="xs"
|
||||
// />
|
||||
|
||||
// <Tooltip label="Kembali ke Website Desa" position="bottom" withArrow>
|
||||
// <ActionIcon
|
||||
// onClick={() => {
|
||||
// router.push("/darmasaba");
|
||||
// }}
|
||||
// color={colors["blue-button"]}
|
||||
// radius="xl"
|
||||
// size="lg"
|
||||
// variant="gradient"
|
||||
// gradient={{ from: colors["blue-button"], to: "#228be6" }}
|
||||
// >
|
||||
// <Image
|
||||
// src="/assets/images/darmasaba-icon.png"
|
||||
// alt="Logo Darmasaba"
|
||||
// w={20}
|
||||
// h={20}
|
||||
// radius="md"
|
||||
// loading="lazy"
|
||||
// style={{
|
||||
// minWidth: '20px',
|
||||
// height: 'auto',
|
||||
// }}
|
||||
// />
|
||||
// </ActionIcon>
|
||||
// </Tooltip>
|
||||
// <Tooltip label="Keluar" position="bottom" withArrow>
|
||||
// <ActionIcon
|
||||
// onClick={() => {
|
||||
// router.push("/darmasaba");
|
||||
// }}
|
||||
// color={colors["blue-button"]}
|
||||
// radius="xl"
|
||||
// size="lg"
|
||||
// variant="gradient"
|
||||
// gradient={{ from: colors["blue-button"], to: "#228be6" }}
|
||||
// >
|
||||
// <IconLogout2 size={22} />
|
||||
// </ActionIcon>
|
||||
// </Tooltip>
|
||||
// </Group>
|
||||
// </Group>
|
||||
// </AppShellHeader>
|
||||
|
||||
// <AppShellNavbar
|
||||
// component={ScrollArea}
|
||||
// style={{
|
||||
// background: "#ffffff",
|
||||
// borderRight: `1px solid ${colors["blue-button"]}20`,
|
||||
// }}
|
||||
// p={{ base: 'xs', sm: 'sm' }}
|
||||
// >
|
||||
// <AppShell.Section p="sm">
|
||||
// {navBar.map((v, k) => {
|
||||
// const isParentActive = segments.includes(_.lowerCase(v.name));
|
||||
|
||||
// return (
|
||||
// <NavLink
|
||||
// key={k}
|
||||
// defaultOpened={isParentActive}
|
||||
// c={isParentActive ? colors["blue-button"] : "gray"}
|
||||
// label={
|
||||
// <Text fw={isParentActive ? 600 : 400} fz="sm">
|
||||
// {v.name}
|
||||
// </Text>
|
||||
// }
|
||||
// style={{
|
||||
// borderRadius: rem(10),
|
||||
// marginBottom: rem(4),
|
||||
// transition: "background 150ms ease",
|
||||
// }}
|
||||
// styles={{
|
||||
// root: {
|
||||
// '&:hover': {
|
||||
// backgroundColor: 'rgba(25, 113, 194, 0.05)',
|
||||
// },
|
||||
// },
|
||||
// }}
|
||||
// variant="light"
|
||||
// active={isParentActive}
|
||||
// >
|
||||
// {v.children.map((child, key) => {
|
||||
// const isChildActive = segments.includes(
|
||||
// _.lowerCase(child.name)
|
||||
// );
|
||||
|
||||
// return (
|
||||
// <NavLink
|
||||
// key={key}
|
||||
// href={child.path}
|
||||
// c={isChildActive ? colors["blue-button"] : "gray"}
|
||||
// label={
|
||||
// <Text fw={isChildActive ? 600 : 400} fz="sm">
|
||||
// {child.name}
|
||||
// </Text>
|
||||
// }
|
||||
// styles={{
|
||||
// root: {
|
||||
// borderRadius: rem(8),
|
||||
// marginBottom: rem(2),
|
||||
// transition: 'background 150ms ease',
|
||||
// padding: '6px 12px',
|
||||
// '&:hover': {
|
||||
// backgroundColor: isChildActive ? 'rgba(25, 113, 194, 0.15)' : 'rgba(25, 113, 194, 0.05)',
|
||||
// },
|
||||
// ...(isChildActive && {
|
||||
// backgroundColor: 'rgba(25, 113, 194, 0.1)',
|
||||
// }),
|
||||
// },
|
||||
// }}
|
||||
// active={isChildActive}
|
||||
// component={Link}
|
||||
// />
|
||||
// );
|
||||
// })}
|
||||
// </NavLink>
|
||||
// );
|
||||
// })}
|
||||
// </AppShell.Section>
|
||||
|
||||
// <AppShell.Section py="md">
|
||||
// <Group justify="end" pr="sm">
|
||||
// <Tooltip
|
||||
// label={desktopOpened ? "Tutup Navigasi" : "Buka Navigasi"}
|
||||
// position="top"
|
||||
// withArrow
|
||||
// >
|
||||
// <ActionIcon
|
||||
// variant="light"
|
||||
// radius="xl"
|
||||
// size="lg"
|
||||
// onClick={toggleDesktop}
|
||||
// color={colors["blue-button"]}
|
||||
// >
|
||||
// <IconChevronLeft />
|
||||
// </ActionIcon>
|
||||
// </Tooltip>
|
||||
// </Group>
|
||||
// </AppShell.Section>
|
||||
// </AppShellNavbar>
|
||||
|
||||
// <AppShellMain
|
||||
// style={{
|
||||
// background: "linear-gradient(180deg, #fdfdfd, #f6f9fc)",
|
||||
// minHeight: "100vh",
|
||||
// }}
|
||||
// >
|
||||
// {children}
|
||||
// </AppShellMain>
|
||||
// </AppShell>
|
||||
// );
|
||||
// }
|
||||
|
||||
|
||||
'use client'
|
||||
|
||||
import colors from "@/con/colors";
|
||||
@@ -290,26 +30,25 @@ import _ from "lodash";
|
||||
import Link from "next/link";
|
||||
import { useRouter, useSelectedLayoutSegments } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { navigationByRole } from "./_com/navigationByRole";
|
||||
import { useSnapshot } from "valtio";
|
||||
import { toast } from "react-toastify";
|
||||
import { getNavbar } from "./(dashboard)/user&role/_com/dynamicNavbar";
|
||||
|
||||
export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
const [opened, { toggle }] = useDisclosure();
|
||||
const [opened, { toggle }] = useDisclosure();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [desktopOpened, { toggle: toggleDesktop }] = useDisclosure(true);
|
||||
const router = useRouter();
|
||||
const segments = useSelectedLayoutSegments().map((s) => _.lowerCase(s));
|
||||
|
||||
const { user } = useSnapshot(authStore);
|
||||
|
||||
console.log("Current user in store:", user);
|
||||
|
||||
// ✅ Fetch user dari backend jika belum ada di store
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
useEffect(() => {
|
||||
if (authStore.user) {
|
||||
setLoading(false);
|
||||
return;
|
||||
} // Sudah ada → jangan fetch
|
||||
}
|
||||
|
||||
const fetchUser = async () => {
|
||||
try {
|
||||
@@ -317,10 +56,19 @@ export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
const data = await res.json();
|
||||
|
||||
if (data.user) {
|
||||
const menuRes = await fetch(`/api/admin/user-menu-access?userId=${data.user.id}`);
|
||||
const menuData = await menuRes.json();
|
||||
|
||||
// ✅ Clone ke array mutable
|
||||
const menuIds = menuData.success && Array.isArray(menuData.menuIds)
|
||||
? [...menuData.menuIds] // Converts readonly array to mutable
|
||||
: null;
|
||||
|
||||
authStore.setUser({
|
||||
id: data.user.id,
|
||||
name: data.user.name,
|
||||
roleId: Number(data.user.roleId),
|
||||
menuIds,
|
||||
});
|
||||
} else {
|
||||
authStore.setUser(null);
|
||||
@@ -336,94 +84,7 @@ export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
};
|
||||
|
||||
fetchUser();
|
||||
}, [user, router]); // ✅ Sekarang 'user' terdefinisi
|
||||
|
||||
// ✅ Polling untuk cek perubahan role setiap 30 detik
|
||||
// Di layout.tsx - useEffect polling
|
||||
useEffect(() => {
|
||||
if (!user?.id) return;
|
||||
|
||||
const checkRoleUpdate = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/auth/me');
|
||||
const data = await res.json();
|
||||
|
||||
// ✅ Session tidak valid (sudah dihapus karena role berubah)
|
||||
if (!data.success || !data.user) {
|
||||
console.log('⚠️ Session tidak valid, logout...');
|
||||
authStore.setUser(null);
|
||||
|
||||
// Clear cookie manual (backup)
|
||||
document.cookie = `${process.env.NEXT_PUBLIC_SESSION_KEY}=; Max-Age=0; path=/;`;
|
||||
|
||||
toast.info('Role Anda telah diubah. Silakan login kembali.', {
|
||||
autoClose: 5000,
|
||||
});
|
||||
|
||||
router.push('/login');
|
||||
return;
|
||||
}
|
||||
|
||||
// Cek perubahan roleId (seharusnya tidak sampai sini jika session dihapus)
|
||||
const currentRoleId = Number(data.user.roleId);
|
||||
|
||||
if (currentRoleId !== user.roleId) {
|
||||
console.log('🔄 Role berubah! Dari', user.roleId, 'ke', currentRoleId);
|
||||
|
||||
// Update store
|
||||
authStore.setUser({
|
||||
id: data.user.id,
|
||||
name: data.user.name || data.user.username,
|
||||
roleId: currentRoleId,
|
||||
});
|
||||
|
||||
// Redirect ke halaman default role baru
|
||||
let redirectPath = '/admin';
|
||||
|
||||
switch (currentRoleId) {
|
||||
case 0:
|
||||
case 1:
|
||||
redirectPath = '/admin/landing-page/profil/program-inovasi';
|
||||
break;
|
||||
case 2:
|
||||
redirectPath = '/admin/kesehatan/posyandu';
|
||||
break;
|
||||
case 3:
|
||||
redirectPath = '/admin/pendidikan/info-sekolah/jenjang-pendidikan';
|
||||
break;
|
||||
}
|
||||
|
||||
toast.info('Role Anda telah diubah. Mengalihkan halaman...', {
|
||||
autoClose: 5000,
|
||||
});
|
||||
|
||||
router.push(redirectPath);
|
||||
|
||||
// Reload untuk clear semua state
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 500);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Error checking role update:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// ✅ Polling setiap 10 detik (lebih responsif dari 30 detik)
|
||||
const interval = setInterval(checkRoleUpdate, 10000);
|
||||
|
||||
// Juga cek saat window focus (user kembali ke tab)
|
||||
const handleFocus = () => {
|
||||
checkRoleUpdate();
|
||||
};
|
||||
|
||||
window.addEventListener('focus', handleFocus);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
window.removeEventListener('focus', handleFocus);
|
||||
};
|
||||
}, [user, router]);
|
||||
}, [router]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -438,8 +99,8 @@ useEffect(() => {
|
||||
}
|
||||
|
||||
// ✅ Ambil menu berdasarkan roleId
|
||||
const currentNav = user?.roleId !== undefined
|
||||
? (navigationByRole[user.roleId as keyof typeof navigationByRole] || [])
|
||||
const currentNav = authStore.user
|
||||
? getNavbar({ roleId: authStore.user.roleId, menuIds: authStore.user.menuIds })
|
||||
: [];
|
||||
|
||||
const handleLogout = () => {
|
||||
@@ -667,4 +328,3 @@ useEffect(() => {
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,127 @@
|
||||
// /* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
// import prisma from "@/lib/prisma";
|
||||
// import { Context } from "elysia";
|
||||
|
||||
// export default async function userUpdate(context: Context) {
|
||||
// try {
|
||||
// const { id, isActive, roleId } = await context.body as {
|
||||
// id: string,
|
||||
// isActive?: boolean,
|
||||
// roleId?: string
|
||||
// };
|
||||
|
||||
// if (!id) {
|
||||
// return {
|
||||
// success: false,
|
||||
// message: "ID user wajib ada",
|
||||
// };
|
||||
// }
|
||||
|
||||
// // Optional: cek apakah roleId valid
|
||||
// if (roleId) {
|
||||
// const cekRole = await prisma.role.findUnique({
|
||||
// where: { id: roleId }
|
||||
// });
|
||||
|
||||
// if (!cekRole) {
|
||||
// return {
|
||||
// success: false,
|
||||
// message: "Role tidak ditemukan",
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
// // ✅ CEK: Apakah roleId berubah?
|
||||
// let isRoleChanged = false;
|
||||
// let oldRoleId: string | null = null;
|
||||
|
||||
// if (roleId) {
|
||||
// const currentUser = await prisma.user.findUnique({
|
||||
// where: { id },
|
||||
// select: {
|
||||
// roleId: true,
|
||||
// username: true,
|
||||
// }
|
||||
// });
|
||||
|
||||
// if (currentUser && currentUser.roleId !== roleId) {
|
||||
// isRoleChanged = true;
|
||||
// oldRoleId = currentUser.roleId;
|
||||
// console.log(`🔄 Role berubah untuk ${currentUser.username}: ${oldRoleId} → ${roleId}`);
|
||||
// }
|
||||
// }
|
||||
|
||||
// // Update user
|
||||
// const updatedUser = await prisma.user.update({
|
||||
// where: { id },
|
||||
// data: {
|
||||
// ...(isActive !== undefined && { isActive }),
|
||||
// ...(roleId && { roleId }),
|
||||
// },
|
||||
// select: {
|
||||
// id: true,
|
||||
// username: true,
|
||||
// nomor: true,
|
||||
// isActive: true,
|
||||
// roleId: true,
|
||||
// updatedAt: true,
|
||||
// role: {
|
||||
// select: {
|
||||
// id: true,
|
||||
// name: true,
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
|
||||
// // ✅ FORCE LOGOUT: Hapus UserSession jika role berubah
|
||||
// if (isRoleChanged) {
|
||||
// try {
|
||||
// const deletedSessions = await prisma.userSession.deleteMany({
|
||||
// where: { userId: id }
|
||||
// });
|
||||
|
||||
// console.log(`🔒 Force logout user ${updatedUser.username} (${id})`);
|
||||
// console.log(` Deleted ${deletedSessions.count} session(s)`);
|
||||
// console.log(` Role: ${oldRoleId} → ${roleId}`);
|
||||
// } catch (sessionError: any) {
|
||||
// // Jika UserSession tidak ditemukan (user belum pernah login), skip error
|
||||
// if (sessionError.code !== 'P2025') {
|
||||
// console.error("⚠️ Error menghapus session:", sessionError);
|
||||
// } else {
|
||||
// console.log(`ℹ️ User ${updatedUser.username} belum pernah login`);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// // ✅ Response dengan info tambahan
|
||||
// return {
|
||||
// success: true,
|
||||
// message: isRoleChanged
|
||||
// ? `User berhasil diupdate. ${updatedUser.username} akan logout otomatis.`
|
||||
// : "User berhasil diupdate",
|
||||
// data: updatedUser,
|
||||
// roleChanged: isRoleChanged, // Info untuk frontend
|
||||
// oldRoleId: oldRoleId,
|
||||
// newRoleId: roleId,
|
||||
// };
|
||||
|
||||
// } catch (e: any) {
|
||||
// console.error("❌ Error update user:", e);
|
||||
// return {
|
||||
// success: false,
|
||||
// message: "Gagal mengupdate user: " + (e.message || "Unknown error"),
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Context } from "elysia";
|
||||
|
||||
|
||||
// API update user (Elysia atau Next.js API Route)
|
||||
export default async function userUpdate(context: Context) {
|
||||
try {
|
||||
const { id, isActive, roleId } = await context.body as {
|
||||
@@ -17,12 +137,9 @@ export default async function userUpdate(context: Context) {
|
||||
};
|
||||
}
|
||||
|
||||
// Optional: cek apakah roleId valid
|
||||
// Cek apakah roleId valid
|
||||
if (roleId) {
|
||||
const cekRole = await prisma.role.findUnique({
|
||||
where: { id: roleId }
|
||||
});
|
||||
|
||||
const cekRole = await prisma.role.findUnique({ where: { id: roleId } });
|
||||
if (!cekRole) {
|
||||
return {
|
||||
success: false,
|
||||
@@ -31,32 +148,24 @@ export default async function userUpdate(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ CEK: Apakah roleId berubah?
|
||||
// Deteksi perubahan role
|
||||
let isRoleChanged = false;
|
||||
let oldRoleId: string | null = null;
|
||||
|
||||
if (roleId) {
|
||||
const currentUser = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
roleId: true,
|
||||
username: true,
|
||||
}
|
||||
select: { roleId: true }
|
||||
});
|
||||
|
||||
if (currentUser && currentUser.roleId !== roleId) {
|
||||
isRoleChanged = true;
|
||||
oldRoleId = currentUser.roleId;
|
||||
console.log(`🔄 Role berubah untuk ${currentUser.username}: ${oldRoleId} → ${roleId}`);
|
||||
}
|
||||
isRoleChanged = currentUser?.roleId !== roleId;
|
||||
}
|
||||
|
||||
// Update user
|
||||
// ✅ UPDATE USER + INVALIDATE SESSION
|
||||
const updatedUser = await prisma.user.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(isActive !== undefined && { isActive }),
|
||||
...(roleId && { roleId }),
|
||||
// Force logout: set sessionInvalid = true
|
||||
...(isRoleChanged && { sessionInvalid: true }),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
@@ -64,48 +173,31 @@ export default async function userUpdate(context: Context) {
|
||||
nomor: true,
|
||||
isActive: true,
|
||||
roleId: true,
|
||||
updatedAt: true,
|
||||
role: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
}
|
||||
}
|
||||
role: { select: { name: true } }
|
||||
}
|
||||
});
|
||||
|
||||
// ✅ FORCE LOGOUT: Hapus UserSession jika role berubah
|
||||
// ✅ Reset sessionInvalid setelah 5 detik (opsional)
|
||||
if (isRoleChanged) {
|
||||
try {
|
||||
const deletedSessions = await prisma.userSession.deleteMany({
|
||||
where: { userId: id }
|
||||
});
|
||||
|
||||
console.log(`🔒 Force logout user ${updatedUser.username} (${id})`);
|
||||
console.log(` Deleted ${deletedSessions.count} session(s)`);
|
||||
console.log(` Role: ${oldRoleId} → ${roleId}`);
|
||||
} catch (sessionError: any) {
|
||||
// Jika UserSession tidak ditemukan (user belum pernah login), skip error
|
||||
if (sessionError.code !== 'P2025') {
|
||||
console.error("⚠️ Error menghapus session:", sessionError);
|
||||
} else {
|
||||
console.log(`ℹ️ User ${updatedUser.username} belum pernah login`);
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
await prisma.user.update({
|
||||
where: { id },
|
||||
data: { sessionInvalid: false }
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Gagal reset sessionInvalid:', e);
|
||||
}
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// ✅ Response dengan info tambahan
|
||||
return {
|
||||
success: true,
|
||||
message: isRoleChanged
|
||||
? `User berhasil diupdate. ${updatedUser.username} akan logout otomatis.`
|
||||
: "User berhasil diupdate",
|
||||
data: updatedUser,
|
||||
roleChanged: isRoleChanged, // Info untuk frontend
|
||||
oldRoleId: oldRoleId,
|
||||
newRoleId: roleId,
|
||||
};
|
||||
|
||||
} catch (e: any) {
|
||||
console.error("❌ Error update user:", e);
|
||||
return {
|
||||
|
||||
65
src/app/api/admin/user-menu-access/route.ts
Normal file
65
src/app/api/admin/user-menu-access/route.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
// src/app/api/admin/user-menu-access/route.ts
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import prisma from '@/lib/prisma'
|
||||
|
||||
// ❌ HAPUS { params } karena tidak dipakai
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const userId = searchParams.get('userId')
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'User ID diperlukan' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const menuAccess = await prisma.userMenuAccess.findMany({
|
||||
where: { userId },
|
||||
select: { menuId: true },
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
menuIds: menuAccess.map(m => m.menuId),
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('GET User Menu Access Error:', error)
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Gagal memuat menu akses' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// POST tetap sama (tanpa perubahan)
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { userId, menuIds } = await request.json()
|
||||
|
||||
if (!userId || !Array.isArray(menuIds)) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Data tidak valid' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
await prisma.userMenuAccess.deleteMany({ where: { userId } })
|
||||
|
||||
if (menuIds.length > 0) {
|
||||
await prisma.userMenuAccess.createMany({
|
||||
data: menuIds.map((menuId: string) => ({ userId, menuId })),
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('POST User Menu Access Error:', error)
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Gagal menyimpan menu akses' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -117,4 +117,44 @@ export const apiFetchVerifyOtp = async ({
|
||||
...data,
|
||||
status: response.status,
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
// Di dalam api_fetch_auth.ts
|
||||
|
||||
export async function apiFetchUserMenuAccess(userId: string): Promise<{
|
||||
success: boolean;
|
||||
menuIds?: string[];
|
||||
message?: string;
|
||||
}> {
|
||||
try {
|
||||
const res = await fetch(`/api/admin/user-menu-access/${userId}`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('API Fetch User Menu Access Error:', error);
|
||||
return { success: false, message: 'Gagal memuat menu akses' };
|
||||
}
|
||||
}
|
||||
|
||||
export async function apiUpdateUserMenuAccess(
|
||||
userId: string,
|
||||
menuIds: string[]
|
||||
): Promise<{ success: boolean; message?: string }> {
|
||||
try {
|
||||
const res = await fetch('/api/admin/user-menu-access', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ userId, menuIds }),
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('API Update User Menu Access Error:', error);
|
||||
return { success: false, message: 'Gagal menyimpan menu akses' };
|
||||
}
|
||||
}
|
||||
@@ -1,90 +1,136 @@
|
||||
// app/api/auth/_lib/session_verify.ts
|
||||
// // app/api/auth/_lib/session_verify.ts
|
||||
// import { cookies } from 'next/headers';
|
||||
// import { decrypt } from './decrypt';
|
||||
// import prisma from '@/lib/prisma';
|
||||
|
||||
// /**
|
||||
// * Verifikasi session hybrid:
|
||||
// * 1. Decrypt JWT token
|
||||
// * 2. Cek apakah token masih ada di database (untuk force logout)
|
||||
// * 3. Return data user terbaru dari database
|
||||
// */
|
||||
// export async function verifySession(): Promise<Record<string, unknown> | null> {
|
||||
// try {
|
||||
// const sessionKey = process.env.BASE_SESSION_KEY;
|
||||
// if (!sessionKey) {
|
||||
// throw new Error('BASE_SESSION_KEY tidak ditemukan di environment');
|
||||
// }
|
||||
|
||||
// const jwtSecret = process.env.BASE_TOKEN_KEY;
|
||||
// if (!jwtSecret) {
|
||||
// throw new Error('BASE_TOKEN_KEY tidak ditemukan di environment');
|
||||
// }
|
||||
|
||||
// const cookieStore = await cookies();
|
||||
// const token = cookieStore.get(sessionKey)?.value;
|
||||
|
||||
// if (!token) {
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// // Step 1: Decrypt JWT
|
||||
// const jwtUser = await decrypt({ token, jwtSecret });
|
||||
|
||||
// if (!jwtUser || !jwtUser.id) {
|
||||
// console.log('⚠️ JWT decrypt failed atau tidak ada user ID');
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// // Step 2: Cek database UserSession (untuk force logout)
|
||||
// try {
|
||||
// const dbSession = await prisma.userSession.findFirst({
|
||||
// where: {
|
||||
// userId: jwtUser.id as string,
|
||||
// token: token,
|
||||
// active: true,
|
||||
// OR: [
|
||||
// { expires: null },
|
||||
// { expires: { gte: new Date() } },
|
||||
// ],
|
||||
// },
|
||||
// include: {
|
||||
// User: {
|
||||
// select: {
|
||||
// id: true,
|
||||
// username: true,
|
||||
// nomor: true,
|
||||
// roleId: true,
|
||||
// isActive: true,
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// });
|
||||
|
||||
// // Token tidak ditemukan di database = sudah dihapus (force logout)
|
||||
// if (!dbSession) {
|
||||
// console.log('⚠️ Token valid tapi sudah dihapus dari database (force logout)');
|
||||
// return null;
|
||||
// }
|
||||
|
||||
// // Step 3: Return data user terbaru dari database
|
||||
// // Ini penting agar roleId selalu update
|
||||
// return {
|
||||
// id: dbSession.User.id,
|
||||
// username: dbSession.User.username,
|
||||
// nomor: dbSession.User.nomor,
|
||||
// roleId: dbSession.User.roleId,
|
||||
// isActive: dbSession.User.isActive,
|
||||
// };
|
||||
|
||||
// } catch (dbError) {
|
||||
// console.error("⚠️ Error cek database session:", dbError);
|
||||
// // Fallback: jika database error, tetap pakai JWT
|
||||
// return jwtUser;
|
||||
// }
|
||||
|
||||
// } catch (error) {
|
||||
// console.warn('❌ Session verification failed:', error);
|
||||
// return null;
|
||||
// }
|
||||
// }
|
||||
|
||||
// src/app/api/auth/_lib/session_verify.ts
|
||||
import { cookies } from 'next/headers';
|
||||
import { decrypt } from './decrypt';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
/**
|
||||
* Verifikasi session hybrid:
|
||||
* 1. Decrypt JWT token
|
||||
* 2. Cek apakah token masih ada di database (untuk force logout)
|
||||
* 3. Return data user terbaru dari database
|
||||
*/
|
||||
export async function verifySession(): Promise<Record<string, unknown> | null> {
|
||||
export async function verifySession() {
|
||||
try {
|
||||
const sessionKey = process.env.BASE_SESSION_KEY;
|
||||
if (!sessionKey) {
|
||||
throw new Error('BASE_SESSION_KEY tidak ditemukan di environment');
|
||||
}
|
||||
|
||||
const jwtSecret = process.env.BASE_TOKEN_KEY;
|
||||
if (!jwtSecret) {
|
||||
throw new Error('BASE_TOKEN_KEY tidak ditemukan di environment');
|
||||
|
||||
if (!sessionKey || !jwtSecret) {
|
||||
throw new Error('Environment variables tidak lengkap');
|
||||
}
|
||||
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get(sessionKey)?.value;
|
||||
const token = (await cookies()).get(sessionKey)?.value;
|
||||
if (!token) return null;
|
||||
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Step 1: Decrypt JWT
|
||||
// Decrypt JWT
|
||||
const jwtUser = await decrypt({ token, jwtSecret });
|
||||
|
||||
if (!jwtUser || !jwtUser.id) {
|
||||
console.log('⚠️ JWT decrypt failed atau tidak ada user ID');
|
||||
if (!jwtUser || !jwtUser.id) return null;
|
||||
|
||||
// ✅ Cek apakah session di-invalidate
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: jwtUser.id as string },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
nomor: true,
|
||||
roleId: true,
|
||||
isActive: true,
|
||||
sessionInvalid: true, // ← Tambahkan field ini
|
||||
},
|
||||
});
|
||||
|
||||
if (!user || user.sessionInvalid) {
|
||||
console.log('⚠️ Session tidak valid (force logout)');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Step 2: Cek database UserSession (untuk force logout)
|
||||
try {
|
||||
const dbSession = await prisma.userSession.findFirst({
|
||||
where: {
|
||||
userId: jwtUser.id as string,
|
||||
token: token,
|
||||
active: true,
|
||||
OR: [
|
||||
{ expires: null },
|
||||
{ expires: { gte: new Date() } },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
User: {
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
nomor: true,
|
||||
roleId: true,
|
||||
isActive: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Token tidak ditemukan di database = sudah dihapus (force logout)
|
||||
if (!dbSession) {
|
||||
console.log('⚠️ Token valid tapi sudah dihapus dari database (force logout)');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Step 3: Return data user terbaru dari database
|
||||
// Ini penting agar roleId selalu update
|
||||
return {
|
||||
id: dbSession.User.id,
|
||||
username: dbSession.User.username,
|
||||
nomor: dbSession.User.nomor,
|
||||
roleId: dbSession.User.roleId,
|
||||
isActive: dbSession.User.isActive,
|
||||
};
|
||||
|
||||
} catch (dbError) {
|
||||
console.error("⚠️ Error cek database session:", dbError);
|
||||
// Fallback: jika database error, tetap pakai JWT
|
||||
return jwtUser;
|
||||
}
|
||||
|
||||
return user;
|
||||
} catch (error) {
|
||||
console.warn('❌ Session verification failed:', error);
|
||||
console.warn('Session verification failed:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,24 @@
|
||||
// app/api/auth/me/route.ts
|
||||
// src/app/api/auth/me/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import { verifySession } from '../_lib/session_verify';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
// ✅ Verify session (hybrid: JWT + Database)
|
||||
const user = await verifySession();
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
message: "Session tidak valid",
|
||||
user: null
|
||||
},
|
||||
{ success: false, message: "Session tidak valid", user: null },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
// Data user sudah fresh dari database (via verifySession)
|
||||
// ✅ Ambil menu akses kustom
|
||||
const menuAccess = await prisma.userMenuAccess.findMany({
|
||||
where: { userId: user.id },
|
||||
select: { menuId: true },
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
user: {
|
||||
@@ -28,17 +28,13 @@ export async function GET() {
|
||||
nomor: user.nomor,
|
||||
roleId: user.roleId,
|
||||
isActive: user.isActive,
|
||||
menuIds: menuAccess.map(m => m.menuId), // ✅ tambahkan ini
|
||||
},
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error("❌ Error in /api/auth/me:", error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
message: "Terjadi kesalahan",
|
||||
user: null
|
||||
},
|
||||
{ success: false, message: "Terjadi kesalahan", user: null },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,46 +1,98 @@
|
||||
// app/middleware.js
|
||||
import { NextResponse, NextRequest } from 'next/server';
|
||||
// // app/middleware.js
|
||||
// import { NextResponse, NextRequest } from 'next/server';
|
||||
|
||||
// Daftar route yang diizinkan tanpa login (public routes)
|
||||
const publicRoutes = [
|
||||
'/*', // Home page
|
||||
'/about', // About page
|
||||
'/public/*', // Wildcard untuk semua route di bawah /public
|
||||
'/login', // Halaman login
|
||||
// // Daftar route yang diizinkan tanpa login (public routes)
|
||||
// const publicRoutes = [
|
||||
// '/*', // Home page
|
||||
// '/about', // About page
|
||||
// '/public/*', // Wildcard untuk semua route di bawah /public
|
||||
// '/login', // Halaman login
|
||||
// ];
|
||||
|
||||
// // Fungsi untuk memeriksa apakah route saat ini adalah route publik
|
||||
// function isPublicRoute(pathname: string) {
|
||||
// return publicRoutes.some((route) => {
|
||||
// // Jika route mengandung wildcard (*), gunakan regex untuk mencocokkan
|
||||
// if (route.endsWith('*')) {
|
||||
// const baseRoute = route.replace('*', ''); // Hapus wildcard
|
||||
// return pathname.startsWith(baseRoute); // Cocokkan dengan pathname
|
||||
// }
|
||||
// return pathname === route; // Cocokkan exact path
|
||||
// });
|
||||
// }
|
||||
|
||||
// export function middleware(request: NextRequest) {
|
||||
// const { pathname } = request.nextUrl;
|
||||
|
||||
// // Jika route adalah public, izinkan akses
|
||||
// if (isPublicRoute(pathname)) {
|
||||
// return NextResponse.next();
|
||||
// }
|
||||
|
||||
// // Jika bukan public route, periksa apakah pengguna sudah login
|
||||
// const isLoggedIn = request.cookies.get('darmasaba-auth-token'); // Contoh: cek cookie auth-token
|
||||
// if (!isLoggedIn) {
|
||||
// // Redirect ke halaman login jika belum login
|
||||
// return NextResponse.redirect(new URL('/login', request.url));
|
||||
// }
|
||||
|
||||
// // Jika sudah login, izinkan akses
|
||||
// return NextResponse.next();
|
||||
// }
|
||||
|
||||
// // Konfigurasi untuk menentukan path mana yang akan dijalankan middleware
|
||||
// export const config = {
|
||||
// matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'], // Jalankan middleware untuk semua route kecuali file statis
|
||||
// };
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
// src/app/admin/middleware.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
import { jwtVerify } from 'jose';
|
||||
|
||||
// Route publik di dalam /admin (boleh diakses tanpa login penuh)
|
||||
const PUBLIC_ADMIN_ROUTES = [
|
||||
'/admin/login',
|
||||
'/admin/registrasi',
|
||||
'/admin/validasi',
|
||||
'/admin/waiting-room',
|
||||
];
|
||||
|
||||
// Fungsi untuk memeriksa apakah route saat ini adalah route publik
|
||||
function isPublicRoute(pathname: string) {
|
||||
return publicRoutes.some((route) => {
|
||||
// Jika route mengandung wildcard (*), gunakan regex untuk mencocokkan
|
||||
if (route.endsWith('*')) {
|
||||
const baseRoute = route.replace('*', ''); // Hapus wildcard
|
||||
return pathname.startsWith(baseRoute); // Cocokkan dengan pathname
|
||||
}
|
||||
return pathname === route; // Cocokkan exact path
|
||||
});
|
||||
}
|
||||
export async function middleware(request: NextRequest) {
|
||||
const path = request.nextUrl.pathname;
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
|
||||
// Jika route adalah public, izinkan akses
|
||||
if (isPublicRoute(pathname)) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
// Jika bukan public route, periksa apakah pengguna sudah login
|
||||
const isLoggedIn = request.cookies.get('darmasaba-auth-token'); // Contoh: cek cookie auth-token
|
||||
if (!isLoggedIn) {
|
||||
// Redirect ke halaman login jika belum login
|
||||
return NextResponse.redirect(new URL('/login', request.url));
|
||||
}
|
||||
|
||||
// Jika sudah login, izinkan akses
|
||||
// Izinkan akses ke route publik di /admin
|
||||
if (PUBLIC_ADMIN_ROUTES.some(route => path.startsWith(route))) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
// Ambil token dari cookie
|
||||
const token = request.cookies.get(process.env.BASE_SESSION_KEY!)?.value;
|
||||
if (!token) {
|
||||
return NextResponse.redirect(new URL('/login', request.url));
|
||||
}
|
||||
|
||||
try {
|
||||
// Verifikasi JWT
|
||||
const secret = new TextEncoder().encode(process.env.BASE_TOKEN_KEY!);
|
||||
const { payload } = await jwtVerify(token, secret);
|
||||
const user = (payload as any).user;
|
||||
|
||||
// Cek apakah user aktif
|
||||
if (!user || !user.isActive) {
|
||||
return NextResponse.redirect(new URL('/login', request.url));
|
||||
}
|
||||
|
||||
// ✅ User valid → izinkan akses
|
||||
return NextResponse.next();
|
||||
} catch (error) {
|
||||
console.error('Middleware auth error:', error);
|
||||
return NextResponse.redirect(new URL('/login', request.url));
|
||||
}
|
||||
}
|
||||
|
||||
// Konfigurasi untuk menentukan path mana yang akan dijalankan middleware
|
||||
// Hanya berlaku untuk /admin/*
|
||||
export const config = {
|
||||
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'], // Jalankan middleware untuk semua route kecuali file statis
|
||||
matcher: ['/admin/:path*'],
|
||||
};
|
||||
@@ -1,9 +1,11 @@
|
||||
// src/store/authStore.ts
|
||||
import { proxy } from 'valtio';
|
||||
|
||||
export type User = {
|
||||
id: string;
|
||||
name: string;
|
||||
roleId?: number; // 0, 1, 2, 3
|
||||
roleId: number;
|
||||
menuIds?: string[] | null; // ✅ Pastikan pakai `string[]`
|
||||
};
|
||||
|
||||
export const authStore = proxy<{
|
||||
|
||||
Reference in New Issue
Block a user