User Admin: Role-Based Access Control
Description
This Python script demonstrates a simplified user admin system with role-based access control. Users are categorized by roles (admin, editor, viewer) with varying permissions.
Code Snippet
import json
users = {
"admin": {"username": "admin", "password": "admin123", "role": "admin"},
"editor": {"username": "editor", "password": "editor123", "role": "editor"},
"viewer": {"username": "viewer", "password": "viewer123", "role": "viewer"}
}
def authenticate(username, password):
user = users.get(username)
if user and user["password"] == password:
return user["role"]
return None
def check_permission(role, action):
permissions = {
"admin": ["create", "read", "update", "delete"],
"editor": ["read", "update"],
"viewer": ["read"]
}
return action in permissions.get(role, [])
username = input("Enter username: ")
password = input("Enter password: ")
role = authenticate(username, password)
if role:
print(f"Logged in as {role}")
action = input("Enter action (create, read, update, delete): ")
if check_permission(role, action):
print(f"Permission granted for {action}")
else:
print(f"Permission denied for {action}")
else:
print("Authentication failed")