Elysia Tools

Browse tools, examples, visual explainers, and topic guides from one clear workspace.

Top Categories

Hubs

Language
ZHDERUPTENFRES

Elysia Tools

Navigation

Authentication & Authorization

Casbin Access Control Library

Powerful and efficient open-source access control library

Samples

Entries inside this sample collection

CodejavascriptSimple

Casbin RBAC Basic Setup

Role-Based Access Control with Casbin

Difficulty

3/10

Estimated time

10 min

Tags

casbin, rbac, authorization, security

Prerequisites

Node.js, Basic authorization concepts

javascript
// Casbin RBAC Setup
const { newEnforcer, newModelFromString, StringAdapter } = require('casbin');

const model = `
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
`;

const policy = `
p, admin, data1, read
p, bob, data2, write
g, alice, admin
`;

// Check permission
async function checkPermission(enforcer, user, resource, action) {
  const allowed = await enforcer.enforce(user, resource, action);
  console.log(`${user} can ${action} ${resource}: ${allowed}`);
  return allowed;
}

async function main() {
  const modelConf = newModelFromString(model);
  const policyAdapter = new StringAdapter(policy);
  const enforcer = await newEnforcer(modelConf, policyAdapter);

  await checkPermission(enforcer, 'alice', 'data1', 'read'); // true
  await checkPermission(enforcer, 'bob', 'data2', 'write');  // true
}

main().catch(console.error);
CodejavascriptIntermediate

Casbin Express.js Middleware

Authorization middleware for Express.js

Difficulty

5/10

Estimated time

15 min

Tags

casbin, express, middleware, api

Prerequisites

Node.js, Express.js, Casbin basics

javascript
// Casbin Express Middleware
const express = require('express');
const { newEnforcer } = require('casbin');

async function createAuthMiddleware(modelPath, policyPath) {
  const enforcer = await newEnforcer(modelPath, policyPath);

  return async (req, res, next) => {
    const user = req.user?.id || 'anonymous';
    const resource = req.path;
    const action = req.method.toLowerCase();

    const allowed = await enforcer.enforce(user, resource, action);

    if (!allowed) {
      return res.status(403).json({ error: 'Access denied' });
    }

    next();
  };
}

// Usage
const app = express();

// Initialize middleware
async function initApp() {
  const authMiddleware = await createAuthMiddleware(
    'path/to/model.conf',
    'path/to/policy.csv'
  );

  // Apply to routes
  app.get('/admin', authMiddleware, (req, res) => {
    res.json({ message: 'Admin area' });
  });

  app.post('/users', authMiddleware, (req, res) => {
    res.json({ message: 'User created' });
  });
}

initApp();
CodejavascriptComplex

Casbin ABAC with Attributes

Attribute-Based Access Control with dynamic rules

Difficulty

7/10

Estimated time

20 min

Tags

casbin, abac, attributes, advanced

Prerequisites

Casbin basics, ABAC concepts

javascript
// Casbin ABAC with Attributes
const model = `
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub_rule, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = eval(p.sub_rule) && r.obj == p.obj && r.act == p.act
`;

// Policy with attribute rules
const policies = [
  ['r.obj.Owner == r.sub', 'document', 'write'],
  ['r.sub.Role == "admin"', 'document', 'delete'],
  ['r.obj.Department == r.sub.Department', 'report', 'read']
];

// Context function for ABAC
function createContext(user, resource) {
  return {
    sub: {
      ...user,
      Role: user.role,
      Department: user.department
    },
    obj: {
      ...resource,
      Owner: resource.owner,
      Department: resource.department
    }
  };
}

// Check with attributes
async function checkABAC(enforcer, user, resource, action) {
  const ctx = createContext(user, resource);
  const allowed = await enforcer.enforce(
    ctx.sub,
    ctx.obj,
    action
  );
  return allowed;
}

const user = { id: 'alice', role: 'manager', department: 'finance' };
const doc = { id: 'doc1', owner: 'alice', department: 'finance' };

checkABAC(enforcer, user, doc, 'write'); // true
CodejavascriptIntermediate

Casbin Database Adapter

Store policies in database with persistent storage

Difficulty

6/10

Estimated time

15 min

Tags

casbin, database, persistence, mongodb

Prerequisites

Node.js, Database basics, Casbin

javascript
// Casbin Database Adapter
const express = require('express');
const { newEnforcer } = require('casbin');
const { MongooseAdapter } = require('casbin-mongoose-adapter');

const app = express();
app.use(express.json());

async function setupCasbinWithDB() {
  // Initialize database adapter
  const adapter = await MongooseAdapter.newAdapter('mongodb://localhost:27017/casbin');

  // Create enforcer with database adapter
  const enforcer = await newEnforcer(
    'path/to/model.conf',
    adapter
  );

  // Add policies to database
  await enforcer.addPolicy('alice', 'data1', 'read');
  await enforcer.addPolicy('bob', 'data2', 'write');

  // Add roles
  await enforcer.addRoleForUser('charlie', 'admin');

  // Check permission
  const allowed = await enforcer.enforce('alice', 'data1', 'read');

  // Get all policies
  const policies = await enforcer.getPolicy();
  console.log('All policies:', policies);

  // Remove policy
  await enforcer.removePolicy('alice', 'data1', 'read');

  return enforcer;
}

// Usage example
async function initAuthSystem() {
  const enforcer = await setupCasbinWithDB();

  // Dynamic policy management
  app.post('/policies', async (req, res) => {
    const { sub, obj, act } = req.body;
    await enforcer.addPolicy(sub, obj, act);
    res.json({ message: 'Policy added' });
  });
}

initAuthSystem();

Tools

Tools frequently paired with this sample

Related

Related sample collections

Related

Related workflows

Hub

Batch Audio Library Cleanup and Delivery

Take a pile of mixed audio files to one shippable library — find and judge duplicates, convert the whole batch to a single format with deliberate encoder settings, fix the CBR or VBR bitrate policy, repair tags and filenames in bulk, and correct playback speed without touching pitch.

Hub

Video Container Conversion with Deliberate Transcode Control

Convert footage between MP4, AVI, FLV, MKV, MOV, and WebM containers, keep CRF and bitrate decisions under control during the re-encode, and batch a whole library under one recorded configuration.

Hub

PDF Archival, Accessibility, and Trust Review

Clean scanned pages, add OCR, prepare PDF/A files, inspect accessibility structure, add bookmarks, and verify signatures before archival handoff.

Hub

Pre-Publish Web Accessibility Audit

Review a page or UI component for structural, reading-order, screenshot-contrast, and color-vision risks, then turn automated findings into a human-reviewed release record.

Home
Tools3212
Samples593
Visualizations471
Viewers103
Hubs239
Tags333
Images, Audio & Video657

Image, audio, and video processing, conversion, and optimization tools

Math, Date & Finance647

Calculators, numerics, date logic, statistics, and finance tools

Design & Color298

Color, layout, graphics, visual styling, and design helper tools

Text & Writing209

Writing, cleanup, formatting, extraction, and text analysis tools

Developer & Web193

Developer utilities, networking, web debugging, and automation helpers

Conversion & Encoding175

Format, file, archive, unit, and encoding conversion tools

Lead Generation Quiz Launch and Contact Handoff
Memorial Drafts: Family Review and Print Handoff
Private Habit Records: Backup, Restore and Sharing Review
Article to X and LinkedIn Drafts: Fact Review and Handoff
Markdown Interactive Deck Review and Offline Handoff

© 2026 Elysia Tools. All rights reserved.

DocsPricingAboutTerms of ServicePrivacy PolicyCookiesContact

Media

Audio Breath Control Editor

Detect breaths in speech and naturally crossfade to reduce, remove, or keep them.

Media

Duplicate Audio Library Finder

Find exact and near-duplicate audio across uploaded files or a ZIP, including copies saved with different codecs.

Development

HTTP Cache-Control CDN Edge TTL Budget Optimizer

Analyze Cache-Control directives, calculate browser/shared-cache TTL and stale budgets, detect directive conflicts, and compare static behavior notes for generic HTTP, Fastly, Cloudflare, and Akamai.

Data Processing

Log Parser - Apache/Nginx Access Log Parser

Parse Apache/Nginx access logs using regex patterns and extract structured data

Authentication & Authorization

OAuth 2.0 & OpenID Connect Samples

OAuth 2.0 authorization framework and OpenID Connect authentication protocol examples

Authentication & Authorization

OAuth 2.0 Samples

OAuth 2.0 implementation examples including authorization flows, client configurations, and security best practices

Security

JWT Samples

Comprehensive JWT examples from basic token structure to advanced security implementations

Security

Zero Trust Architecture Samples

Comprehensive Zero Trust architecture samples covering identity authentication, network segmentation, micro-segmentation strategies, and secure access control

Authentication & Authorization

Passport.js Authentication Middleware

Node.js authentication middleware with Passport.js and various strategies

Authentication & Authorization

SAML Samples

SAML (Security Assertion Markup Language) implementation examples including SSO, metadata, and identity provider configurations