DEV Community

Siswoyo Siswoyo
Siswoyo Siswoyo

Posted on

Clean Code Principle: Avoid Using Local Storage for Segregation of Duties (SOD)

Don't: Put SOD (Segregation of Duties) in Local Storage

When developing applications, especially for enterprise systems or anything that involves user permissions and access control, Segregation of Duties (SOD) is a critical security and compliance concept. It ensures no single user has excessive power that could lead to fraud or misuse of data.

Example of bad practice:

// don't do this
localStorage.setItem("userRole", "admin");
if (localStorage.getItem("userRole") === "admin") {
    // allow
}
Enter fullscreen mode Exit fullscreen mode

Why This is a Problem

1. Insecure by Design: Local storage is fully accessible by the browser. Anyone with access to DevTools can change the value:

   localStorage.setItem("userRole", "admin");
Enter fullscreen mode Exit fullscreen mode

2. Easy to Manipulate:
A malicious user can bypass role checks by editing stored values, granting themselves unauthorized access.

3. Violates Clean Code & Security Principles:

  • Clean code separates business logic and authorization logic from the frontend.

  • Authorization decisions should come from a trusted backend, not a tamperable frontend.

Do This Instead: Backed-Driven Role Enforcement

All SOD checks should happen on the server side. The frontend should only act based on permissions securely sent from the backend, usually via a token (e.g., JWT) or a secure API call.

Example:

// Frontend (React, vue, etc.)
fetch("/api/user/permisions")
   .then(res => res.json())
   .then(data => {
     if (data.canApproveOrders) {
     // show approve button
     }
   });
Enter fullscreen mode Exit fullscreen mode

Backend (e.g., FastAPI, Spring Boot):

@router.get("/user/permissions")
def get_permissions(user: User = Depends(get_current_user)):
    return {
        "canApproveOrders": user.role == "role_manager"
    }
Enter fullscreen mode Exit fullscreen mode

Best Practices Summary

Principle Best Practice
Authorization Handle on the backend
Security Never trust client-side data for access control
Clean Code Keep responsibilities well-separated
Audit & Compliance Ensure traceability via server logs, not browser data

Top comments (0)