đ Python Code Examples
import requests
import hashlib
import socket
import platform
import uuid
import json
import sys
API_KEY = "your-api-key-here"
API_URL = "http://your-domain.com/api/license/auth"
PRODUCT = "MyPythonApp"
VERSION = "1.0.0"
class TKIAuth:
@staticmethod
def get_hwid():
"""Generate hardware ID based on system information"""
try:
# Get MAC address
mac = hex(uuid.getnode())[2:].upper()
# Get system info
system_info = f"{platform.machine()}-{platform.processor()}-{mac}"
# Create hash
hwid = hashlib.md5(system_info.encode()).hexdigest()[:16]
return f"PY-{hwid}"
except Exception:
# Fallback HWID
return f"PY-FALLBACK-{hash(platform.node()) % 1000000}"
@staticmethod
def get_local_ip():
"""Get local IP address"""
try:
# Connect to a remote server to determine local IP
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
except Exception:
return "127.0.0.1"
@staticmethod
def authenticate(license_key):
"""Authenticate license with TKI Auth API"""
try:
payload = {
"data": {
"product": PRODUCT,
"version": VERSION,
"licensekey": license_key,
"ip": TKIAuth.get_local_ip(),
"hwid": TKIAuth.get_hwid()
}
}
headers = {
"Content-Type": "application/json",
"Authorization": API_KEY
}
response = requests.post(
API_URL,
json=payload,
headers=headers,
timeout=30
)
if response.status_code == 200:
data = response.json()
if data.get("status_overview") == "success":
print("â License authenticated!")
print(f"User: {data.get('discord_username', 'Unknown')}")
print(f"Expires: {data.get('expire_date', 'Unknown')}")
print(f"Staff License: {data.get('staff_license', False)}")
return True
else:
print(f"â Authentication failed: {data.get('message', 'Unknown error')}")
else:
print(f"â HTTP Error: {response.status_code}")
except requests.RequestException as e:
print(f"â Network error: {e}")
except json.JSONDecodeError:
print("â Invalid response format")
except Exception as e:
print(f"â Error: {e}")
return False
def main():
"""Main application entry point"""
license_key = input("Enter license key: ").strip()
if TKIAuth.authenticate(license_key):
print("Starting application...")
# Your application logic here
else:
print("Authentication failed!")
sys.exit(1)
if __name__ == "__main__":
main()
Advanced Python Implementationâ
import requests
import hashlib
import platform
import uuid
import json
import time
import threading
from typing import Optional, Dict, Any
from dataclasses import dataclass
from contextlib import contextmanager
API_KEY = "your-api-key-here"
API_URL = "http://your-domain.com/api/license/auth"
PRODUCT = "MyAdvancedPyApp"
VERSION = "1.0.0"
@dataclass
class LicenseInfo:
discord_username: str
discord_tag: str
discord_id: str
expire_date: str
version: str
staff_license: bool
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'LicenseInfo':
return cls(
discord_username=data.get('discord_username', ''),
discord_tag=data.get('discord_tag', ''),
discord_id=data.get('discord_id', ''),
expire_date=data.get('expire_date', ''),
version=data.get('version', ''),
staff_license=data.get('staff_license', False)
)
class TKIAuthException(Exception):
"""Base exception for TKI Auth errors"""
pass
class NetworkException(TKIAuthException):
"""Network related errors"""
pass
class AuthenticationException(TKIAuthException):
"""Authentication related errors"""
pass
class RateLimitException(TKIAuthException):
"""Rate limiting errors"""
pass
class TKIAuthClient:
def __init__(self, api_key: str = API_KEY, api_url: str = API_URL,
product: str = PRODUCT, version: str = VERSION):
self.api_key = api_key
self.api_url = api_url
self.product = product
self.version = version
self.session = requests.Session()
self.session.headers.update({
'Authorization': api_key,
'Content-Type': 'application/json',
'User-Agent': f'TKI-Auth-Python/{version}'
})
def get_hwid(self) -> str:
"""Generate hardware ID"""
try:
mac = hex(uuid.getnode())[2:].upper()
cpu_info = platform.processor() or platform.machine()
system_info = f"{platform.system()}-{cpu_info}-{mac}"
hwid = hashlib.sha256(system_info.encode()).hexdigest()[:16]
return f"PY-{hwid}"
except Exception:
return f"PY-FALLBACK-{abs(hash(platform.node())) % 1000000}"
def get_local_ip(self) -> str:
"""Get local IP address"""
import socket
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("1.1.1.1", 80))
return s.getsockname()[0]
except Exception:
return "127.0.0.1"
def authenticate(self, license_key: str, ip: Optional[str] = None,
hwid: Optional[str] = None) -> LicenseInfo:
"""Authenticate license and return license info"""
payload = {
"data": {
"product": self.product,
"version": self.version,
"licensekey": license_key,
"ip": ip or self.get_local_ip(),
"hwid": hwid or self.get_hwid()
}
}
try:
response = self.session.post(self.api_url, json=payload, timeout=30)
if response.status_code == 200:
data = response.json()
if data.get("status_overview") == "success":
return LicenseInfo.from_dict(data)
else:
raise AuthenticationException(data.get('message', 'Authentication failed'))
elif response.status_code == 429:
raise RateLimitException("Rate limit exceeded")
elif response.status_code in [400, 403, 404]:
data = response.json()
raise AuthenticationException(data.get('message', f'HTTP {response.status_code}'))
else:
raise NetworkException(f'HTTP {response.status_code}: {response.text}')
except requests.RequestException as e:
raise NetworkException(f'Network error: {e}')
except json.JSONDecodeError:
raise NetworkException('Invalid response format')
def authenticate_with_retry(self, license_key: str, max_retries: int = 3) -> LicenseInfo:
"""Authenticate with retry logic"""
for attempt in range(1, max_retries + 1):
try:
return self.authenticate(license_key)
except RateLimitException:
if attempt == max_retries:
raise
wait_time = 2 ** attempt
print(f"Rate limited. Waiting {wait_time}s before retry {attempt}/{max_retries}")
time.sleep(wait_time)
except NetworkException:
if attempt == max_retries:
raise
time.sleep(attempt)
raise AuthenticationException("Max retries exceeded")
class LicensedApplication:
def __init__(self):
self.client = TKIAuthClient()
self.license_info: Optional[LicenseInfo] = None
self.is_authenticated = False
self.validation_thread: Optional[threading.Thread] = None
self.stop_validation = threading.Event()
def authenticate(self, license_key: str) -> bool:
"""Authenticate and initialize the application"""
try:
print("Authenticating license...")
self.license_info = self.client.authenticate_with_retry(license_key)
self.is_authenticated = True
print("â Authentication successful!")
print(f" User: {self.license_info.discord_username}")
print(f" Tag: {self.license_info.discord_tag}")
print(f" Expires: {self.license_info.expire_date}")
print(f" Staff License: {self.license_info.staff_license}")
return True
except (AuthenticationException, NetworkException, RateLimitException) as e:
print(f"â Authentication failed: {e}")
return False
def start_periodic_validation(self, interval: int = 1800): # 30 minutes
"""Start periodic license validation"""
def validate_periodically():
while not self.stop_validation.wait(interval):
if self.is_authenticated and self.license_info:
try:
# Re-authenticate with the same license
license_key = "stored_license_key" # You'd store this securely
self.client.authenticate(license_key)
print("â Periodic validation successful")
except Exception as e:
print(f"â Periodic validation failed: {e}")
self.is_authenticated = False
self.on_license_expired()
break
self.validation_thread = threading.Thread(target=validate_periodically, daemon=True)
self.validation_thread.start()
def on_license_expired(self):
"""Called when license expires or validation fails"""
print("License expired or validation failed!")
# Implement your logic here (e.g., disable features, exit app)
@contextmanager
def license_guard(self):
"""Context manager to ensure license is valid"""
if not self.is_authenticated:
raise AuthenticationException("Not authenticated")
try:
yield self.license_info
finally:
pass
def shutdown(self):
"""Clean shutdown"""
if self.validation_thread:
self.stop_validation.set()
self.validation_thread.join(timeout=5)
# Example usage
def main():
app = LicensedApplication()
license_key = input("Enter license key: ").strip()
if app.authenticate(license_key):
print("Starting application...")
# Start periodic validation
app.start_periodic_validation()
# Use license guard for protected operations
try:
with app.license_guard() as license_info:
print(f"Running licensed feature for {license_info.discord_username}")
# Your protected application logic here
# Simulate running application
time.sleep(10)
except AuthenticationException as e:
print(f"License error: {e}")
finally:
app.shutdown()
else:
print("Failed to authenticate license!")
return 1
return 0
if __name__ == "__main__":
exit(main())
Flask Web Applicationâ
from flask import Flask, request, session, redirect, url_for, render_template_string
import hashlib
import requests
app = Flask(__name__)
app.secret_key = 'your-secret-key'
API_KEY = "your-api-key-here"
API_URL = "http://your-domain.com/api/license/auth"
PRODUCT = "MyFlaskApp"
VERSION = "1.0.0"
class TKIAuth:
@staticmethod
def get_hwid(request):
user_agent = request.headers.get('User-Agent', '')
ip = request.remote_addr or '127.0.0.1'
hw_string = f"{user_agent}-{ip}"
return f"FLASK-{hashlib.md5(hw_string.encode()).hexdigest()[:16]}"
@staticmethod
def authenticate(license_key, request):
payload = {
"data": {
"product": PRODUCT,
"version": VERSION,
"licensekey": license_key,
"ip": request.remote_addr or '127.0.0.1',
"hwid": TKIAuth.get_hwid(request)
}
}
headers = {
"Content-Type": "application/json",
"Authorization": API_KEY
}
try:
response = requests.post(API_URL, json=payload, headers=headers, timeout=30)
if response.status_code == 200:
data = response.json()
if data.get("status_overview") == "success":
return True, data
return False, response.json().get('message', 'Authentication failed')
except Exception as e:
return False, str(e)
@app.route('/')
def index():
if not session.get('authenticated'):
return redirect(url_for('login'))
user_info = session.get('user_info', {})
return render_template_string('''
<h1>Welcome to Licensed App!</h1>
<p>User: {{ username }}</p>
<p>Expires: {{ expire_date }}</p>
<p>Staff License: {{ staff_license }}</p>
<a href="{{ url_for('logout') }}">Logout</a>
''', **user_info)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
license_key = request.form.get('license_key')
if license_key:
success, result = TKIAuth.authenticate(license_key, request)
if success:
session['authenticated'] = True
session['user_info'] = {
'username': result.get('discord_username'),
'expire_date': result.get('expire_date'),
'staff_license': result.get('staff_license')
}
return redirect(url_for('index'))
else:
return render_template_string('''
<h1>License Authentication</h1>
<form method="post">
<input type="text" name="license_key" placeholder="Enter license key" required>
<button type="submit">Authenticate</button>
</form>
<p style="color: red;">{{ error }}</p>
''', error=result)
return render_template_string('''
<h1>License Authentication</h1>
<form method="post">
<input type="text" name="license_key" placeholder="Enter license key" required>
<button type="submit">Authenticate</button>
</form>
''')
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
Requirements.txtâ
requests>=2.31.0
flask>=2.3.0