Skip to content

Instantly share code, notes, and snippets.

@hscstudio
Last active December 13, 2023 18:27
Show Gist options
  • Save hscstudio/6a6459fe0b6e9809b27af7ff38451532 to your computer and use it in GitHub Desktop.
Save hscstudio/6a6459fe0b6e9809b27af7ff38451532 to your computer and use it in GitHub Desktop.
Implementasi Role Base Access Control (RBAC) di AdonisJS

Implementasi Role Base Access Control (RBAC) di AdonisJS

Buat field role (String) pada tabel user

Untuk menentukan role dari user, misalnya apakah di administrator, staff, member, dll

Buat middelware: app/Middleware/Rbac.js

class Rbac {
  async handle ({ request, auth }, next, rule) {
    const roles = rule
    if (roles.length == 0) {
      await next()
    } else {
      try {
        const user = await auth.current.user
        const role = user.role
        if(roles.includes(role)){
          await next()
        } else {
          throw new Error(`Only user with role: ${roles} can access the route`)  
        }
      } catch (e) {
        console.log(e)
        throw new Error(`Only user with role: ${roles} can access the route`)
      }
    }
  }
}

module.exports = Rbac

Register RBAC middleware to start/kernel.js

const namedMiddleware = {
  auth: 'Adonis/Middleware/Auth',
  guest: 'Adonis/Middleware/AllowGuestOnly',
  rbac: 'App/Middleware/Rbac' // <= ini
}

Daftarkan middleware ini pada route yang akan dilindungi

// route khusus administrator
Route.group(() => {
  Route.resource('manage-user', 'UserController').apiOnly()
  // route lain
}).prefix('api/v1').middleware(['auth:jwt', 'rbac:administrator'])

// route khusus untuk member
Route.group(() => {
  Route.resource('membership', 'MemberController').apiOnly()
  // route lain
}).prefix('api/v1').middleware(['auth:jwt', 'rbac:member'])

// route untuk administartor dan member
Route.group(() => {
  Route.post('/profile', 'ProfileController.update')
}).prefix('api/v1').middleware(['auth:jwt', 'rbac:administrator,member'])

Tambahkan fungsi hasRole pada model User untuk mengecek hak akses

hasRole(roles){
    const role = this.role
    return roles.includes(role)
} 

sehingga bisa dipakai di controller misalnya

async check ({ request, auth, response }) {
   const user = await auth.current.user

   if (user.hasRole(['administrator'])){
      // aksi untuk administrator saja
   }
}
@hscstudio
Copy link
Author

Iya sih benar om.. aku ganti jadi

canAccess => hasRole

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment