Skip to content

React RBAC Implementation

Published: at 09:30 AM

Table of Contents

Open Table of Contents

Apa itu Role-Based Access Control (RBAC)?

RBAC adalah sistem yang membatasi akses pengguna berdasarkan peran (role) yang mereka miliki. Misalnya, admin bisa mengakses semua fitur, siswa hanya bisa melihat materi, dan guru bisa menambahkan materi.


Setup Authentication

Gunakan library seperti NextAuth.js untuk mengelola autentikasi.

Install NextAuth.js:

npm install next-auth

Buat file pages/api/auth/[...nextauth].ts:

import NextAuth from "next-auth";
import Providers from "next-auth/providers";

export default NextAuth({
  providers: [
    Providers.Credentials({
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        // Cek credentials di database
        const user = {
          id: 1,
          name: "John Doe",
          email: "john@example.com",
          role: "admin",
        };
        if (
          credentials.email === user.email &&
          credentials.password === "123456"
        ) {
          return user;
        }
        return null;
      },
    }),
  ],
  callbacks: {
    async jwt(token, user) {
      if (user) {
        token.role = user.role;
      }
      return token;
    },
    async session(session, token) {
      session.user.role = token.role;
      return session;
    },
  },
});

Implementasi RBAC di API Routes

Tambahkan validasi role di API routes. Misalnya, hanya admin yang bisa menambahkan course.

Contoh di pages/api/courses/index.ts:

import { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "next-auth/react";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const session = await getSession({ req });

  if (req.method === "POST" && session?.user.role !== "admin") {
    return res.status(403).json({ message: "Forbidden" });
  }

  if (req.method === "POST") {
    const { title, description } = req.body;
    try {
      const course = await prisma.course.create({
        data: { title, description },
      });
      res.status(201).json(course);
    } catch (error) {
      res.status(500).json({ message: "Failed to add course" });
    }
  } else {
    res.status(405).json({ message: "Method not allowed" });
  }
}

Implementasi RBAC di Frontend

Gunakan session untuk memeriksa role user sebelum mengakses halaman tertentu.

Contoh di pages/admin/dashboard.tsx:

import { useSession } from "next-auth/react";
import { useRouter } from "next/router";

const AdminDashboard = () => {
  const { data: session, status } = useSession();
  const router = useRouter();

  if (status === "loading") return <div>Loading...</div>;

  if (status === "unauthenticated" || session?.user.role !== "admin") {
    router.push("/login");
    return null;
  }

  return (
    <div>
      <h1>Admin Dashboard</h1>
      <p>Welcome, {session.user.name}</p>
    </div>
  );
};

export default AdminDashboard;

Kesimpulan

Dengan RBAC, Anda dapat mengontrol akses pengguna berdasarkan peran mereka secara efektif. Ini sangat berguna untuk aplikasi yang memiliki banyak jenis pengguna seperti platform e-learning.

Explore NextAuth.js


Previous Post
OrbStack Alternatif Docker Desktop yang Lebih Ringan dan RAM-Friendly
Next Post
React Zustand Implementation