Fix: middleware

Deskripsi
- Fix middleware
- Fix metode login ( sekarang menggunakan api )
This commit is contained in:
2024-12-02 16:24:03 +08:00
parent 45279cd37f
commit 31124c5500
55 changed files with 1675 additions and 420 deletions

View File

@@ -1,4 +1,4 @@
import { funCheckCookies } from "@/app_modules/_global/fun/get/fun_check_cookies";
import { Login } from "@/app_modules/auth";
import versionUpdate from "../../../../package.json";

View File

@@ -1,8 +0,0 @@
import { Register } from "@/app_modules/auth";
import { auth_getCodeOtpByNumber } from "@/app_modules/auth/fun/get_kode_otp_by_id";
export default async function Page({ params }: { params: { id: string } }) {
let otpId = params.id;
const dataOtp = await auth_getCodeOtpByNumber({ kodeId: otpId });
return <Register dataOtp={dataOtp} />;
}

View File

@@ -0,0 +1,5 @@
import { Register } from "@/app_modules/auth";
export default async function Page() {
return <Register />;
}

View File

@@ -0,0 +1,7 @@
import { SplashScreen } from "@/app_modules/auth";
export default async function Page() {
return <>
<SplashScreen/>
</>
}

View File

@@ -1,9 +0,0 @@
import { Validasi } from "@/app_modules/auth";
import { auth_getCodeOtpByNumber } from "@/app_modules/auth/fun/get_kode_otp_by_id";
export default async function Page({ params }: { params: { id: string } }) {
let kodeId = params.id;
const dataOtp = await auth_getCodeOtpByNumber({ kodeId: kodeId });
return <Validasi dataOtp={dataOtp as any} />;
}

View File

@@ -0,0 +1,5 @@
import { Validasi } from "@/app_modules/auth";
export default async function Page() {
return <Validasi />;
}

View File

@@ -0,0 +1,19 @@
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { funGlobal_checkActivationUseById } from "@/app_modules/_global/fun/get/fun_check_activation_use_by_id";
import WaitingRoom_View from "@/app_modules/waiting_room/view";
export default async function Page() {
const userLoginId = await funGetUserIdByToken();
const activationUser = await funGlobal_checkActivationUseById({
userId: userLoginId as string,
});
return (
<>
<WaitingRoom_View
activationUser={activationUser as boolean}
userLoginId={userLoginId as string}
/>
</>
);
}

View File

@@ -0,0 +1,21 @@
import { prisma } from "@/app/lib";
import { data } from "autoprefixer";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
try {
const data = await prisma.kodeOtp.findFirst({
where: {
id: id as string,
},
});
return new Response(JSON.stringify({ data }), { status: 200 });
} catch (error) {
console.log(error);
}
return new Response(JSON.stringify({ data: null }), { status: 404 });
}

View File

@@ -1,31 +1,64 @@
import { prisma } from "@/app/lib";
import { randomOTP } from "@/app_modules/auth/fun/rondom_otp";
import { NextResponse } from "next/server";
export async function POST(req: Request) {
if (req.method === "POST") {
const codeOtp = randomOTP();
const body = await req.json();
// console.log(body);
const { nomor } = body;
if (body.nomor === "1234567890") {
return NextResponse.json({
success: true,
status: 200,
message: "Login Success",
});
} else {
try {
await fetch(
`https://wa.wibudev.com/code?nom=${body.nomor}&text=Masukan Kode OTP:${body.otp}`
try {
const res = await fetch(
`https://wa.wibudev.com/code?nom=${nomor}&text=HIPMI - Kode ini bersifat RAHASIA dan JANGAN DI BAGIKAN KEPADA SIAPAPUN, termasuk anggota ataupun pengurus HIPMI lainnya.
\n
>> Kode OTP anda: ${codeOtp}.
`
);
const sendWa = await res.json();
if (sendWa.status !== "success")
return new Response(
JSON.stringify({
success: false,
message: "Nomor Whatsapp Tidak Aktif",
}),
{ status: 400 }
);
return NextResponse.json({
body,
status: 200,
message: "Login Success",
});
} catch (error) {
return NextResponse.json({ status: 500, message: "Server Error !!!" });
}
const createOtpId = await prisma.kodeOtp.create({
data: {
nomor: nomor,
otp: codeOtp,
},
});
if (!createOtpId)
return new Response(
JSON.stringify({
success: false,
message: "Gagal Membuat Kode OTP",
}),
{ status: 400 }
);
return new Response(
JSON.stringify({
success: true,
message: "Kode Verifikasi Dikirim",
kodeId: createOtpId.id,
}),
{ status: 200 }
);
} catch (error) {
console.log(error);
return new Response(
JSON.stringify({
success: false,
message: "Server Whatsapp Error !!",
}),
{ status: 500 }
);
}
}
return NextResponse.json({ success: false });

View File

@@ -1,12 +1,28 @@
import { prisma } from "@/app/lib";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
export async function GET() {
cookies().set({
name: "mySession",
value: "",
maxAge: 0,
});
const delToken = await prisma.userSession.delete({
where: {
userId: id as string,
},
});
return NextResponse.json({ status: 200, message: "Logout" });
const del = cookies().delete(process.env.NEXT_PUBLIC_BASE_SESSION_KEY!);
return new Response(JSON.stringify({ success: true, message: "Logout Berhasil" }), {status: 200});
}
// import { cookies } from "next/headers";
// import { NextResponse } from "next/server";
// export async function GET() {
// cookies().set({
// name: "mySession",
// value: "",
// maxAge: 0,
// });
// return NextResponse.json({ status: 200, message: "Logout" });
// }

View File

@@ -1,51 +1,69 @@
import { sessionCreate } from "@/app/auth/_lib/session_create";
import prisma from "@/app/lib/prisma";
import { ServerEnv } from "@/app/lib/server_env";
import { sealData } from "iron-session";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
export async function POST(req: Request) {
if (req.method === "POST") {
const body = await req.json();
// MyConsole(body);
const { data } = await req.json();
const cekUsername = await prisma.user.findUnique({
where: {
username: body.username,
username: data.username,
},
});
if (cekUsername)
return NextResponse.json({ status: 400, message: "Username sudah ada" });
return new Response(
JSON.stringify({
success: false,
message: "Username sudah digunakan",
}),
{ status: 400 }
);
const data = await prisma.user.create({
const createUser = await prisma.user.create({
data: {
username: body.username,
nomor: body.nomor,
username: data.username,
nomor: data.nomor,
},
});
if (data) {
const seal = await sealData(
JSON.stringify({
id: data.id,
username: data.username,
}),
{
password: ServerEnv.value?.WIBU_PWD as string,
}
);
const token = await sessionCreate({
sessionKey: process.env.NEXT_PUBLIC_BASE_SESSION_KEY!,
encodedKey: process.env.NEXT_PUBLIC_BASE_TOKEN_KEY!,
user: createUser as any,
});
cookies().set({
name: "mySession",
value: seal,
maxAge: 60 * 60 * 24 * 7,
try {
const createUserSession = await prisma.userSession.create({
data: {
token: token as string,
userId: createUser.id,
},
});
return NextResponse.json({ status: 201 });
if (!createUserSession)
return new Response(
JSON.stringify({
success: false,
message: "Gagal Membuat Session",
}),
{ status: 400 }
);
} catch (error) {
console.log(error);
}
return NextResponse.json({ success: true });
return new Response(
JSON.stringify({
success: true,
message: "Berhasil Login",
}),
{ status: 200 }
);
}
return NextResponse.json({ success: false });
return new Response(
JSON.stringify({ success: false, message: "Method Not Allowed" }),
{ status: 405 }
);
}

View File

@@ -0,0 +1,65 @@
import { prisma } from "@/app/lib";
import { randomOTP } from "@/app_modules/auth/fun/rondom_otp";
import { NextResponse } from "next/server";
export async function POST(req: Request) {
if (req.method === "POST") {
const codeOtp = randomOTP();
const body = await req.json();
const { nomor } = body;
try {
const res = await fetch(
`https://wa.wibudev.com/code?nom=${nomor}&text=HIPMI - Kode ini bersifat RAHASIA dan JANGAN DI BAGIKAN KEPADA SIAPAPUN, termasuk anggota ataupun pengurus HIPMI lainnya.
\n
>> Kode OTP anda: ${codeOtp}.
`
);
const sendWa = await res.json();
if (sendWa.status !== "success")
return new Response(
JSON.stringify({
success: false,
message: "Nomor Whatsapp Tidak Aktif",
}),
{ status: 400 }
);
const createOtpId = await prisma.kodeOtp.create({
data: {
nomor: nomor,
otp: codeOtp,
},
});
if (!createOtpId)
return new Response(
JSON.stringify({
success: false,
message: "Gagal Membuat Kode OTP",
}),
{ status: 400 }
);
return new Response(
JSON.stringify({
success: true,
message: "Kode Verifikasi Dikirim",
kodeId: createOtpId.id,
}),
{ status: 200 }
);
} catch (error) {
console.log(error);
return new Response(
JSON.stringify({
success: false,
message: "Server Whatsapp Error !!",
}),
{ status: 500 }
);
}
}
return NextResponse.json({ success: false });
}

View File

@@ -1,3 +1,4 @@
import { sessionCreate } from "@/app/auth/_lib/session_create";
import prisma from "@/app/lib/prisma";
import { ServerEnv } from "@/app/lib/server_env";
import { sealData } from "iron-session";
@@ -7,45 +8,100 @@ import { NextResponse } from "next/server";
export async function POST(req: Request) {
if (req.method === "POST") {
const body = await req.json();
const { nomor } = await req.json();
const data = await prisma.user.findUnique({
const dataUser = await prisma.user.findUnique({
where: {
nomor: body.nomor,
nomor: nomor,
},
select: {
id: true,
nomor: true,
username: true,
active: true,
masterUserRoleId: true,
},
});
if (!data) return NextResponse.json({ status: 404 });
if (data) {
const res = await sealData(
JSON.stringify({
id: data.id,
username: data.username,
}),
{
password: ServerEnv.value?.WIBU_PWD as string,
}
if (dataUser === null)
return new Response(
JSON.stringify({ success: false, message: "Nomor Belum Terdaftar" }),
{ status: 404 }
);
cookies().set({
name: "mySession",
value: res,
maxAge: 60 * 60 * 24 * 7,
const token = await sessionCreate({
sessionKey: process.env.NEXT_PUBLIC_BASE_SESSION_KEY!,
encodedKey: process.env.NEXT_PUBLIC_BASE_TOKEN_KEY!,
user: dataUser as any,
});
const cekSessionUser = await prisma.userSession.findFirst({
where: {
userId: dataUser.id,
},
});
if (cekSessionUser !== null) {
await prisma.userSession.delete({
where: {
userId: dataUser.id,
},
});
revalidatePath("/dev/home");
return NextResponse.json({ status: 200, data });
}
return NextResponse.json({ success: true });
try {
const createUserSession = await prisma.userSession.create({
data: {
token: token as string,
userId: dataUser.id,
},
});
if (!createUserSession)
return new Response(
JSON.stringify({ success: false, message: "Gagal Membuat Session" }),
{ status: 400 }
);
} catch (error) {
console.log(error);
}
// if (data) {
// const res = await sealData(
// JSON.stringify({
// id: data.id,
// username: data.username,
// }),
// {
// password: ServerEnv.value?.WIBU_PWD as string,
// }
// );
// cookies().set({
// name: "mySession",
// value: res,
// maxAge: 60 * 60 * 24 * 7,
// });
// revalidatePath("/dev/home");
// return NextResponse.json({ status: 200, data });
// }
// return NextResponse.json({ success: true });
return new Response(
JSON.stringify({
success: true,
message: "Berhasil Login",
roleId: dataUser.masterUserRoleId,
active: dataUser.active,
}),
{ status: 200 }
);
}
return NextResponse.json({ success: false });
return new Response(
JSON.stringify({ success: false, message: "Method Not Allowed" }),
{ status: 405 }
);
}

View File

@@ -0,0 +1,7 @@
export async function GET(req: Request) {
const auth = req.headers.get("Authorization");
const token = auth?.split(" ")[1];
if (!token)
return new Response(JSON.stringify({ success: false }), { status: 401 });
return new Response(JSON.stringify({ success: true }));
}

View File

@@ -0,0 +1,22 @@
import { jwtVerify } from "jose";
export async function decrypt({
token,
encodedKey,
}: {
token: string;
encodedKey: string;
}): Promise<Record<string, any> | null> {
try {
const enc = new TextEncoder().encode(encodedKey);
const { payload } = await jwtVerify(token, enc, {
algorithms: ["HS256"],
});
return (payload.user as Record<string, any>) || null;
} catch (error) {
console.error("Gagal verifikasi session", error);
return null;
}
}
// wibu:0.2.82

View File

@@ -0,0 +1,25 @@
import { SignJWT } from "jose";
export async function encrypt({
user,
exp = "7 year",
encodedKey,
}: {
user: Record<string, any>;
exp?: string;
encodedKey: string;
}): Promise<string | null> {
try {
const enc = new TextEncoder().encode(encodedKey);
return new SignJWT({ user })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime(exp)
.sign(enc);
} catch (error) {
console.error("Gagal mengenkripsi", error);
return null;
}
}
// wibu:0.2.82

View File

@@ -0,0 +1,35 @@
import { cookies } from "next/headers";
import { encrypt } from "./encrypt";
export async function sessionCreate({
sessionKey,
exp = "7 year",
encodedKey,
user,
}: {
sessionKey: string;
exp?: string;
encodedKey: string;
user: Record<string, unknown>;
}) {
const token = await encrypt({
exp,
encodedKey,
user,
});
const cookie: any = {
key: sessionKey,
value: token,
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
},
};
cookies().set(cookie.key, cookie.value, { ...cookie.options });
return token;
}
// wibu:0.2.82

View File

@@ -0,0 +1,27 @@
import { prisma } from "@/app/lib";
import { sessionCreate } from "../../_lib/session_create";
export async function POST(req: Request) {
const user = await prisma.user.findUnique({
where: {
nomor: "6281339158911",
},
select: {
id: true,
nomor: true,
},
});
if (!user)
return new Response(
JSON.stringify({ success: false, message: "User not found" }), {status: 404}
);
const token = await sessionCreate({
sessionKey: process.env.NEXT_PUBLIC_BASE_SESSION_KEY!,
encodedKey: process.env.NEXT_PUBLIC_BASE_TOKEN_KEY!,
user: user as any,
});
return new Response(JSON.stringify({ success: true, token }));
}

View File

@@ -0,0 +1,5 @@
import { cookies } from "next/headers";
export async function GET() {
const del = cookies().delete(process.env.NEXT_PUBLIC_BASE_SESSION_KEY!);
return new Response(JSON.stringify({ success: true }));
}

View File

@@ -0,0 +1,39 @@
"use client";
import { Button } from "@mantine/core";
import { useState } from "react";
export default function Page() {
const [loading, setLoading] = useState(false);
async function login() {
setLoading(true);
try {
const res = await fetch("/auth/api/login", {
method: "POST",
});
const dataText = await res.text();
if (!res.ok) {
console.error(dataText);
throw new Error(res.statusText);
}
const dataJson = JSON.parse(dataText);
console.log(dataJson);
// window.location.replace("/dev/home");
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
}
return (
<>
<Button loading={loading} onClick={login}>
Login
</Button>
</>
);
}

View File

@@ -6,9 +6,9 @@ import { redirect } from "next/navigation";
export default async function Page() {
const version = versionUpdate.version;
const checkCookies = await funCheckCookies();
console.log(checkCookies, "ini halaman login");
if (!checkCookies) return redirect("/");
// const checkCookies = await funCheckCookies();
// console.log(checkCookies, "ini halaman login");
// if (!checkCookies) return redirect("/");
return (
<>

View File

@@ -4,5 +4,5 @@ import { auth_getCodeOtpByNumber } from "@/app_modules/auth/fun/get_kode_otp_by_
export default async function Page({ params }: { params: { id: string } }) {
let otpId = params.id;
const dataOtp = await auth_getCodeOtpByNumber({ kodeId: otpId });
return <Register dataOtp={dataOtp} />;
return <Register />;
}

View File

@@ -3,7 +3,7 @@ import { SplashScreen } from "@/app_modules/auth";
export default async function PageSplash() {
return (
<>
<SplashScreen checkCookies/>
<SplashScreen />
</>
);
}

View File

@@ -5,6 +5,5 @@ export default async function Page({ params }: { params: { id: string } }) {
let kodeId = params.id;
const dataOtp = await auth_getCodeOtpByNumber({ kodeId: kodeId });
return <Validasi dataOtp={dataOtp as any} />;
return <Validasi />;
}

View File

@@ -6,16 +6,16 @@ import { CheckCookies_UiView } from "@/app_modules/check_cookies";
import { redirect } from "next/navigation";
export default async function Page() {
const userLoginId = await funGetUserIdByToken();
const dataUser = await funGlobal_getUserById({ userId: userLoginId });
// const userLoginId = await funGetUserIdByToken();
// const dataUser = await funGlobal_getUserById({ userId: userLoginId });
if (dataUser?.masterUserRoleId === "1") {
return redirect(RouterHome.main_home);
}
// if (dataUser?.masterUserRoleId === "1") {
// return redirect(RouterHome.main_home);
// }
if (dataUser?.masterUserRoleId !== "1") {
return redirect(RouterAdminDashboard.splash_admin);
}
// if (dataUser?.masterUserRoleId !== "1") {
// return redirect(RouterAdminDashboard.splash_admin);
// }
// return <CheckCookies_UiView />;
}

View File

@@ -16,7 +16,7 @@ export default async function Page({ params }: { params: { id: string } }) {
page: 1,
});
dataPosting?.isActive === false && redirect(RouterForum.beranda);
// dataPosting?.isActive === false && redirect(RouterForum.beranda);
const countKomentar = await forum_countTotalKomenById(postingId);

View File

@@ -1,10 +1,14 @@
import { RouterAdminDashboard } from "@/app/lib/router_hipmi/router_admin";
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { HomeView } from "@/app_modules/home";
import { user_getOneByUserId } from "@/app_modules/home/fun/get/get_one_user_by_id";
import { job_getTwoForHomeView } from "@/app_modules/job/fun/get/get_two_for_home_view";
import notifikasi_countUserNotifikasi from "@/app_modules/notifikasi/fun/count/fun_count_by_id";
export default async function Page() {
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
export default async function PageHome() {
const userLoginId = await funGetUserIdByToken();
const dataUser = await user_getOneByUserId(userLoginId as string);
const dataJob = await job_getTwoForHomeView();
@@ -16,8 +20,8 @@ export default async function Page() {
// if (dataUser?.active === false) {
// return redirect(RouterHome.home_user_non_active);
// }
// if (dataUser?.masterUserRoleId === "2" || dataUser?.masterUserRoleId === "3")
// return redirect(RouterAdminDashboard.splash_admin);
if (dataUser?.masterUserRoleId === "2" || dataUser?.masterUserRoleId === "3")
return redirect(RouterAdminDashboard.main_admin);
return (
<>

View File

@@ -1,28 +1,23 @@
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { funCheckCookies } from "@/app_modules/_global/fun/get/fun_check_cookies";
import { permanentRedirect, redirect } from "next/navigation";
import { funGlobal_getUserById } from "@/app_modules/_global/fun/get/fun_get_user_by_id";
import { redirect } from "next/navigation";
import { RealtimeProvider } from "../lib";
import { ServerEnv } from "../lib/server_env";
import { funGlobal_getUserById } from "@/app_modules/_global/fun/get/fun_get_user_by_id";
import { RouterHome } from "../lib/router_hipmi/router_home";
import { CheckCookies_UiLayout } from "@/app_modules/check_cookies";
import { RouterAdminDashboard } from "../lib/router_hipmi/router_admin";
import { funGlobal_checkActivationUseById } from "@/app_modules/_global/fun/get/fun_check_activation_use_by_id";
export default async function Layout({
children,
}: {
children: React.ReactNode;
}) {
const checkCookies = await funCheckCookies();
const userLoginId = await funGetUserIdByToken();
if (!checkCookies) return redirect("/");
// const dataUser = await funGlobal_getUserById({ userId: userLoginId });
// console.log(dataUser?.active, dataUser?.username, "ini di layout");
// if(dataUser?.active == false) return permanentRedirect(RouterHome.home_user_non_active);
// const WIBU_REALTIME_TOKEN = process.env.NEXT_PUBLIC_WIBU_REALTIME_TOKEN;
// console.log(WIBU_REALTIME_TOKEN, "check cookies di layout dalam");
const activationUser = await funGlobal_checkActivationUseById({
userId: userLoginId as string,
});
console.log(activationUser, "ini di layout");
if (activationUser == false) return redirect("/waiting-room");
return (
<>
<RealtimeProvider

View File

@@ -1,6 +1,4 @@
import { Home_UserNonActive } from "@/app_modules/home";
// import { redirect } from "next/navigation";
export default async function Page() {
return (
<>

View File

@@ -16,7 +16,7 @@ export default async function Layout({
<>
<LayoutVote_DetailSemuaRiwayat
votingId={votingId}
userLoginId={userLoginId}
userLoginId={userLoginId as string}
>
{children}
</LayoutVote_DetailSemuaRiwayat>

View File

@@ -1,13 +1,8 @@
import MqttLoader from "@/util/mqtt_loader";
import RootStyleRegistry from "./emotion";
// import "./globals.css";
import { TokenProvider } from "./lib/token";
import dotenv from "dotenv";
import { ServerEnv } from "./lib/server_env";
import { RealtimeProvider } from "./lib";
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { funCheckCookies } from "@/app_modules/_global/fun/get/fun_check_cookies";
import { redirect } from "next/navigation";
import { TokenProvider } from "./lib/token";
dotenv.config({
path: ".env",
});

View File

@@ -1,24 +1,10 @@
import { funCheckCookies } from "@/app_modules/_global/fun/get/fun_check_cookies";
import PageSplash from "./dev/auth/splash/page";
import { redirect } from "next/navigation";
import { Login, SplashScreen } from "@/app_modules/auth";
import { RouterAuth } from "./lib/router_hipmi/router_auth";
import versionUpdate from "../../package.json";
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { funGlobal_getUserById } from "@/app_modules/_global/fun/get/fun_get_user_by_id";
import { RouterHome } from "./lib/router_hipmi/router_home";
import { RouterAdminDashboard } from "./lib/router_hipmi/router_admin";
export default async function Page() {
const version = versionUpdate.version;
const checkCookies = await funCheckCookies();
// console.log(checkCookies, "ini check cookies di page awal");
if (checkCookies) return redirect("/dev/check-cookies");
return redirect("/login");
// const WIBU_REALTIME_TOKEN = process.env.NEXT_PUBLIC_WIBU_REALTIME_TOKEN;
// return <Login version={version} />;
// return <SplashScreen checkCookies={checkCookies} />;
return <PageSplash />;
return redirect("/dev/home");
// return <PageSplash />;
}