Compare commits

..

5 Commits

Author SHA1 Message Date
091c33a73c Test Hapus Auth 2025-11-27 18:13:29 +08:00
dbf7c34228 Fix eror registrasi 2 2025-11-27 17:08:17 +08:00
036fc86fed Fix eror registrasi 1 2025-11-27 16:45:47 +08:00
2cecec733e Tambah cookies di bagian verifikasi, agar kedeteksi user sudah regis apa belom 2025-11-27 14:46:49 +08:00
c64a2e5457 Fix Seeder User, dan role 2025-11-27 12:18:15 +08:00
30 changed files with 311 additions and 129 deletions

View File

@@ -2163,20 +2163,20 @@ enum StatusPeminjaman {
// ========================================= USER ========================================= //
model User {
id String @id @default(cuid())
id String @id @default(cuid())
username String
nomor String @unique
roleId String @default("2")
isActive Boolean @default(false)
sessionInvalid Boolean @default(false)
nomor String @unique
roleId String @default("2")
isActive Boolean @default(false)
sessionInvalid Boolean @default(false)
lastLogin DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
sessions UserSession[] // ✅ Relasi one-to-many
role Role @relation(fields: [roleId], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
permissions Json?
sessions UserSession[] // ✅ Relasi one-to-many
role Role @relation(fields: [roleId], references: [id])
menuAccesses UserMenuAccess[]
@@map("users")
}
@@ -2184,6 +2184,7 @@ model Role {
id String @id @default(cuid())
name String @unique // ADMIN_DESA, ADMIN_KESEHATAN, ADMIN_SEKOLAH
description String?
permissions Json?
isActive Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -2203,18 +2204,18 @@ model KodeOtp {
}
model UserSession {
id String @id @default(cuid())
token String @db.Text // ✅ JWT bisa panjang
expiresAt DateTime // ✅ Ubah jadi expiresAt (konsisten)
active Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId String // ✅ HAPUS @unique - user bisa punya multiple sessions
@@index([userId]) // ✅ Index untuk query cepat
@@index([token]) // ✅ Index untuk verify cepat
id String @id @default(cuid())
token String @db.Text // ✅ JWT bisa panjang
expiresAt DateTime // ✅ Ubah jadi expiresAt (konsisten)
active Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId String // ✅ HAPUS @unique - user bisa punya multiple sessions
@@index([userId]) // ✅ Index untuk query cepat
@@index([token]) // ✅ Index untuk verify cepat
@@map("user_sessions")
}

View File

@@ -64,29 +64,23 @@ import { safeSeedUnique } from "./safeseedUnique";
(async () => {
console.log("🔄 Seeding roles...");
// Check for duplicate names in roles data
const roleNames = new Set();
const duplicateRoleNames = roles.filter((r) => {
if (roleNames.has(r.name)) {
console.warn(`⚠️ Duplicate role name found: ${r.name}`);
return true;
}
roleNames.add(r.name);
return false;
});
for (const r of roles) {
try {
// ✅ Destructure to remove permissions if exists
const { permissions, ...roleData } = r as any;
await safeSeedUnique(
"role",
{ id: r.id },
{ name: roleData.name },
{
name: r.name,
description: r.description,
isActive: r.isActive,
id: roleData.id,
name: roleData.name,
description: roleData.description,
permissions: roleData.permissions || {}, // ✅ Include permissions
isActive: roleData.isActive,
}
);
console.log(`✅ Seeded role -> ${r.name}`);
console.log(`✅ Seeded role -> ${roleData.name}`);
} catch (error: any) {
if (error.code === "P2002") {
console.warn(`⚠️ Role already exists (skipping): ${r.name}`);
@@ -96,13 +90,15 @@ import { safeSeedUnique } from "./safeseedUnique";
}
}
console.log("✅ Roles seeding completed");
// =========== USER ===========
console.log("🔄 Seeding users...");
for (const u of users) {
try {
// Verify role exists
// Verify role exists first
const roleExists = await prisma.role.findUnique({
where: { id: u.roleId.toString() },
select: { id: true }, // Only select id to minimize query
});
if (!roleExists) {
@@ -125,7 +121,13 @@ import { safeSeedUnique } from "./safeseedUnique";
);
console.log(`✅ Seeded user -> ${u.username}`);
} catch (error: any) {
console.error(`❌ Failed to seed user ${u.username}:`, error.message);
if (error.code === "P2003") {
console.error(
`❌ Foreign key constraint failed for user ${u.username}: Role ${u.roleId} does not exist`
);
} else {
console.error(`❌ Failed to seed user ${u.username}:`, error.message);
}
}
}
console.log("✅ Users seeding completed");

View File

@@ -1,5 +1,6 @@
'use client';
import { apiFetchLogin } from '@/app/api/auth/_lib/api_fetch_auth';
import { apiFetchLogin } from '@/app/api/[auth]/_lib/api_fetch_auth';
import colors from '@/con/colors';
import { Box, Button, Center, Image, Paper, Stack, Title } from '@mantine/core';
import { useRouter } from 'next/navigation';
@@ -15,7 +16,9 @@ function Login() {
// Login.tsx
async function onLogin() {
const cleanPhone = phone.replace(/\D/g, '');
console.log(cleanPhone);
if (cleanPhone.length < 10) {
toast.error('Nomor telepon tidak valid');
return;
@@ -25,6 +28,8 @@ function Login() {
setLoading(true);
const response = await apiFetchLogin({ nomor: cleanPhone });
console.log(response);
if (!response.success) {
toast.error(response.message || 'Gagal memproses login');
return;
@@ -32,11 +37,12 @@ function Login() {
// Simpan nomor untuk register
localStorage.setItem('auth_nomor', cleanPhone);
if (response.isRegistered) {
// ✅ User lama: simpan kodeId & ke validasi
// ✅ User lama: simpan kodeId
localStorage.setItem('auth_kodeId', response.kodeId);
router.push('/validasi');
// ✅ Cookie sudah di-set oleh API, langsung redirect
router.push('/validasi'); // Clean URL
} else {
// ❌ User baru: langsung ke registrasi (tanpa kodeId)
router.push('/registrasi');

View File

@@ -1,7 +1,7 @@
// app/registrasi/page.tsx
'use client';
import { apiFetchRegister } from '@/app/api/auth/_lib/api_fetch_auth';
import { apiFetchRegister } from '@/app/api/[auth]/_lib/api_fetch_auth';
import BackButton from '@/app/darmasaba/(pages)/desa/layanan/_com/BackButto';
import colors from '@/con/colors';
import {

View File

@@ -19,17 +19,34 @@ import { authStore } from '@/store/authStore';
export default function Validasi() {
const router = useRouter();
const [nomor, setNomor] = useState<string | null>(null);
const [otp, setOtp] = useState('');
const [loading, setLoading] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [kodeId, setKodeId] = useState<string | null>(null);
const [isRegistrationFlow, setIsRegistrationFlow] = useState(false); // Tambahkan flag
const [isRegistrationFlow, setIsRegistrationFlow] = useState(false);
// Cek apakah ini alur registrasi
// ✅ Deteksi flow dari cookie via API
useEffect(() => {
const storedUsername = localStorage.getItem('auth_username');
setIsRegistrationFlow(!!storedUsername);
const checkFlow = async () => {
try {
const res = await fetch('/api/get-flow', {
credentials: 'include'
});
const data = await res.json();
if (data.success) {
setIsRegistrationFlow(data.flow === 'register');
console.log('🔍 Flow detected from cookie:', data.flow);
}
} catch (error) {
console.error('❌ Error getting flow:', error);
setIsRegistrationFlow(false);
}
};
checkFlow();
}, []);
useEffect(() => {
@@ -43,7 +60,7 @@ export default function Validasi() {
setKodeId(storedKodeId);
const loadOtpData = async () => {
try {
const res = await fetch(`/api/auth/otp-data?kodeId=${encodeURIComponent(storedKodeId)}`);
const res = await fetch(`/api/otp-data?kodeId=${encodeURIComponent(storedKodeId)}`);
const result = await res.json();
if (res.ok && result.data?.nomor) {
@@ -68,10 +85,8 @@ export default function Validasi() {
setLoading(true);
try {
if (isRegistrationFlow) {
// 🔑 Alur REGISTRASI
await handleRegistrationVerification();
} else {
// 🔑 Alur LOGIN
await handleLoginVerification();
}
} catch (error) {
@@ -82,55 +97,56 @@ export default function Validasi() {
}
};
const handleRegistrationVerification = async () => {
const username = localStorage.getItem('auth_username');
if (!username) {
toast.error('Data registrasi tidak ditemukan.');
return;
}
const handleRegistrationVerification = async () => {
const username = localStorage.getItem('auth_username');
if (!username) {
toast.error('Data registrasi tidak ditemukan.');
return;
}
const cleanNomor = nomor?.replace(/\D/g, '') ?? '';
if (cleanNomor.length < 10 || username.trim().length < 5) {
toast.error('Data tidak valid');
return;
}
const cleanNomor = nomor?.replace(/\D/g, '') ?? '';
if (cleanNomor.length < 10 || username.trim().length < 5) {
toast.error('Data tidak valid');
return;
}
// Verifikasi OTP dulu
const verifyRes = await fetch('/api/auth/verify-otp-register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nomor: cleanNomor, otp, kodeId }),
});
const verifyRes = await fetch('/api/verify-otp-register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nomor: cleanNomor, otp, kodeId }),
credentials: 'include'
});
const verifyData = await verifyRes.json();
if (!verifyRes.ok) {
toast.error(verifyData.message || 'Verifikasi OTP gagal');
return;
}
const verifyData = await verifyRes.json();
if (!verifyRes.ok) {
toast.error(verifyData.message || 'Verifikasi OTP gagal');
return;
}
// ✅ Kirim ke finalize-registration → akan redirect ke /waiting-room
const finalizeRes = await fetch('/api/auth/finalize-registration', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nomor, username, kodeId }),
credentials: 'include'
});
const finalizeRes = await fetch('/api/finalize-registration', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nomor, username, kodeId }),
credentials: 'include'
});
if (finalizeRes.redirected) {
// ✅ Redirect otomatis oleh server
window.location.href = finalizeRes.url;
} else {
const data = await finalizeRes.json();
toast.error(data.message || 'Registrasi gagal');
}
};
if (data.success || finalizeRes.redirected) {
// ✅ Cleanup setelah registrasi sukses
await cleanupStorage();
window.location.href = '/waiting-room';
} else {
toast.error(data.message || 'Registrasi gagal');
}
};
// ✅ Verifikasi OTP untuk LOGIN
const handleLoginVerification = async () => {
const loginRes = await fetch('/api/auth/verify-otp-login', {
const loginRes = await fetch('/api/verify-otp-login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nomor, otp, kodeId }),
credentials: 'include'
});
const loginData = await loginRes.json();
@@ -148,7 +164,8 @@ const handleRegistrationVerification = async () => {
roleId: Number(roleId),
});
cleanupStorage();
// ✅ Cleanup setelah login sukses
await cleanupStorage();
if (!isActive) {
window.location.href = '/waiting-room';
@@ -161,29 +178,41 @@ const handleRegistrationVerification = async () => {
const getRedirectPath = (roleId: number): string => {
switch (roleId) {
case 0: // DEVELOPER
case 1: // SUPERADMIN
case 2: // ADMIN_DESA
case 0:
case 1:
case 2:
return '/admin/landing-page/profil/program-inovasi';
case 3: // ADMIN_KESEHATAN
case 3:
return '/admin/kesehatan/posyandu';
case 4: // ADMIN_PENDIDIKAN
case 4:
return '/admin/pendidikan/info-sekolah/jenjang-pendidikan';
default:
return '/admin';
}
};
const cleanupStorage = () => {
// ✅ CLEANUP FUNCTION - Hapus localStorage + Cookie
const cleanupStorage = async () => {
// Clear localStorage
localStorage.removeItem('auth_kodeId');
localStorage.removeItem('auth_nomor');
localStorage.removeItem('auth_username');
// Clear cookie
try {
await fetch('/api/clear-flow', {
method: 'POST',
credentials: 'include'
});
} catch (error) {
console.error('Error clearing flow cookie:', error);
}
};
const handleResend = async () => {
if (!nomor) return;
try {
const res = await fetch('/api/auth/resend', {
const res = await fetch('/api/resend', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nomor }),

View File

@@ -49,7 +49,7 @@ export default function Layout({ children }: { children: React.ReactNode }) {
useEffect(() => {
const fetchUser = async () => {
try {
const res = await fetch('/api/auth/me');
const res = await fetch('/api/me');
const data = await res.json();
if (data.user) {
@@ -114,7 +114,7 @@ export default function Layout({ children }: { children: React.ReactNode }) {
setIsLoggingOut(true);
// ✅ Panggil API logout untuk clear session di server
const response = await fetch('/api/auth/logout', { method: 'POST' });
const response = await fetch('/api/logout', { method: 'POST' });
const result = await response.json();
if (result.success) {

View File

@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
// app/api/auth/_lib/api_fetch_auth.ts
// app/api/_lib/api_fetch_auth.ts
// app/api/auth/_lib/api_fetch_auth.ts
// app/api/_lib/api_fetch_auth.ts
export const apiFetchLogin = async ({ nomor }: { nomor: string }) => {
if (!nomor || nomor.replace(/\D/g, '').length < 10) {
@@ -10,10 +10,11 @@ export const apiFetchLogin = async ({ nomor }: { nomor: string }) => {
const cleanPhone = nomor.replace(/\D/g, '');
const response = await fetch("/api/auth/login", {
const response = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ nomor: cleanPhone }),
credentials: 'include'
});
// Pastikan respons bisa di-parse sebagai JSON
@@ -21,7 +22,7 @@ export const apiFetchLogin = async ({ nomor }: { nomor: string }) => {
try {
data = await response.json();
} catch (e) {
console.error("Non-JSON response from /api/auth/login:", await response.text());
console.error("Non-JSON response from /api/login:", await response.text());
throw new Error('Respons server tidak valid');
}
@@ -54,10 +55,11 @@ export const apiFetchRegister = async ({
const cleanPhone = nomor.replace(/\D/g, '');
if (cleanPhone.length < 10) throw new Error('Nomor tidak valid');
const response = await fetch("/api/auth/register", {
const response = await fetch("/api/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: username.trim(), nomor: cleanPhone }),
credentials: 'include',
});
const data = await response.json();
@@ -71,7 +73,7 @@ export const apiFetchOtpData = async ({ kodeId }: { kodeId: string }) => {
throw new Error('Kode ID tidak valid');
}
const response = await fetch("/api/auth/otp-data", {
const response = await fetch("/api/otp-data", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ kodeId }),
@@ -88,7 +90,7 @@ export const apiFetchOtpData = async ({ kodeId }: { kodeId: string }) => {
// Ganti endpoint ke verify-otp-login
export const apiFetchVerifyOtp = async ({ nomor, otp, kodeId }: { nomor: string; otp: string; kodeId: string }) => {
const response = await fetch('/api/auth/verify-otp-login', {
const response = await fetch('/api/verify-otp-login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nomor, otp, kodeId }),

View File

@@ -0,0 +1,19 @@
// app/api/auth/clear-flow/route.ts
import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
export async function POST() {
try {
// ✅ Next.js 15 syntax
const cookieStore = await cookies();
cookieStore.delete('auth_flow');
return NextResponse.json({ success: true });
} catch (error) {
console.error('❌ Error clearing flow cookie:', error);
return NextResponse.json(
{ success: false, message: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -3,6 +3,21 @@ import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";
import { sessionCreate } from "../_lib/session_create";
// ✅ Gunakan STRING untuk roleId
const DEFAULT_MENUS_BY_ROLE: Record<string, string[]> = {
"0": [
"Landing Page", "PPID", "Desa", "Kesehatan", "Keamanan",
"Ekonomi", "Inovasi", "Lingkungan", "Pendidikan", "User & Role"
],
"1": [
"Landing Page", "PPID", "Desa", "Keamanan",
"Ekonomi", "Inovasi", "Lingkungan", "User & Role"
],
"2": ["Landing Page", "Desa", "Ekonomi", "Inovasi", "Lingkungan"],
"3": ["Kesehatan"],
"4": ["Pendidikan"],
};
export async function POST(req: Request) {
try {
const { nomor, username, kodeId } = await req.json();
@@ -30,27 +45,43 @@ export async function POST(req: Request) {
);
}
const defaultRole = await prisma.role.findFirst({
where: { name: "ADMIN DESA" },
select: { id: true },
// 🔥 Tentukan roleId sebagai STRING
const targetRoleId = "1"; // ✅ string, bukan number
// Validasi role (gunakan string)
const roleExists = await prisma.role.findUnique({
where: { id: targetRoleId }, // ✅ id bertipe string
select: { id: true }
});
if (!defaultRole) {
if (!roleExists) {
return NextResponse.json(
{ success: false, message: "Role default tidak ditemukan" },
{ status: 500 }
{ success: false, message: "Role tidak valid" },
{ status: 400 }
);
}
// Buat user dengan roleId string
const newUser = await prisma.user.create({
data: {
username,
nomor,
roleId: defaultRole.id,
roleId: targetRoleId, // ✅ string
isActive: false,
},
});
// Berikan akses menu
const menuIds = DEFAULT_MENUS_BY_ROLE[targetRoleId] || [];
if (menuIds.length > 0) {
await prisma.userMenuAccess.createMany({
data: menuIds.map(menuId => ({
userId: newUser.id,
menuId,
})),
});
}
await prisma.kodeOtp.update({
where: { id: kodeId },
data: { isActive: false },
@@ -64,13 +95,12 @@ export async function POST(req: Request) {
id: newUser.id,
nomor: newUser.nomor,
username: newUser.username,
roleId: newUser.roleId,
roleId: newUser.roleId, // string
isActive: false,
},
invalidatePrevious: false,
});
// ✅ REDIRECT DARI SERVER — cookie pasti tersedia
const response = NextResponse.redirect(new URL('/waiting-room', req.url));
response.cookies.set(process.env.BASE_SESSION_KEY!, token, {
httpOnly: true,

View File

@@ -0,0 +1,22 @@
// app/api/auth/get-flow/route.ts
import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
export async function GET() {
try {
// ✅ Next.js 15 syntax
const cookieStore = await cookies();
const flow = cookieStore.get('auth_flow')?.value || 'login';
return NextResponse.json({
success: true,
flow
});
} catch (error) {
console.error('❌ Error getting flow cookie:', error);
return NextResponse.json(
{ success: false, flow: 'login' },
{ status: 500 }
);
}
}

View File

@@ -2,6 +2,7 @@
import prisma from "@/lib/prisma";
import { NextResponse } from "next/server";
import { randomOTP } from "../_lib/randomOTP";
import { cookies } from "next/headers";
export async function POST(req: Request) {
if (req.method !== "POST") {
@@ -29,19 +30,37 @@ export async function POST(req: Request) {
const isRegistered = !!existingUser;
if (isRegistered) {
// ✅ User terdaftar → kirim OTP
const codeOtp = randomOTP();
const otpNumber = Number(codeOtp);
const waMessage = `Website Desa Darmasaba - Kode verifikasi Anda: ${codeOtp}`;
const waUrl = `https://wa.wibudev.com/code?nom=${encodeURIComponent(nomor)}&text=${encodeURIComponent(waMessage)}`;
// ✅ PERBAIKAN: Gunakan format pesan yang lebih sederhana
// Hapus karakter khusus yang bisa bikin masalah
const waMessage = `Website Desa Darmasaba\nKode verifikasi Anda ${codeOtp}`;
// // ✅ OPSI 1: Tanpa encoding (coba dulu ini)
// const waUrl = `https://wa.wibudev.com/code?nom=${nomor}&text=${waMessage}`;
// ✅ OPSI 2: Dengan encoding (kalau opsi 1 gagal)
const waUrl = `https://wa.wibudev.com/code?nom=${nomor}&text=${encodeURIComponent(waMessage)}`;
// ✅ OPSI 3: Encoding manual untuk URL-safe (alternatif terakhir)
// const encodedMessage = waMessage.replace(/\n/g, '%0A').replace(/ /g, '%20');
// const waUrl = `https://wa.wibudev.com/code?nom=${nomor}&text=${encodedMessage}`;
console.log("🔍 Debug WA URL:", waUrl); // Untuk debugging
const res = await fetch(waUrl);
const sendWa = await res.json();
console.log("📱 WA Response:", sendWa); // Debug response
if (sendWa.status !== "success") {
return NextResponse.json(
{ success: false, message: "Gagal mengirim OTP via WhatsApp" },
{
success: false,
message: "Gagal mengirim OTP via WhatsApp",
debug: sendWa // Tampilkan error detail
},
{ status: 400 }
);
}
@@ -50,6 +69,15 @@ export async function POST(req: Request) {
data: { nomor, otp: otpNumber, isActive: true },
});
const cookieStore = await cookies();
cookieStore.set('auth_flow', 'login', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 60 * 5, // 5 menit
path: '/'
});
return NextResponse.json({
success: true,
message: "Kode verifikasi dikirim",
@@ -57,16 +85,14 @@ export async function POST(req: Request) {
isRegistered: true,
});
} else {
// ❌ User belum terdaftar → JANGAN kirim OTP
return NextResponse.json({
success: true,
message: "Nomor belum terdaftar",
isRegistered: false,
// Tidak ada kodeId
});
}
} catch (error) {
console.error("Error Login:", error);
console.error("Error Login:", error);
return NextResponse.json(
{ success: false, message: "Terjadi kesalahan saat login" },
{ status: 500 }

View File

@@ -50,7 +50,7 @@ export async function GET() {
},
});
} catch (error) {
console.error("❌ Error in /api/auth/me:", error);
console.error("❌ Error in /api/me:", error);
return NextResponse.json(
{ success: false, message: "Internal server error", user: null },
{ status: 500 }

View File

@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import prisma from '@/lib/prisma';
import { randomOTP } from '../_lib/randomOTP'; // pastikan ada
import { randomOTP } from '../_lib/randomOTP';
export async function POST(req: Request) {
try {
@@ -36,7 +37,17 @@ export async function POST(req: Request) {
data: { nomor, otp: otpNumber, isActive: true }
});
// ✅ Kembalikan kodeId (jangan buat user di sini!)
// ✅ Set cookie flow=register (Next.js 15+ syntax)
const cookieStore = await cookies();
cookieStore.set('auth_flow', 'register', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 60 * 5, // 5 menit
path: '/'
});
// ✅ Kembalikan kodeId
return NextResponse.json({
success: true,
message: 'Kode verifikasi dikirim',

View File

@@ -0,0 +1,34 @@
// app/api/auth/set-flow/route.ts
import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
export async function POST(request: Request) {
try {
const { flow } = await request.json();
if (!flow || !['login', 'register'].includes(flow)) {
return NextResponse.json(
{ success: false, message: 'Invalid flow parameter' },
{ status: 400 }
);
}
// ✅ Next.js 15 syntax
const cookieStore = await cookies();
cookieStore.set('auth_flow', flow, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 60 * 5,
path: '/'
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('❌ Error setting flow cookie:', error);
return NextResponse.json(
{ success: false, message: 'Internal server error' },
{ status: 500 }
);
}
}

View File

@@ -16,7 +16,7 @@ import { useEffect, useState } from 'react';
import { authStore } from '@/store/authStore'; // ✅ integrasi authStore
async function fetchUser() {
const res = await fetch('/api/auth/me');
const res = await fetch('/api/me');
if (!res.ok) {
const text = await res.text();
throw new Error(`HTTP ${res.status}: ${text}`);
@@ -77,7 +77,7 @@ export default function WaitingRoom() {
// Force a session refresh
try {
const res = await fetch('/api/auth/refresh-session', {
const res = await fetch('/api/refresh-session', {
method: 'POST',
credentials: 'include'
});