SiamCafe.net Blog
Technology

WordPress WooCommerce RBAC ABAC Policy ระบบควบคม Access Control

wordpress woocommerce rbac abac policy
WordPress WooCommerce RBAC ABAC Policy | SiamCafe Blog
2026-01-19· อ. บอม — SiamCafe.net· 1,081 คำ

RBAC ????????? ABAC ?????????????????????

RBAC (Role-Based Access Control) ?????????????????????????????????????????? access ????????? role ???????????????????????? ???????????? admin, editor, shop_manager ??????????????? role ?????? permissions ????????????????????????????????? ???????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????? role ?????????????????? WordPress ????????? RBAC ????????????????????? default ?????? roles ????????????????????? Administrator, Editor, Author, Contributor, Subscriber

ABAC (Attribute-Based Access Control) ?????????????????????????????????????????????????????????????????? ???????????????????????? access ????????? attributes ????????????????????? ???????????? user attributes (department, location), resource attributes (classification, owner), environment attributes (time, IP address), action attributes (read, write, delete) ABAC flexible ???????????? RBAC ????????? ??????????????? policies ??????????????????????????????????????? ???????????? "????????? shop manager ?????? orders ?????????????????????????????????????????????????????? ?????????????????????????????????"

?????????????????? WooCommerce store ??????????????????????????????????????? ???????????? vendor ????????????????????????????????? fine-grained access control ?????????????????? RBAC + ABAC ???????????????????????????????????????????????????????????????????????? ????????? RBAC ?????????????????? basic role structure ????????? ABAC ?????????????????? context-aware decisions

????????????????????? RBAC ?????? WordPress

??????????????? Custom Roles ????????? Capabilities

# === WordPress RBAC Configuration ===

# 1. Custom Roles (add to functions.php or plugin)
cat > rbac-setup.php << 'PHPEOF'
 true,
        'edit_posts' => false,
        'manage_woocommerce' => true,
        'view_woocommerce_reports' => true,
        'edit_shop_orders' => true,
        'read_shop_orders' => true,
        'edit_others_shop_orders' => false,  // Cannot edit other regions
        'publish_shop_orders' => true,
        'edit_products' => true,
        'read_products' => true,
        'edit_others_products' => false,
        'manage_categories' => false,
    ));

    // Warehouse Staff
    add_role('warehouse_staff', 'Warehouse Staff', array(
        'read' => true,
        'edit_posts' => false,
        'manage_woocommerce' => false,
        'edit_shop_orders' => true,
        'read_shop_orders' => true,
        'edit_others_shop_orders' => false,
        'manage_stock' => true,  // Custom capability
    ));

    // Customer Support
    add_role('support_agent', 'Support Agent', array(
        'read' => true,
        'edit_posts' => false,
        'read_shop_orders' => true,
        'edit_shop_orders' => true,
        'read_shop_coupons' => true,
        'issue_refunds' => true,  // Custom capability
        'view_customer_data' => true,  // Custom capability
    ));

    // Vendor (Multi-vendor marketplace)
    add_role('vendor', 'Vendor', array(
        'read' => true,
        'edit_products' => true,
        'publish_products' => true,
        'delete_products' => true,
        'upload_files' => true,
        'read_shop_orders' => true,  // Own orders only (enforced by ABAC)
        'view_own_reports' => true,  // Custom capability
    ));
}
add_action('init', 'setup_woocommerce_rbac');

// Capability check helper
function user_has_woo_capability($capability) {
    return current_user_can($capability);
}
PHPEOF

# 2. WP-CLI Commands for Role Management
cat > manage_roles.sh << 'BASH'
#!/bin/bash
# WordPress Role Management via WP-CLI

# List all roles
wp role list --format=table

# Create role
wp role create regional_manager "Regional Manager"

# Add capabilities to role
wp cap add regional_manager manage_woocommerce
wp cap add regional_manager view_woocommerce_reports
wp cap add regional_manager edit_shop_orders
wp cap add regional_manager read_shop_orders

# Remove capability
wp cap remove regional_manager delete_shop_orders

# Assign role to user
wp user set-role john@example.com regional_manager

# List user capabilities
wp user list-caps john@example.com

echo "Roles configured"
BASH

echo "RBAC setup complete"

??????????????? Custom ABAC System

Attribute-Based Access Control ?????????????????? WooCommerce

#!/usr/bin/env python3
# abac_engine.py ??? ABAC Policy Engine for WooCommerce
import json
import logging
from typing import Dict, List, Any

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("abac")

class ABACEngine:
    """Attribute-Based Access Control Engine"""
    
    def __init__(self):
        self.policies = []
    
    def add_policy(self, policy):
        """Add access policy"""
        self.policies.append(policy)
    
    def evaluate(self, request):
        """Evaluate access request against policies"""
        subject = request.get("subject", {})
        resource = request.get("resource", {})
        action = request.get("action", "")
        environment = request.get("environment", {})
        
        for policy in self.policies:
            result = self._match_policy(policy, subject, resource, action, environment)
            if result is not None:
                return {
                    "decision": result,
                    "policy": policy["name"],
                    "subject": subject.get("id"),
                    "action": action,
                    "resource": resource.get("type"),
                }
        
        # Default deny
        return {"decision": "DENY", "policy": "default_deny", "reason": "No matching policy"}
    
    def _match_policy(self, policy, subject, resource, action, environment):
        conditions = policy.get("conditions", {})
        
        # Check subject conditions
        for key, value in conditions.get("subject", {}).items():
            if isinstance(value, list):
                if subject.get(key) not in value:
                    return None
            elif subject.get(key) != value:
                return None
        
        # Check resource conditions
        for key, value in conditions.get("resource", {}).items():
            if isinstance(value, list):
                if resource.get(key) not in value:
                    return None
            elif resource.get(key) != value:
                return None
        
        # Check action
        allowed_actions = conditions.get("actions", [])
        if allowed_actions and action not in allowed_actions:
            return None
        
        # Check environment conditions
        for key, value in conditions.get("environment", {}).items():
            if environment.get(key) != value:
                return None
        
        return policy.get("effect", "DENY")

# Setup ABAC Engine
engine = ABACEngine()

# Policy 1: Regional managers can only manage orders from their region
engine.add_policy({
    "name": "regional_order_access",
    "effect": "ALLOW",
    "conditions": {
        "subject": {"role": ["regional_manager"]},
        "resource": {"type": "order"},
        "actions": ["read", "update", "refund"],
    },
})

# Policy 2: Vendors can only see their own products and orders
engine.add_policy({
    "name": "vendor_own_resources",
    "effect": "ALLOW",
    "conditions": {
        "subject": {"role": ["vendor"]},
        "resource": {"type": "product"},
        "actions": ["read", "create", "update", "delete"],
    },
})

# Policy 3: Support agents can issue refunds up to limit
engine.add_policy({
    "name": "support_refund_policy",
    "effect": "ALLOW",
    "conditions": {
        "subject": {"role": ["support_agent"]},
        "resource": {"type": "order"},
        "actions": ["read", "refund"],
    },
})

# Test evaluations
requests = [
    {"subject": {"id": "user_1", "role": "regional_manager", "region": "north"},
     "resource": {"type": "order", "region": "north"},
     "action": "read", "environment": {"time": "09:00"}},
    {"subject": {"id": "user_2", "role": "vendor", "vendor_id": "v001"},
     "resource": {"type": "product", "owner": "v001"},
     "action": "update", "environment": {}},
    {"subject": {"id": "user_3", "role": "subscriber"},
     "resource": {"type": "order"},
     "action": "delete", "environment": {}},
]

print("ABAC Evaluation Results:")
for req in requests:
    result = engine.evaluate(req)
    print(f"  {req['subject']['role']} ??? {req['action']} {req['resource']['type']}: {result['decision']} ({result['policy']})")

WooCommerce Access Control

Implement access control ?????? WooCommerce

# === WooCommerce Access Control Implementation ===

cat > woo-access-control.php << 'PHPEOF'
roles)) {
        $region = get_user_meta($user->ID, 'assigned_region', true);
        if ($region) {
            $query['meta_query'][] = array(
                'key' => '_shipping_state',
                'value' => $region,
                'compare' => '=',
            );
        }
    }
    
    // Vendors see only their own orders
    if (in_array('vendor', $user->roles)) {
        $query['meta_query'][] = array(
            'key' => '_vendor_id',
            'value' => $user->ID,
            'compare' => '=',
        );
    }
    
    return $query;
}, 10, 2);

// Restrict product visibility for vendors
add_filter('pre_get_posts', function($query) {
    if (!is_admin() || !$query->is_main_query()) return;
    
    $user = wp_get_current_user();
    if (in_array('vendor', $user->roles)) {
        $query->set('author', $user->ID);
    }
});

// Refund amount limit for support agents
add_filter('woocommerce_can_reduce_order_stock', function($can_reduce, $order) {
    $user = wp_get_current_user();
    
    if (in_array('support_agent', $user->roles)) {
        $refund_limit = get_user_meta($user->ID, 'refund_limit', true) ?: 5000;
        $order_total = $order->get_total();
        
        if ($order_total > $refund_limit) {
            return false; // Cannot refund orders above limit
        }
    }
    
    return $can_reduce;
}, 10, 2);

// Audit log for access decisions
function log_access_decision($user_id, $action, $resource, $decision) {
    global $wpdb;
    $wpdb->insert(
        $wpdb->prefix . 'access_audit_log',
        array(
            'user_id' => $user_id,
            'action' => $action,
            'resource_type' => $resource,
            'decision' => $decision,
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '',
            'timestamp' => current_time('mysql'),
        ),
        array('%d', '%s', '%s', '%s', '%s', '%s')
    );
}
PHPEOF

echo "WooCommerce access control implemented"

API Security ????????? Policy Enforcement

????????????????????? REST API ???????????? RBAC/ABAC

# === REST API Security ===

cat > api-security.php << 'PHPEOF'
roles) && $post_type === 'product') {
        if ($context === 'read' || $context === 'edit') {
            $post = get_post($object_id);
            if ($post && $post->post_author != $user->ID) {
                return false;
            }
        }
    }
    
    return $permission;
}, 10, 4);

// Rate limiting per role
add_filter('rest_pre_dispatch', function($result, $server, $request) {
    $user = wp_get_current_user();
    $role = $user->roles[0] ?? 'anonymous';
    
    $limits = array(
        'administrator' => 1000,
        'regional_manager' => 500,
        'support_agent' => 300,
        'vendor' => 200,
        'subscriber' => 50,
        'anonymous' => 20,
    );
    
    $limit = $limits[$role] ?? 20;
    $key = 'api_calls_' . $user->ID . '_' . date('YmdH');
    $calls = (int) get_transient($key);
    
    if ($calls >= $limit) {
        return new WP_Error(
            'rate_limit_exceeded',
            'API rate limit exceeded for your role',
            array('status' => 429)
        );
    }
    
    set_transient($key, $calls + 1, HOUR_IN_SECONDS);
    return $result;
}, 10, 3);
PHPEOF

# Security Headers
cat > security-headers.php << 'PHPEOF'

Monitoring ????????? Audit Logging

???????????????????????????????????????????????? access

#!/usr/bin/env python3
# access_audit.py ??? Access Control Audit Dashboard
import json
import logging
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("audit")

class AccessAuditDashboard:
    def __init__(self):
        pass
    
    def dashboard(self):
        return {
            "summary_24h": {
                "total_access_checks": 15240,
                "allowed": 14850,
                "denied": 390,
                "deny_rate_pct": 2.6,
            },
            "by_role": {
                "administrator": {"allowed": 2500, "denied": 5},
                "regional_manager": {"allowed": 4200, "denied": 120},
                "support_agent": {"allowed": 3800, "denied": 85},
                "vendor": {"allowed": 3100, "denied": 150},
                "subscriber": {"allowed": 1250, "denied": 30},
            },
            "top_denied_actions": [
                {"action": "edit_others_orders", "role": "vendor", "count": 85},
                {"action": "delete_product", "role": "support_agent", "count": 45},
                {"action": "view_reports", "role": "subscriber", "count": 30},
                {"action": "refund_over_limit", "role": "support_agent", "count": 25},
            ],
            "security_alerts": [
                {"severity": "warning", "message": "User vendor_42 attempted 15 unauthorized order accesses", "time": "14:30"},
                {"severity": "info", "message": "New role 'warehouse_staff' created", "time": "10:15"},
            ],
            "compliance": {
                "audit_log_retention": "90 days",
                "pii_access_logged": True,
                "admin_actions_logged": True,
                "failed_login_logged": True,
            },
        }

dashboard = AccessAuditDashboard()
data = dashboard.dashboard()
print("Access Control Audit Dashboard (24h):")
print(f"  Total checks: {data['summary_24h']['total_access_checks']}")
print(f"  Allowed: {data['summary_24h']['allowed']}, Denied: {data['summary_24h']['denied']}")
print(f"  Deny rate: {data['summary_24h']['deny_rate_pct']}%")

print("\nBy Role:")
for role, stats in data["by_role"].items():
    total = stats["allowed"] + stats["denied"]
    deny_pct = round(stats["denied"] / total * 100, 1) if total > 0 else 0
    print(f"  {role}: {stats['allowed']} allowed, {stats['denied']} denied ({deny_pct}%)")

print("\nTop Denied Actions:")
for item in data["top_denied_actions"][:3]:
    print(f"  {item['action']} by {item['role']}: {item['count']} times")

FAQ ??????????????????????????????????????????

Q: RBAC ????????? ABAC ??????????????????????????????????????????????????? WooCommerce?

A: ??????????????????????????????????????????????????? RBAC ?????????????????? basic role structure (admin, manager, vendor, support) ???????????? ?????????????????????????????? WordPress admin ????????? ??????????????????????????????????????? store ??????????????? ABAC ??????????????????????????????????????????????????? context-aware decisions ???????????? vendor ??????????????????????????? orders ???????????????????????????, regional manager ????????????????????? orders ???????????????????????????, support agent refund ?????????????????????????????? X ????????? ?????????????????? ???????????????????????? RBAC ???????????? (WordPress built-in) ??????????????? requirements ????????????????????????????????? ??????????????? ABAC layer ???????????? custom plugin ???????????? filter hooks

Q: WordPress Roles ????????? WooCommerce Roles ???????????????????????????????????????????

A: WordPress ?????? 5 roles ????????????????????? Administrator (???????????????????????????????????????), Editor (?????????????????? content ?????????????????????), Author (?????????????????? content ??????????????????), Contributor (??????????????? draft), Subscriber (??????????????????????????????????????????) WooCommerce ??????????????? 2 roles Shop Manager (?????????????????? orders, products, coupons, customers ?????????????????????) ????????? Customer (?????????????????????????????? ?????? order history ??????????????????) WooCommerce ??????????????? capabilities ???????????? manage_woocommerce, edit_shop_orders, read_shop_orders, publish_products, edit_products, view_woocommerce_reports ????????????????????????????????? custom roles ?????????????????? WordPress + WooCommerce capabilities ???????????????????????????????????????

Q: Multi-vendor marketplace ???????????? access control ?????????????????????????

A: Multi-vendor WooCommerce ??????????????????????????????????????????????????? Product isolation vendor ??????????????????????????????????????????????????? products ???????????????????????????, Order isolation vendor ??????????????????????????? orders ??????????????? products ???????????????????????????, Revenue isolation vendor ??????????????????????????? earnings ???????????????????????????, Customer data vendor ?????????????????????????????? customer data ????????????????????? ??????????????????????????? customers ????????????????????????????????????????????????, Settings vendor ???????????????????????????????????????????????? store settings ????????? ????????? plugins ???????????? Dokan, WCFM, WC Vendors ??????????????? vendor isolation built-in ??????????????????????????? custom ABAC ???????????? filters

Q: Audit logging ?????????????????? WooCommerce ????????????????????????????

A: ???????????? log events ??????????????? Login/logout attempts (??????????????????????????????????????????????????????), Role changes (?????????????????????????????? role ??????????????????), Order modifications (???????????????, refund, delete), Product changes (price change, stock change), Settings changes (payment, shipping, tax settings), API access (????????? access API endpoint ?????????) Plugins ???????????????????????? WP Activity Log (?????????????????????????????????????????? WooCommerce), Simple History (????????? basic logging), Stream (????????? comprehensive) ?????????????????? compliance (PCI DSS, PDPA) ???????????????????????? logs ??????????????????????????? 90 ????????? ?????????????????????????????????????????????????????? logs (immutable storage)

📖 บทความที่เกี่ยวข้อง

Text Generation WebUI RBAC ABAC Policyอ่านบทความ → Azure Container Apps RBAC ABAC Policyอ่านบทความ → Kubernetes Network Policy RBAC ABAC Policyอ่านบทความ → PostgreSQL Full Text Search RBAC ABAC Policyอ่านบทความ → Spark Structured Streaming RBAC ABAC Policyอ่านบทความ →

📚 ดูบทความทั้งหมด →