secure-token


Namesecure-token JSON
Version 1.0.0 PyPI version JSON
download
home_pageNone
SummarySecure Token System for Python
upload_time2025-09-07 18:55:01
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseMIT
keywords security token authentication encryption jwt-alternative
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ๐Ÿ” Secure Token

[![PyPI version](https://badge.fury.io/py/secure-token.svg)](https://badge.fury.io/py/secure-token)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Downloads](https://pepy.tech/badge/secure-token)](https://pepy.tech/project/secure-token)
[![Tests](https://img.shields.io/badge/tests-passing-brightgreen.svg)](https://github.com/amirhosein2004/secure-token)

A simple and secure token management library for Python applications. Generate, validate, and manage encrypted tokens with ease.

Perfect for **authentication**, **API security**, **session management**, and **microservices**.

## โœจ Key Features

- **๐Ÿ›ก๏ธ Secure**: Fernet encryption with PBKDF2 key derivation
- **โšก Fast**: Stateless design, no database required
- **๐ŸŽฏ Simple**: Easy-to-use API
- **๐Ÿ”ง Flexible**: Custom permissions and expiration times
- **๐Ÿ“ฆ Lightweight**: Minimal dependencies

## ๐Ÿ“‹ Contents

- [Installation](#-installation)
- [Quick Start](#-quick-start)
- [Core Features](#-core-features)
- [Configuration](#-configuration)
- [Error Handling](#-error-handling)
- [Documentation](#-documentation)

## ๐Ÿš€ Installation

```bash
pip install secure-token
```

## ๐Ÿ’ก Quick Start

Get up and running in seconds:

```python
from secure_token import SecureTokenManager

# Initialize the token manager
manager = SecureTokenManager()

# Generate a secure token
token = manager.generate_token(
    user_id="john_doe",
    permissions=["read", "write"],
    expires_in_hours=24
)
print(f"Generated token: {token[:50]}...")

# Validate the token
result = manager.validate_token(token)
if result['valid']:
    print(f"โœ… Welcome back, {result['user_id']}!")
    print(f"๐Ÿ”‘ Your permissions: {result['permissions']}")
    print(f"โฐ Expires at: {result['expires_at']}")
else:
    print("โŒ Invalid token")

# Check specific permission
try:
    manager.check_permission(token, "write")
    print("โœ… Write access granted!")
except PermissionDeniedError:
    print("โŒ Write access denied")
```

**Output:**
```
Generated token: gAAAAABh8J9K3L2M5N6O7P8Q9R0S1T2U3V4W5X6Y7Z8A9B...
โœ… Welcome back, john_doe!
๐Ÿ”‘ Your permissions: ['read', 'write']
โฐ Expires at: 2025-01-08 10:30:00
โœ… Write access granted!
```

## ๐ŸŽฏ Core Features

### ๐Ÿ”‘ **Token Generation**
Create secure, encrypted tokens with custom data and permissions:

```python
# Basic token (expires in 24 hours by default)
basic_token = manager.generate_token("user123")

# Token with permissions
user_token = manager.generate_token(
    user_id="regular_user",
    permissions=["read", "write"]
)

# Advanced token with custom data
admin_token = manager.generate_token(
    user_id="admin_user",
    permissions=["admin", "read", "write", "delete"],
    expires_in_hours=48,
    additional_data={
        "role": "administrator",
        "department": "IT",
        "login_ip": "192.168.1.100",
        "session_id": "sess_abc123"
    }
)

# Short-lived token for sensitive operations
sensitive_token = manager.generate_token(
    user_id="user123",
    permissions=["delete", "admin"],
    expires_in_hours=1  # Expires in 1 hour
)
```

### โœ… **Token Validation**
Validate tokens and extract user information:

```python
from secure_token import TokenExpiredError, InvalidTokenError

try:
    result = manager.validate_token(token)

    # Extract token information
    user_id = result['user_id']
    permissions = result['permissions']
    expires_at = result['expires_at']
    issued_at = result['issued_at']
    additional_data = result['additional_data']
    time_remaining = result['time_remaining']

    print(f"โœ… Valid token for user: {user_id}")
    print(f"๐Ÿ”‘ Permissions: {permissions}")
    print(f"โฐ Time remaining: {time_remaining}")
    print(f"๐Ÿ“Š Additional data: {additional_data}")

except TokenExpiredError:
    print("โŒ Token has expired - please login again")
except InvalidTokenError:
    print("โŒ Invalid token format - authentication failed")
except Exception as e:
    print(f"โŒ Token validation error: {e}")
```

### ๐Ÿ”„ **Token Refresh**
Extend token lifetime without losing data:

```python
# Refresh with default expiration (24 hours)
new_token = manager.refresh_token(old_token)

# Refresh with custom expiration
extended_token = manager.refresh_token(old_token, new_expires_in_hours=72)

# Example: Automatic token refresh in middleware
def refresh_if_needed(token):
    try:
        info = manager.get_token_info(token)
        # Refresh if less than 2 hours remaining
        remaining = info['time_remaining']
        if "1:" in remaining or "0:" in remaining:  # Less than 2 hours
            return manager.refresh_token(token, new_expires_in_hours=24)
        return token
    except TokenExpiredError:
        return None  # Token expired, need new login
```

### ๐Ÿ›ก๏ธ **Permission Checking**
Verify user permissions easily:

```python
from secure_token import PermissionDeniedError

# Check single permission
try:
    manager.check_permission(token, "admin")
    print("โœ… Admin access granted!")
except PermissionDeniedError:
    print("โŒ Admin access denied")

# Check multiple permissions
def check_multiple_permissions(token, required_permissions):
    granted = []
    denied = []

    for permission in required_permissions:
        try:
            manager.check_permission(token, permission)
            granted.append(permission)
        except PermissionDeniedError:
            denied.append(permission)

    return {"granted": granted, "denied": denied}

# Usage
result = check_multiple_permissions(token, ["read", "write", "admin"])
print(f"โœ… Granted: {result['granted']}")
print(f"โŒ Denied: {result['denied']}")
```

### ๐Ÿ“Š **Token Information**
Get comprehensive token details:

```python
info = manager.get_token_info(token)

print(f"๐Ÿ†” Token ID: {info['token_id']}")
print(f"๐Ÿ‘ค User: {info['user_id']}")
print(f"โฐ Time remaining: {info['time_remaining']}")
print(f"๐Ÿ”‘ Permissions: {info['permissions']}")
print(f"๐Ÿ“… Issued at: {info['issued_at']}")
print(f"โŒ› Expires at: {info['expires_at']}")
print(f"๐Ÿ“Š Additional data: {info['additional_data']}")
print(f"๐Ÿ”’ Is revoked: {info['is_revoked']}")

# Example: Token dashboard
def display_token_dashboard(token):
    try:
        info = manager.get_token_info(token)
        print("=" * 50)
        print("๐Ÿ” TOKEN DASHBOARD")
        print("=" * 50)
        print(f"User ID: {info['user_id']}")
        print(f"Status: {'โœ… Active' if info['valid'] else 'โŒ Invalid'}")
        print(f"Permissions: {', '.join(info['permissions'])}")
        print(f"Time Left: {info['time_remaining']}")
        print("=" * 50)
    except Exception as e:
        print(f"โŒ Error: {e}")
```

## ๐Ÿ”ง Configuration

Customize settings for your application:

```python
from secure_token import SecureTokenManager, Settings
import os

# Method 1: Environment variables (Recommended for production)
os.environ['SECRET_KEY'] = 'your-super-secret-key-here'
os.environ['DEFAULT_EXPIRATION_HOURS'] = '12'

# Method 2: Custom settings instance
settings = Settings(
    SECRET_KEY="your-super-secret-key-here",
    DEFAULT_EXPIRATION_HOURS=12,
    SALT=b"your-custom-salt-32-bytes-long!!"
)

manager = SecureTokenManager(settings_instance=settings)

# Method 3: Using .env file (create .env file in your project)
# SECRET_KEY=your-super-secret-key-here
# DEFAULT_EXPIRATION_HOURS=12
# Then load with python-dotenv:
from dotenv import load_dotenv
load_dotenv()
manager = SecureTokenManager()  # Will use environment variables

# Example: Different configurations for different environments
def create_manager_for_environment(env="development"):
    if env == "production":
        settings = Settings(
            SECRET_KEY=os.getenv("PROD_SECRET_KEY"),
            DEFAULT_EXPIRATION_HOURS=8,  # Shorter expiration for production
            SALT=os.getenv("PROD_SALT").encode()
        )
    elif env == "testing":
        settings = Settings(
            SECRET_KEY="test-key-not-for-production",
            DEFAULT_EXPIRATION_HOURS=1,  # Very short for tests
            SALT=b"test-salt-32-bytes-long-test!!"
        )
    else:  # development
        settings = Settings(
            SECRET_KEY="dev-key-change-in-production",
            DEFAULT_EXPIRATION_HOURS=24,  # Longer for development
            SALT=b"dev-salt-32-bytes-long-develop"
        )

    return SecureTokenManager(settings_instance=settings)
```


## ๐Ÿ“‹ Error Handling

Secure Token provides specific exceptions for different scenarios:

```python
from secure_token import (
    TokenError,           # Base exception
    TokenExpiredError,    # Token has expired
    InvalidTokenError,    # Invalid token format
    PermissionDeniedError # Insufficient permissions
)

try:
    result = manager.validate_token(token)
except TokenExpiredError:
    # Handle expired token
    pass
except InvalidTokenError:
    # Handle invalid token
    pass
except PermissionDeniedError:
    # Handle permission issues
    pass
```

## ๐ŸŽจ Complete Example

```python
from secure_token import SecureTokenManager
import logging

# Setup logging
logging.basicConfig(level=logging.INFO)

class AuthService:
    def __init__(self):
        self.token_manager = SecureTokenManager()

    def login(self, username: str, user_permissions: list) -> str:
        """Generate token after successful login"""
        return self.token_manager.generate_token(
            user_id=username,
            permissions=user_permissions,
            expires_in_hours=24,
            additional_data={"login_time": "2025-01-07T10:30:00"}
        )

    def verify_access(self, token: str, required_permission: str) -> bool:
        """Verify user has required permission"""
        try:
            return self.token_manager.check_permission(token, required_permission)
        except Exception:
            return False

    def get_user_info(self, token: str) -> dict:
        """Get user information from token"""
        try:
            return self.token_manager.validate_token(token)
        except Exception:
            return {"valid": False}

# Usage
auth = AuthService()
token = auth.login("john_doe", ["read", "write"])
if auth.verify_access(token, "write"):
    print("User can write!")
```

## ๐Ÿ“š Documentation

### ๐Ÿ“– Documentation Files
- **[๐Ÿ“‹ API Reference](docs/api-reference.md)** - Complete API documentation with all methods and parameters
- **[๐ŸŽ“ Tutorial Guide](docs/tutorial-guide.md)** - Step-by-step beginner's guide with examples
- **[โš™๏ธ Development Setup](docs/development-setup.md)** - Set up development environment
- **[๐Ÿงช Testing Guide](docs/testing-guide.md)** - Run tests and benchmarks
- **[๐Ÿ”ง Advanced Examples](docs/advanced-examples.md)** - Real-world examples with Flask, Django, and Python apps

### ๐ŸŒ Online Documentation
**[https://secure-token.readthedocs.io/en](https://secure-token.readthedocs.io/en/)**

## ๐Ÿค Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ”— Links

- **PyPI Package**: [https://pypi.org/project/secure-token/](https://pypi.org/project/secure-token/)
- **Source Code**: [https://github.com/amirhosein2004/secure-token](https://github.com/amirhosein2004/secure-token)
- **Documentation**: [https://secure-token.readthedocs.io/en](https://secure-token.readthedocs.io/en/)
- **Bug Reports**: [https://github.com/amirhosein2004/secure-token/issues](https://github.com/amirhosein2004/secure-token/issues)

---

**Made with โค๏ธ by [AmirHossein Babaee](https://github.com/amirhosein2004)**

*Secure Token - Because your application's security matters.*

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "secure-token",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "AmirHossein Babaee <amirhoosenbabai82@gmail.com>",
    "keywords": "security, token, authentication, encryption, jwt-alternative",
    "author": null,
    "author_email": "AmirHossein Babaee <amirhoosenbabai82@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/ee/5c/4371519f8e96283bcaf11d7b0c3ba434484a5e23dab5f1d7a02d965f7649/secure_token-1.0.0.tar.gz",
    "platform": null,
    "description": "# \ud83d\udd10 Secure Token\r\n\r\n[![PyPI version](https://badge.fury.io/py/secure-token.svg)](https://badge.fury.io/py/secure-token)\r\n[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)\r\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\r\n[![Downloads](https://pepy.tech/badge/secure-token)](https://pepy.tech/project/secure-token)\r\n[![Tests](https://img.shields.io/badge/tests-passing-brightgreen.svg)](https://github.com/amirhosein2004/secure-token)\r\n\r\nA simple and secure token management library for Python applications. Generate, validate, and manage encrypted tokens with ease.\r\n\r\nPerfect for **authentication**, **API security**, **session management**, and **microservices**.\r\n\r\n## \u2728 Key Features\r\n\r\n- **\ud83d\udee1\ufe0f Secure**: Fernet encryption with PBKDF2 key derivation\r\n- **\u26a1 Fast**: Stateless design, no database required\r\n- **\ud83c\udfaf Simple**: Easy-to-use API\r\n- **\ud83d\udd27 Flexible**: Custom permissions and expiration times\r\n- **\ud83d\udce6 Lightweight**: Minimal dependencies\r\n\r\n## \ud83d\udccb Contents\r\n\r\n- [Installation](#-installation)\r\n- [Quick Start](#-quick-start)\r\n- [Core Features](#-core-features)\r\n- [Configuration](#-configuration)\r\n- [Error Handling](#-error-handling)\r\n- [Documentation](#-documentation)\r\n\r\n## \ud83d\ude80 Installation\r\n\r\n```bash\r\npip install secure-token\r\n```\r\n\r\n## \ud83d\udca1 Quick Start\r\n\r\nGet up and running in seconds:\r\n\r\n```python\r\nfrom secure_token import SecureTokenManager\r\n\r\n# Initialize the token manager\r\nmanager = SecureTokenManager()\r\n\r\n# Generate a secure token\r\ntoken = manager.generate_token(\r\n    user_id=\"john_doe\",\r\n    permissions=[\"read\", \"write\"],\r\n    expires_in_hours=24\r\n)\r\nprint(f\"Generated token: {token[:50]}...\")\r\n\r\n# Validate the token\r\nresult = manager.validate_token(token)\r\nif result['valid']:\r\n    print(f\"\u2705 Welcome back, {result['user_id']}!\")\r\n    print(f\"\ud83d\udd11 Your permissions: {result['permissions']}\")\r\n    print(f\"\u23f0 Expires at: {result['expires_at']}\")\r\nelse:\r\n    print(\"\u274c Invalid token\")\r\n\r\n# Check specific permission\r\ntry:\r\n    manager.check_permission(token, \"write\")\r\n    print(\"\u2705 Write access granted!\")\r\nexcept PermissionDeniedError:\r\n    print(\"\u274c Write access denied\")\r\n```\r\n\r\n**Output:**\r\n```\r\nGenerated token: gAAAAABh8J9K3L2M5N6O7P8Q9R0S1T2U3V4W5X6Y7Z8A9B...\r\n\u2705 Welcome back, john_doe!\r\n\ud83d\udd11 Your permissions: ['read', 'write']\r\n\u23f0 Expires at: 2025-01-08 10:30:00\r\n\u2705 Write access granted!\r\n```\r\n\r\n## \ud83c\udfaf Core Features\r\n\r\n### \ud83d\udd11 **Token Generation**\r\nCreate secure, encrypted tokens with custom data and permissions:\r\n\r\n```python\r\n# Basic token (expires in 24 hours by default)\r\nbasic_token = manager.generate_token(\"user123\")\r\n\r\n# Token with permissions\r\nuser_token = manager.generate_token(\r\n    user_id=\"regular_user\",\r\n    permissions=[\"read\", \"write\"]\r\n)\r\n\r\n# Advanced token with custom data\r\nadmin_token = manager.generate_token(\r\n    user_id=\"admin_user\",\r\n    permissions=[\"admin\", \"read\", \"write\", \"delete\"],\r\n    expires_in_hours=48,\r\n    additional_data={\r\n        \"role\": \"administrator\",\r\n        \"department\": \"IT\",\r\n        \"login_ip\": \"192.168.1.100\",\r\n        \"session_id\": \"sess_abc123\"\r\n    }\r\n)\r\n\r\n# Short-lived token for sensitive operations\r\nsensitive_token = manager.generate_token(\r\n    user_id=\"user123\",\r\n    permissions=[\"delete\", \"admin\"],\r\n    expires_in_hours=1  # Expires in 1 hour\r\n)\r\n```\r\n\r\n### \u2705 **Token Validation**\r\nValidate tokens and extract user information:\r\n\r\n```python\r\nfrom secure_token import TokenExpiredError, InvalidTokenError\r\n\r\ntry:\r\n    result = manager.validate_token(token)\r\n\r\n    # Extract token information\r\n    user_id = result['user_id']\r\n    permissions = result['permissions']\r\n    expires_at = result['expires_at']\r\n    issued_at = result['issued_at']\r\n    additional_data = result['additional_data']\r\n    time_remaining = result['time_remaining']\r\n\r\n    print(f\"\u2705 Valid token for user: {user_id}\")\r\n    print(f\"\ud83d\udd11 Permissions: {permissions}\")\r\n    print(f\"\u23f0 Time remaining: {time_remaining}\")\r\n    print(f\"\ud83d\udcca Additional data: {additional_data}\")\r\n\r\nexcept TokenExpiredError:\r\n    print(\"\u274c Token has expired - please login again\")\r\nexcept InvalidTokenError:\r\n    print(\"\u274c Invalid token format - authentication failed\")\r\nexcept Exception as e:\r\n    print(f\"\u274c Token validation error: {e}\")\r\n```\r\n\r\n### \ud83d\udd04 **Token Refresh**\r\nExtend token lifetime without losing data:\r\n\r\n```python\r\n# Refresh with default expiration (24 hours)\r\nnew_token = manager.refresh_token(old_token)\r\n\r\n# Refresh with custom expiration\r\nextended_token = manager.refresh_token(old_token, new_expires_in_hours=72)\r\n\r\n# Example: Automatic token refresh in middleware\r\ndef refresh_if_needed(token):\r\n    try:\r\n        info = manager.get_token_info(token)\r\n        # Refresh if less than 2 hours remaining\r\n        remaining = info['time_remaining']\r\n        if \"1:\" in remaining or \"0:\" in remaining:  # Less than 2 hours\r\n            return manager.refresh_token(token, new_expires_in_hours=24)\r\n        return token\r\n    except TokenExpiredError:\r\n        return None  # Token expired, need new login\r\n```\r\n\r\n### \ud83d\udee1\ufe0f **Permission Checking**\r\nVerify user permissions easily:\r\n\r\n```python\r\nfrom secure_token import PermissionDeniedError\r\n\r\n# Check single permission\r\ntry:\r\n    manager.check_permission(token, \"admin\")\r\n    print(\"\u2705 Admin access granted!\")\r\nexcept PermissionDeniedError:\r\n    print(\"\u274c Admin access denied\")\r\n\r\n# Check multiple permissions\r\ndef check_multiple_permissions(token, required_permissions):\r\n    granted = []\r\n    denied = []\r\n\r\n    for permission in required_permissions:\r\n        try:\r\n            manager.check_permission(token, permission)\r\n            granted.append(permission)\r\n        except PermissionDeniedError:\r\n            denied.append(permission)\r\n\r\n    return {\"granted\": granted, \"denied\": denied}\r\n\r\n# Usage\r\nresult = check_multiple_permissions(token, [\"read\", \"write\", \"admin\"])\r\nprint(f\"\u2705 Granted: {result['granted']}\")\r\nprint(f\"\u274c Denied: {result['denied']}\")\r\n```\r\n\r\n### \ud83d\udcca **Token Information**\r\nGet comprehensive token details:\r\n\r\n```python\r\ninfo = manager.get_token_info(token)\r\n\r\nprint(f\"\ud83c\udd94 Token ID: {info['token_id']}\")\r\nprint(f\"\ud83d\udc64 User: {info['user_id']}\")\r\nprint(f\"\u23f0 Time remaining: {info['time_remaining']}\")\r\nprint(f\"\ud83d\udd11 Permissions: {info['permissions']}\")\r\nprint(f\"\ud83d\udcc5 Issued at: {info['issued_at']}\")\r\nprint(f\"\u231b Expires at: {info['expires_at']}\")\r\nprint(f\"\ud83d\udcca Additional data: {info['additional_data']}\")\r\nprint(f\"\ud83d\udd12 Is revoked: {info['is_revoked']}\")\r\n\r\n# Example: Token dashboard\r\ndef display_token_dashboard(token):\r\n    try:\r\n        info = manager.get_token_info(token)\r\n        print(\"=\" * 50)\r\n        print(\"\ud83d\udd10 TOKEN DASHBOARD\")\r\n        print(\"=\" * 50)\r\n        print(f\"User ID: {info['user_id']}\")\r\n        print(f\"Status: {'\u2705 Active' if info['valid'] else '\u274c Invalid'}\")\r\n        print(f\"Permissions: {', '.join(info['permissions'])}\")\r\n        print(f\"Time Left: {info['time_remaining']}\")\r\n        print(\"=\" * 50)\r\n    except Exception as e:\r\n        print(f\"\u274c Error: {e}\")\r\n```\r\n\r\n## \ud83d\udd27 Configuration\r\n\r\nCustomize settings for your application:\r\n\r\n```python\r\nfrom secure_token import SecureTokenManager, Settings\r\nimport os\r\n\r\n# Method 1: Environment variables (Recommended for production)\r\nos.environ['SECRET_KEY'] = 'your-super-secret-key-here'\r\nos.environ['DEFAULT_EXPIRATION_HOURS'] = '12'\r\n\r\n# Method 2: Custom settings instance\r\nsettings = Settings(\r\n    SECRET_KEY=\"your-super-secret-key-here\",\r\n    DEFAULT_EXPIRATION_HOURS=12,\r\n    SALT=b\"your-custom-salt-32-bytes-long!!\"\r\n)\r\n\r\nmanager = SecureTokenManager(settings_instance=settings)\r\n\r\n# Method 3: Using .env file (create .env file in your project)\r\n# SECRET_KEY=your-super-secret-key-here\r\n# DEFAULT_EXPIRATION_HOURS=12\r\n# Then load with python-dotenv:\r\nfrom dotenv import load_dotenv\r\nload_dotenv()\r\nmanager = SecureTokenManager()  # Will use environment variables\r\n\r\n# Example: Different configurations for different environments\r\ndef create_manager_for_environment(env=\"development\"):\r\n    if env == \"production\":\r\n        settings = Settings(\r\n            SECRET_KEY=os.getenv(\"PROD_SECRET_KEY\"),\r\n            DEFAULT_EXPIRATION_HOURS=8,  # Shorter expiration for production\r\n            SALT=os.getenv(\"PROD_SALT\").encode()\r\n        )\r\n    elif env == \"testing\":\r\n        settings = Settings(\r\n            SECRET_KEY=\"test-key-not-for-production\",\r\n            DEFAULT_EXPIRATION_HOURS=1,  # Very short for tests\r\n            SALT=b\"test-salt-32-bytes-long-test!!\"\r\n        )\r\n    else:  # development\r\n        settings = Settings(\r\n            SECRET_KEY=\"dev-key-change-in-production\",\r\n            DEFAULT_EXPIRATION_HOURS=24,  # Longer for development\r\n            SALT=b\"dev-salt-32-bytes-long-develop\"\r\n        )\r\n\r\n    return SecureTokenManager(settings_instance=settings)\r\n```\r\n\r\n\r\n## \ud83d\udccb Error Handling\r\n\r\nSecure Token provides specific exceptions for different scenarios:\r\n\r\n```python\r\nfrom secure_token import (\r\n    TokenError,           # Base exception\r\n    TokenExpiredError,    # Token has expired\r\n    InvalidTokenError,    # Invalid token format\r\n    PermissionDeniedError # Insufficient permissions\r\n)\r\n\r\ntry:\r\n    result = manager.validate_token(token)\r\nexcept TokenExpiredError:\r\n    # Handle expired token\r\n    pass\r\nexcept InvalidTokenError:\r\n    # Handle invalid token\r\n    pass\r\nexcept PermissionDeniedError:\r\n    # Handle permission issues\r\n    pass\r\n```\r\n\r\n## \ud83c\udfa8 Complete Example\r\n\r\n```python\r\nfrom secure_token import SecureTokenManager\r\nimport logging\r\n\r\n# Setup logging\r\nlogging.basicConfig(level=logging.INFO)\r\n\r\nclass AuthService:\r\n    def __init__(self):\r\n        self.token_manager = SecureTokenManager()\r\n\r\n    def login(self, username: str, user_permissions: list) -> str:\r\n        \"\"\"Generate token after successful login\"\"\"\r\n        return self.token_manager.generate_token(\r\n            user_id=username,\r\n            permissions=user_permissions,\r\n            expires_in_hours=24,\r\n            additional_data={\"login_time\": \"2025-01-07T10:30:00\"}\r\n        )\r\n\r\n    def verify_access(self, token: str, required_permission: str) -> bool:\r\n        \"\"\"Verify user has required permission\"\"\"\r\n        try:\r\n            return self.token_manager.check_permission(token, required_permission)\r\n        except Exception:\r\n            return False\r\n\r\n    def get_user_info(self, token: str) -> dict:\r\n        \"\"\"Get user information from token\"\"\"\r\n        try:\r\n            return self.token_manager.validate_token(token)\r\n        except Exception:\r\n            return {\"valid\": False}\r\n\r\n# Usage\r\nauth = AuthService()\r\ntoken = auth.login(\"john_doe\", [\"read\", \"write\"])\r\nif auth.verify_access(token, \"write\"):\r\n    print(\"User can write!\")\r\n```\r\n\r\n## \ud83d\udcda Documentation\r\n\r\n### \ud83d\udcd6 Documentation Files\r\n- **[\ud83d\udccb API Reference](docs/api-reference.md)** - Complete API documentation with all methods and parameters\r\n- **[\ud83c\udf93 Tutorial Guide](docs/tutorial-guide.md)** - Step-by-step beginner's guide with examples\r\n- **[\u2699\ufe0f Development Setup](docs/development-setup.md)** - Set up development environment\r\n- **[\ud83e\uddea Testing Guide](docs/testing-guide.md)** - Run tests and benchmarks\r\n- **[\ud83d\udd27 Advanced Examples](docs/advanced-examples.md)** - Real-world examples with Flask, Django, and Python apps\r\n\r\n### \ud83c\udf10 Online Documentation\r\n**[https://secure-token.readthedocs.io/en](https://secure-token.readthedocs.io/en/)**\r\n\r\n## \ud83e\udd1d Contributing\r\n\r\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\r\n\r\n## \ud83d\udcc4 License\r\n\r\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\r\n\r\n## \ud83d\udd17 Links\r\n\r\n- **PyPI Package**: [https://pypi.org/project/secure-token/](https://pypi.org/project/secure-token/)\r\n- **Source Code**: [https://github.com/amirhosein2004/secure-token](https://github.com/amirhosein2004/secure-token)\r\n- **Documentation**: [https://secure-token.readthedocs.io/en](https://secure-token.readthedocs.io/en/)\r\n- **Bug Reports**: [https://github.com/amirhosein2004/secure-token/issues](https://github.com/amirhosein2004/secure-token/issues)\r\n\r\n---\r\n\r\n**Made with \u2764\ufe0f by [AmirHossein Babaee](https://github.com/amirhosein2004)**\r\n\r\n*Secure Token - Because your application's security matters.*\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Secure Token System for Python",
    "version": "1.0.0",
    "project_urls": {
        "Bug Tracker": "https://github.com/amirhosein2004/secure-token/issues",
        "Changelog": "https://github.com/amirhosein2004/secure-token/blob/main/CHANGELOG.md",
        "Documentation": "https://secure-token.readthedocs.io",
        "Homepage": "https://github.com/amirhosein2004/secure-token",
        "Repository": "https://github.com/amirhosein2004/secure-token.git"
    },
    "split_keywords": [
        "security",
        " token",
        " authentication",
        " encryption",
        " jwt-alternative"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "6ea6f0e240cf772dd2a4fae73e4a57d0240e2c10035cb135afadedac5e8b64a3",
                "md5": "d60dd7f0793a0a264338434b2f909015",
                "sha256": "6941476edb6f6802e566cb1e928d0d7fa0e7aca8840512756d86e5f873117d04"
            },
            "downloads": -1,
            "filename": "secure_token-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d60dd7f0793a0a264338434b2f909015",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 13363,
            "upload_time": "2025-09-07T18:54:58",
            "upload_time_iso_8601": "2025-09-07T18:54:58.907525Z",
            "url": "https://files.pythonhosted.org/packages/6e/a6/f0e240cf772dd2a4fae73e4a57d0240e2c10035cb135afadedac5e8b64a3/secure_token-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "ee5c4371519f8e96283bcaf11d7b0c3ba434484a5e23dab5f1d7a02d965f7649",
                "md5": "731b8427606133685417ae7eda584b01",
                "sha256": "85df0f25a82f27d6431c00b0e7fd18900d3a16966d1f17ae09219b91cbbc57ad"
            },
            "downloads": -1,
            "filename": "secure_token-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "731b8427606133685417ae7eda584b01",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 20647,
            "upload_time": "2025-09-07T18:55:01",
            "upload_time_iso_8601": "2025-09-07T18:55:01.192666Z",
            "url": "https://files.pythonhosted.org/packages/ee/5c/4371519f8e96283bcaf11d7b0c3ba434484a5e23dab5f1d7a02d965f7649/secure_token-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-09-07 18:55:01",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "amirhosein2004",
    "github_project": "secure-token",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "secure-token"
}
        
Elapsed time: 1.47834s