# change_history

change_time: 2026-03-06 15:56:14.144385
status: pending
changes:
新增 4 条功能需求：
  + [7] 创建权限 (create_permission)
  + [8] 查询权限 (read_permission)
  + [9] 更新权限 (update_permission)
  + [10] 删除权限 (delete_permission)


# code_files

file_name: create_user.py
file_path: output/first_project/user_management/create_user.py
module: user_management
language: python
generated_at: 2026-03-06 15:45:20.182945
content:
import re

class UserCreationError(Exception):
    """Custom exception for user creation errors."""
    pass

def create_user(user_info):
    """
    Validates user information and creates a user, returning the user ID.

    Parameters:
    user_info (dict): A dictionary containing user information such as name, email, and password.

    Returns:
    int: The unique identifier of the newly created user on success.
    int: An error code indicating the reason for failure on failure.
    """
    # Basic validation of user_info
    if not isinstance(user_info, dict):
        raise UserCreationError("Invalid input: user_info must be a dictionary.")
    
    required_fields = ['name', 'email', 'password']
    for field in required_fields:
        if field not in user_info:
            raise UserCreationError(f"Missing required field: {field}")

    # Validate email format
    if not re.match(r"[^@]+@[^@]+\.[^@]+", user_info['email']):
        raise UserCreationError("Invalid email format.")

    # Validate password length
    if len(user_info['password']) < 6:
        raise UserCreationError("Password must be at least 6 characters long.")

    # Simulate user creation and return a user ID
    # In a real-world scenario, this would involve database operations
    user_id = hash(user_info['email']) % 10000  # Simplified user ID generation

    return user_id

# Example usage:
# try:
#     user_id = create_user({'name': 'John Doe', 'email': 'john.doe@example.com', 'password': 'secure123'})
#     print(f"User created with ID: {user_id}")
# except UserCreationError as e:
#     print(f"Error creating user: {e}")


file_name: authenticate_user.py
file_path: output/first_project/user_auth/authenticate_user.py
module: user_auth
language: python
generated_at: 2026-03-06 15:45:20.188922
content:
import hashlib
import jwt
import datetime

# Mock database for demonstration purposes
USER_DATABASE = {
    "test_user": {
        "password_hash": hashlib.sha256("secure_password".encode()).hexdigest(),
        "user_id": 1
    }
}

SECRET_KEY = "your_secret_key"

def authenticate_user(username: str, password: str) -> dict:
    """
    Validates user credentials (e.g., username and password) and returns authentication result and token.

    Args:
        username (str): The username of the user attempting to authenticate.
        password (str): The password of the user attempting to authenticate.

    Returns:
        dict: On success, returns a dictionary containing:
            - authenticated (bool): True if authentication is successful.
            - token (str): A JWT token for the authenticated user.
              Example: {"authenticated": True, "token": "jwt_token"}
        On failure, returns a dictionary containing:
            - error_code (int): An error code indicating the type of failure.
            - error_message (str): A descriptive error message.
              Example: {"error_code": 401, "error_message": "Invalid username or password."}
    """
    # Validate input parameters
    if not isinstance(username, str) or not username.strip():
        return {"error_code": 400, "error_message": "Invalid username format."}
    if not isinstance(password, str) or not password.strip():
        return {"error_code": 400, "error_message": "Invalid password format."}

    # Check if the user exists in the database
    user_data = USER_DATABASE.get(username)
    if not user_data:
        return {"error_code": 401, "error_message": "Invalid username or password."}

    # Verify the password
    password_hash = hashlib.sha256(password.encode()).hexdigest()
    if password_hash != user_data["password_hash"]:
        return {"error_code": 401, "error_message": "Invalid username or password."}

    # Generate a JWT token
    try:
        payload = {
            "user_id": user_data["user_id"],
            "username": username,
            "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1)
        }
        token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
    except Exception as e:
        return {"error_code": 500, "error_message": f"Token generation failed: {str(e)}"}

    # Return success response
    return {"authenticated": True, "token": token}


file_name: validate_user_info.py
file_path: output/first_project/user_management/validate_user_info.py
module: user_management
language: python
generated_at: 2026-03-06 15:45:20.193350
content:
import re


def validate_user_info(username: str, password: str, email: str, age: int = None) -> bool:
    """
    Validates the user registration input for compliance with requirements.

    Args:
        username (str): The username provided by the user.
        password (str): The password provided by the user.
        email (str): The email address provided by the user.
        age (int, optional): The age of the user, if provided.

    Returns:
        bool: True if the user information is valid, False otherwise.
    """
    # Validate username: must be between 3 and 20 characters and alphanumeric
    if not isinstance(username, str) or not (3 <= len(username) <= 20) or not username.isalnum():
        return False

    # Validate password: must be at least 8 characters, contain at least one uppercase letter,
    # one lowercase letter, one digit, and one special character
    if not isinstance(password, str) or len(password) < 8:
        return False
    if not re.search(r'[A-Z]', password):
        return False
    if not re.search(r'[a-z]', password):
        return False
    if not re.search(r'[0-9]', password):
        return False
    if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
        return False

    # Validate email: must follow a valid email format
    email_regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
    if not isinstance(email, str) or not re.match(email_regex, email):
        return False

    # Validate age: must be a positive integer if provided
    if age is not None:
        if not isinstance(age, int) or age <= 0:
            return False

    return True


file_name: generate_token.py
file_path: output/first_project/user_auth/generate_token.py
module: user_auth
language: python
generated_at: 2026-03-06 15:45:20.198139
content:
import jwt
import datetime
from typing import Union

def generate_token(user_credentials: dict, expiration_time: int = 3600) -> str:
    """
    Generates an access token based on user authentication information.

    Args:
        user_credentials (dict): A dictionary containing user authentication information such as username and password.
        expiration_time (int, optional): Optional expiration time for the generated token in seconds. Defaults to 3600 seconds (1 hour).

    Returns:
        str: The generated access token on success, or an error message on failure.
    """
    # Secret key for signing the token (in a real application, store this securely)
    SECRET_KEY = "your_secret_key"

    # Validate input parameters
    if not isinstance(user_credentials, dict):
        return "Error: user_credentials must be a dictionary."
    if "username" not in user_credentials or "password" not in user_credentials:
        return "Error: user_credentials must contain 'username' and 'password'."
    if not isinstance(expiration_time, int) or expiration_time <= 0:
        return "Error: expiration_time must be a positive integer."

    try:
        # Simulate user authentication (replace with actual authentication logic)
        username = user_credentials.get("username")
        password = user_credentials.get("password")
        if username != "valid_user" or password != "valid_password":
            return "Error: Invalid username or password."

        # Generate token payload
        payload = {
            "username": username,
            "exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=expiration_time)
        }

        # Generate JWT token
        token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
        return token
    except Exception as e:
        return f"Error: Failed to generate token. {str(e)}"


file_name: encrypt_password.py
file_path: output/first_project/security/encrypt_password.py
module: security
language: python
generated_at: 2026-03-06 15:45:20.202770
content:
import hashlib
import base64

def encrypt_password(password):
    """
    Encrypts a user's password for secure storage.

    Args:
        password (str): The plain text password to be encrypted.

    Returns:
        str: The encrypted version of the input password on success.
        str: An error message indicating why the encryption failed on failure.
    """
    if not isinstance(password, str):
        return "Error: Password must be a string."
    
    if not password:
        return "Error: Password cannot be empty."
    
    try:
        # Hash the password using SHA-256
        sha256_hash = hashlib.sha256(password.encode('utf-8')).digest()
        # Encode the hash using Base64 for storage
        encrypted_password = base64.b64encode(sha256_hash).decode('utf-8')
        return encrypted_password
    except Exception as e:
        return f"Error: Failed to encrypt password. Details: {str(e)}"


file_name: validate_token.py
file_path: output/first_project/user_auth/validate_token.py
module: user_auth
language: python
generated_at: 2026-03-06 15:45:20.207530
content:
import jwt
from jwt.exceptions import ExpiredSignatureError, InvalidTokenError

def validate_token(token, request_context=None):
    """
    Validates the token provided in the user request.

    Args:
        token (str): The token provided by the user for validation.
        request_context (dict, optional): Additional context about the user request, 
                                          such as headers or metadata.

    Returns:
        bool: True if the token is valid, False otherwise.
    """
    # Define a secret key and algorithm for decoding the token
    SECRET_KEY = "your_secret_key"
    ALGORITHM = "HS256"

    # Validate input parameters
    if not isinstance(token, str) or not token.strip():
        raise ValueError("The token must be a non-empty string.")

    if request_context is not None and not isinstance(request_context, dict):
        raise ValueError("The request_context must be a dictionary if provided.")

    try:
        # Decode the token
        decoded_token = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        
        # Perform additional validation if needed (e.g., check claims)
        # Example: Ensure the token contains a specific claim
        if "user_id" not in decoded_token:
            return False

        return True
    except ExpiredSignatureError:
        # Token has expired
        return False
    except InvalidTokenError:
        # Token is invalid
        return False
    except Exception as e:
        # Handle unexpected errors
        raise RuntimeError(f"An unexpected error occurred during token validation: {e}") from e


file_name: create_permission.py
file_path: output/first_project/permission_management/create_permission.py
module: permission_management
language: python
generated_at: 2026-03-06 15:56:38.080687
content:
from typing import Union, Dict

class Permission:
    """
    A mock Permission class representing a database model for permissions.
    """
    def __init__(self, name: str, description: str = ""):
        self.name = name
        self.description = description

    def save(self):
        """
        Simulates saving the permission object to a database.
        """
        # In a real implementation, this would interact with a database.
        # For this example, we assume the save operation is always successful.
        return True

def create_permission(name: str, description: str = "") -> Union[Dict[str, str], Permission]:
    """
    Creates a new permission record with the given name and description, and saves it to the database.

    Args:
        name (str): The name of the permission to be created. Required.
        description (str): A brief description of the permission. Optional.

    Returns:
        Union[Dict[str, str], Permission]: 
            - On success: The created Permission object.
            - On failure: A dictionary containing error details.
    """
    # Validate input parameters
    if not isinstance(name, str) or not name.strip():
        return {"error": "Invalid 'name' parameter. It must be a non-empty string."}
    if not isinstance(description, str):
        return {"error": "Invalid 'description' parameter. It must be a string."}

    try:
        # Create a new Permission object
        permission = Permission(name=name.strip(), description=description.strip())

        # Save the permission to the database
        if permission.save():
            return permission
        else:
            return {"error": "Failed to save the permission to the database."}
    except Exception as e:
        # Handle unexpected errors
        return {"error": f"An unexpected error occurred: {str(e)}"}


file_name: read_permission.py
file_path: output/first_project/permission_management/read_permission.py
module: permission_management
language: python
generated_at: 2026-03-06 15:56:38.087337
content:
from typing import List, Union, Dict, Optional


def read_permission(
    permission_id: Optional[int] = None,
    filters: Optional[Dict] = None,
    include_details: bool = False
) -> Union[List[Dict], Dict]:
    """
    Retrieve a list of permissions or details of a specific permission based on given criteria.

    Args:
        permission_id (Optional[int]): The unique identifier of the permission to retrieve details for.
        filters (Optional[Dict]): A dictionary of filter criteria to query the permissions list.
        include_details (bool): Whether to include detailed information for each permission in the list.

    Returns:
        Union[List[Dict], Dict]: 
            - A list of permissions or a single permission object if `permission_id` is provided.
            - An error object or message in case of failure.

    Raises:
        ValueError: If both `permission_id` and `filters` are None.
        TypeError: If the input types are invalid.
    """
    # Mock database of permissions for demonstration purposes
    permissions_db = [
        {"id": 1, "name": "read", "description": "Read access", "details": {"scope": "global"}},
        {"id": 2, "name": "write", "description": "Write access", "details": {"scope": "global"}},
        {"id": 3, "name": "delete", "description": "Delete access", "details": {"scope": "restricted"}},
    ]

    try:
        # Validate input types
        if permission_id is not None and not isinstance(permission_id, int):
            raise TypeError("`permission_id` must be an integer.")
        if filters is not None and not isinstance(filters, dict):
            raise TypeError("`filters` must be a dictionary.")
        if not isinstance(include_details, bool):
            raise TypeError("`include_details` must be a boolean.")

        # If permission_id is provided, retrieve the specific permission
        if permission_id is not None:
            for permission in permissions_db:
                if permission["id"] == permission_id:
                    return permission if include_details else {k: v for k, v in permission.items() if k != "details"}
            return {"error": f"Permission with id {permission_id} not found."}

        # If filters are provided, filter the permissions list
        if filters:
            filtered_permissions = [
                permission for permission in permissions_db
                if all(permission.get(key) == value for key, value in filters.items())
            ]
        else:
            filtered_permissions = permissions_db

        # Include or exclude details based on the `include_details` flag
        if not include_details:
            for permission in filtered_permissions:
                permission.pop("details", None)

        return filtered_permissions

    except Exception as e:
        return {"error": str(e)}


file_name: update_permission.py
file_path: output/first_project/permission_management/update_permission.py
module: permission_management
language: python
generated_at: 2026-03-06 15:56:38.092687
content:
def update_permission(permission_id, name=None, description=None, metadata=None):
    """
    Update the name, description, or other details of an existing permission and save the changes.

    Args:
        permission_id (int): The unique identifier of the permission to be updated.
        name (str, optional): The new name for the permission.
        description (str, optional): The new description for the permission.
        metadata (dict, optional): Additional metadata or attributes to update for the permission.

    Returns:
        dict: On success, returns the updated permission object containing the new details.
              On failure, returns an error message describing why the update failed.

    Raises:
        ValueError: If permission_id is not a valid integer or if required fields are missing.
    """
    # Simulated database of permissions (for demonstration purposes)
    permissions_db = {
        1: {"name": "Read Access", "description": "Allows read access to resources", "metadata": {}},
        2: {"name": "Write Access", "description": "Allows write access to resources", "metadata": {}},
    }

    # Validate permission_id
    if not isinstance(permission_id, int) or permission_id <= 0:
        raise ValueError("Invalid permission_id. It must be a positive integer.")

    # Check if the permission exists
    if permission_id not in permissions_db:
        return {"error_message": f"Permission with ID {permission_id} does not exist."}

    # Retrieve the existing permission
    permission = permissions_db[permission_id]

    # Update the permission details
    if name is not None:
        if not isinstance(name, str) or not name.strip():
            return {"error_message": "Invalid name. It must be a non-empty string."}
        permission["name"] = name.strip()

    if description is not None:
        if not isinstance(description, str) or not description.strip():
            return {"error_message": "Invalid description. It must be a non-empty string."}
        permission["description"] = description.strip()

    if metadata is not None:
        if not isinstance(metadata, dict):
            return {"error_message": "Invalid metadata. It must be a dictionary."}
        permission["metadata"].update(metadata)

    # Save the updated permission back to the database
    permissions_db[permission_id] = permission

    # Return the updated permission object
    return {"updated_permission": permission}


file_name: delete_permission.py
file_path: output/first_project/permission_management/delete_permission.py
module: permission_management
language: python
generated_at: 2026-03-06 15:56:38.097489
content:
from typing import Dict, Union

def delete_permission(permission_id: int) -> Dict[str, Union[str, int]]:
    """
    Deletes a specific permission record based on the permission ID.

    Args:
        permission_id (int): The unique identifier of the permission to be deleted.

    Returns:
        dict: A dictionary indicating the result of the operation.
              On success: {"status": "success"}
              On failure: {"status": "error", "message": "Error message"}
    """
    # Simulated database of permissions (for demonstration purposes)
    permissions_db = {
        1: {"name": "read", "description": "Read access"},
        2: {"name": "write", "description": "Write access"},
        3: {"name": "delete", "description": "Delete access"}
    }

    # Validate the input parameter
    if not isinstance(permission_id, int):
        return {"status": "error", "message": "Invalid permission_id. Must be an integer."}

    # Check if the permission ID exists in the database
    if permission_id not in permissions_db:
        return {"status": "error", "message": f"Permission with ID {permission_id} does not exist."}

    # Perform the deletion
    try:
        del permissions_db[permission_id]
        return {"status": "success"}
    except Exception as e:
        return {"status": "error", "message": f"An error occurred while deleting the permission: {str(e)}"}


