Repository navigation
Expand file tree
/
Copy pathauth_system.py
More file actions
449 lines (365 loc) Β· 15.2 KB
/
Copy pathauth_system.py
File metadata and controls
449 lines (365 loc) Β· 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import os
import hashlib
import secrets
import sqlite3
from datetime import datetime, timedelta
from flask import Flask, request, jsonify
from flask_cors import CORS
class SimpleAuthSystem:
"""Simple and clean license key management system"""
def __init__(self):
self.db_path = "auth_database.db"
self.admin_password = "admin123"
self.init_database()
def init_database(self):
"""Create the database table"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS licenses (
license_key TEXT PRIMARY KEY,
created_at TEXT,
expires_at TEXT,
is_active BOOLEAN,
hwid TEXT,
notes TEXT
)
''')
conn.commit()
conn.close()
def generate_license(self, days=30, notes=""):
"""Generate a new license key"""
license_key = f"KEY-{secrets.token_hex(8).upper()}"
current_time = datetime.now()
expires_at = current_time + timedelta(days=days)
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO licenses VALUES (?, ?, ?, ?, ?, ?)
''', (license_key, current_time.isoformat(), expires_at.isoformat(), True, None, notes))
conn.commit()
conn.close()
return license_key
def validate_license(self, license_key, hwid=None):
"""Check if a license is valid"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('SELECT * FROM licenses WHERE license_key = ?', (license_key,))
row = cursor.fetchone()
conn.close()
if not row:
return False, "Invalid license key"
_, created_at, expires_at, is_active, bound_hwid, notes = row
if not is_active:
return False, "License is deactivated"
if datetime.now() > datetime.fromisoformat(expires_at):
return False, "License has expired"
# Bind HWID if provided and not already bound
if hwid and not bound_hwid:
self.bind_hwid(license_key, hwid)
return True, "License valid and bound to device"
elif hwid and bound_hwid != hwid:
return False, "License bound to different device"
return True, "License valid"
def bind_hwid(self, license_key, hwid):
"""Bind a license to a device"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('''
UPDATE licenses SET hwid = ? WHERE license_key = ?
''', (hwid, license_key))
conn.commit()
conn.close()
def list_licenses(self):
"""Get all licenses"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('SELECT * FROM licenses')
rows = cursor.fetchall()
conn.close()
licenses = []
for row in rows:
licenses.append({
"key": row[0],
"created": row[1],
"expires": row[2],
"active": row[3],
"hwid": row[4],
"notes": row[5]
})
return licenses
def delete_license(self, license_key):
"""Delete a license"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute('DELETE FROM licenses WHERE license_key = ?', (license_key,))
success = cursor.rowcount > 0
conn.commit()
conn.close()
return success
class SimpleHWID:
"""Simple hardware ID generator"""
@staticmethod
def generate():
"""Generate a simple hardware ID"""
import platform
import uuid
# Get basic system info
system = platform.system()
machine = platform.machine()
# Create a unique identifier
unique_id = f"{system}-{machine}-{uuid.uuid4().hex[:8]}"
hwid = hashlib.sha256(unique_id.encode()).hexdigest()[:16].upper()
return hwid
class SimpleAPI:
"""Simple Flask API for license management"""
def __init__(self, auth_system):
self.auth_system = auth_system
self.app = Flask(__name__)
CORS(self.app)
self.setup_routes()
def setup_routes(self):
"""Setup API endpoints"""
@self.app.route('/api/health', methods=['GET'])
def health():
return jsonify({"status": "ok", "message": "Auth API is running"})
@self.app.route('/api/license/validate', methods=['POST'])
def validate():
data = request.get_json()
if not data or 'license_key' not in data:
return jsonify({"error": "Missing license key"}), 400
license_key = data['license_key']
user_hwid = data.get('hwid')
# If no HWID provided, generate one based on request info
if not user_hwid:
# Create a unique HWID based on IP and user agent
import hashlib
client_ip = request.remote_addr
user_agent = request.headers.get('User-Agent', 'Unknown')
hwid_seed = f"{client_ip}:{user_agent}"
user_hwid = f"HWID-{hashlib.md5(hwid_seed.encode()).hexdigest()[:8].upper()}"
success, message = self.auth_system.validate_license(license_key, user_hwid)
if success:
# Get full license details for the response
conn = sqlite3.connect(self.auth_system.db_path)
cursor = conn.cursor()
cursor.execute('SELECT * FROM licenses WHERE license_key = ?', (license_key,))
license_data = cursor.fetchone()
conn.close()
if license_data:
# Calculate days remaining
from datetime import datetime
expires_at = license_data[2] # expires_at column
if expires_at:
try:
expire_date = datetime.strptime(expires_at, '%Y-%m-%d %H:%M:%S')
days_remaining = (expire_date - datetime.now()).days
if days_remaining > 0:
expires_info = f"{days_remaining} days remaining"
else:
expires_info = "Expired"
except:
expires_info = expires_at
else:
expires_info = "No expiration"
return jsonify({
"success": True,
"message": message,
"status": "Active",
"expires_at": expires_info,
"hwid": license_data[4] or "Not bound", # hwid column (index 4)
"user_hwid": user_hwid # The HWID used for this validation
})
else:
return jsonify({"success": True, "message": message, "user_hwid": user_hwid})
else:
return jsonify({"success": False, "error": message}), 400
@self.app.route('/api/admin/licenses', methods=['GET'])
def list_licenses():
# Simple auth check
if request.headers.get('X-API-Key') != 'admin123':
return jsonify({"error": "Unauthorized"}), 401
licenses = self.auth_system.list_licenses()
return jsonify({"licenses": licenses})
def start(self, host='0.0.0.0', port=5000):
"""Start the API server"""
print(f"π Starting API server on {host}:{port}")
print(f"π API endpoints:")
print(f" GET /api/health")
print(f" POST /api/license/validate")
print(f" GET /api/admin/licenses (requires X-API-Key: admin123)")
self.app.run(host=host, port=port, debug=False)
class SimpleUI:
"""Simple console interface"""
def __init__(self, auth_system):
self.auth_system = auth_system
self.hwid = SimpleHWID()
def clear_screen(self):
"""Clear console"""
os.system('cls' if os.name == 'nt' else 'clear')
def show_menu(self):
"""Show main menu"""
print("\n" + "="*50)
print("π SIMPLE LICENSE MANAGER")
print("="*50)
print("1. Generate License")
print("2. Validate License")
print("3. List Licenses")
print("4. Delete License")
print("5. Start API Server")
print("6. Show HWID")
print("7. Quick Demo")
print("8. Exit")
print("="*50)
def generate_license(self):
"""Generate a new license"""
print("\nπ GENERATE LICENSE")
print("-" * 30)
try:
days = int(input("Days valid (default 30): ") or "30")
notes = input("Notes (optional): ")
license_key = self.auth_system.generate_license(days, notes)
print(f"\nβ
License generated: {license_key}")
print(f"Valid for: {days} days")
except ValueError:
print("β Invalid number of days")
input("\nPress Enter to continue...")
def validate_license(self):
"""Validate a license"""
print("\nβ
VALIDATE LICENSE")
print("-" * 30)
license_key = input("Enter license key: ")
if not license_key:
print("β License key required")
input("\nPress Enter to continue...")
return
# Get current HWID
current_hwid = self.hwid.generate()
print(f"Current HWID: {current_hwid}")
success, message = self.auth_system.validate_license(license_key, current_hwid)
if success:
print(f"β
{message}")
else:
print(f"β {message}")
input("\nPress Enter to continue...")
def list_licenses(self):
"""Show all licenses"""
print("\nπ ALL LICENSES")
print("-" * 50)
licenses = self.auth_system.list_licenses()
if not licenses:
print("No licenses found")
else:
for i, license_data in enumerate(licenses, 1):
status = "β
Active" if license_data['active'] else "β Inactive"
print(f"{i}. {license_data['key']}")
print(f" Status: {status}")
print(f" Expires: {license_data['expires']}")
print(f" HWID: {license_data['hwid'] or 'Not bound'}")
print(f" Notes: {license_data['notes'] or 'None'}")
print()
input("\nPress Enter to continue...")
def delete_license(self):
"""Delete a license"""
print("\nποΈ DELETE LICENSE")
print("-" * 30)
license_key = input("Enter license key to delete: ")
if not license_key:
print("β License key required")
input("\nPress Enter to continue...")
return
if self.auth_system.delete_license(license_key):
print("β
License deleted")
else:
print("β License not found")
input("\nPress Enter to continue...")
def start_api(self):
"""Start the API server"""
print("\nπ STARTING API SERVER")
print("-" * 30)
# Auto-select best options
host = "0.0.0.0" # Best for all network access
port = 5000 # Standard Flask port
print(f"Auto-selected: Host {host}, Port {port}")
print("Starting server...")
try:
api = SimpleAPI(self.auth_system)
api.start(host, port)
except KeyboardInterrupt:
print("\n\nAPI server stopped")
except Exception as e:
print(f"β Error: {e}")
input("\nPress Enter to continue...")
def show_hwid(self):
"""Show current hardware ID"""
print("\nπ» HARDWARE ID")
print("-" * 30)
hwid = self.hwid.generate()
print(f"Current HWID: {hwid}")
print("\nThis ID is unique to your device and will be used")
print("to bind licenses to prevent sharing.")
input("\nPress Enter to continue...")
def run(self):
"""Main UI loop"""
while True:
self.clear_screen()
self.show_menu()
choice = input("\nSelect option (1-8): ")
if choice == "1":
self.generate_license()
elif choice == "2":
self.validate_license()
elif choice == "3":
self.list_licenses()
elif choice == "4":
self.delete_license()
elif choice == "5":
self.start_api()
elif choice == "6":
self.show_hwid()
elif choice == "7":
print("\nπ RUNNING QUICK DEMO")
print("-" * 30)
print("Generating a sample license...")
sample_license_key = self.auth_system.generate_license(days=7, notes="Demo license")
print(f"β
Sample license generated: {sample_license_key}")
print("Valid for: 7 days")
print("Attempting to validate with a different HWID...")
# Generate a different HWID for the demo
demo_hwid = self.hwid.generate()
print(f"Current HWID: {demo_hwid}")
success, message = self.auth_system.validate_license(sample_license_key, demo_hwid)
if success:
print(f"β
Sample license validated with different HWID: {message}")
else:
print(f"β Sample license failed to validate with different HWID: {message}")
print("=" * 30)
input("\nPress Enter to continue...")
elif choice == "8":
print("\nπ Goodbye!")
break
else:
print("β Invalid option")
input("\nPress Enter to continue...")
def main():
"""Main function"""
print("π Starting Simple License Manager...")
print("=" * 50)
print("β
Database initialized")
print("β
API endpoints ready")
print("β
License validation system active")
print("β
HWID binding system ready")
print("=" * 50)
print("\nπ― What you can do:")
print("β’ Generate license keys for customers")
print("β’ Start API server for software integration")
print("β’ Use license_checker.py to test validation")
print("β’ Manage all licenses through admin interface")
print("=" * 50)
# Create auth system
auth = SimpleAuthSystem()
# Create and run UI
ui = SimpleUI(auth)
ui.run()
if __name__ == "__main__":
main()