-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
250 lines (208 loc) · 8.91 KB
/
auth.py
File metadata and controls
250 lines (208 loc) · 8.91 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
from functools import wraps
from flask import session, redirect, url_for, request, jsonify, g
from config import get_config, save_config
import datetime
import json # Added for JSON logging
import os # Added for path check
import hashlib # For generating browser identity
import ipaddress
LOG_FILE = "logs.json"
MAX_LOG_ENTRIES = 1000 # Max number of log entries to keep
MAX_BROWSER_HISTORY = 5 # Maximum number of browser entries to keep per user
# --- JSON Log Handling Functions ---
def read_logs():
"""Reads all logs from the JSON log file."""
if not os.path.exists(LOG_FILE):
return []
try:
with open(LOG_FILE, 'r', encoding='utf-8') as f:
logs = json.load(f)
return logs
except (json.JSONDecodeError, IOError) as e:
print(f"Error reading log file '{LOG_FILE}': {e}")
return [] # Return empty list on error or if file is corrupted/empty
def write_logs(logs_data):
"""Writes logs data to the JSON log file."""
try:
with open(LOG_FILE, 'w', encoding='utf-8') as f:
json.dump(logs_data, f, indent=4)
except IOError as e:
print(f"Error writing to log file '{LOG_FILE}': {e}")
# --- IP Address Helper ---
def get_real_ip():
"""Get the real client IP address with proxy-protocol aware fallback."""
config = get_config()
server_config = config.get('server', {})
remote_addr = request.remote_addr
if server_config.get('proxy_protocol_v2'):
# With Gunicorn --proxy-protocol, REMOTE_ADDR is sourced from PROXY header.
return remote_addr
# Optional trusted proxy fallback for X-Forwarded-For when not using proxy protocol.
trusted_raw = server_config.get('proxy_protocol_allow_from', '')
trusted_sources = [src.strip() for src in str(trusted_raw).split(',') if src.strip()]
if not trusted_sources:
return remote_addr
if _ip_is_trusted_proxy(remote_addr, trusted_sources):
xff = request.headers.get('X-Forwarded-For', '')
if xff:
first_hop = xff.split(',')[0].strip()
if first_hop:
return first_hop
return remote_addr
def _ip_is_trusted_proxy(ip_value, trusted_sources):
"""Check if an IP belongs to trusted proxies (single IP, CIDR, or '*')."""
if not ip_value:
return False
for trusted in trusted_sources:
if trusted == '*':
return True
try:
if '/' in trusted:
if ipaddress.ip_address(ip_value) in ipaddress.ip_network(trusted, strict=False):
return True
elif ip_value == trusted:
return True
except ValueError:
# Ignore malformed entries instead of failing request handling.
continue
return False
# --- Browser Fingerprinting ---
def generate_browser_fingerprint():
"""Generate a simple browser fingerprint based on request data."""
user_agent = request.headers.get('User-Agent', '')
ip_address = get_real_ip()
accept_language = request.headers.get('Accept-Language', '')
# Create a unique identifier from these components
fingerprint_data = f"{user_agent}|{ip_address}|{accept_language}"
return hashlib.md5(fingerprint_data.encode()).hexdigest()
def get_browser_data():
"""Get current browser data for tracking."""
now = datetime.datetime.now().isoformat()
return {
"ip_address": get_real_ip(),
"user_agent": request.headers.get('User-Agent', 'Unknown'),
"browser_identity": generate_browser_fingerprint(),
"session_id": request.cookies.get('session', ''),
"first_login": now,
"last_login": now
}
# --- Authentication and User Management ---
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'username' not in session:
if request.headers.get("X-Requested-With") == "XMLHttpRequest":
return jsonify(error="Unauthorized", message="User not logged in."), 401
# Use only the path + query string, not the full URL
next_path = request.path
if request.query_string:
next_path += '?' + request.query_string.decode('utf-8')
return redirect(url_for('login', next=next_path))
# Populate g.user with current user information
g.user = get_current_user_info()
if g.user is None:
# Session exists but user info is missing - invalid session
session.clear()
if request.headers.get("X-Requested-With") == "XMLHttpRequest":
return jsonify(error="Unauthorized", message="Invalid session."), 401
# Use only the path + query string, not the full URL
next_path = request.path
if request.query_string:
next_path += '?' + request.query_string.decode('utf-8')
return redirect(url_for('login', next=next_path))
return f(*args, **kwargs)
return decorated_function
def handle_login(username, password):
"""Handles user login with browser tracking."""
config = get_config()
if password == config.get("app_password"):
# Store username in session
session['username'] = username
# Ensure users dictionary exists
if 'users' not in config or config['users'] is None:
config['users'] = {}
# Get or create user entry
if username not in config['users']:
config['users'][username] = {
"browsers": []
}
# Get current browser data
current_browser = get_browser_data()
browser_id = current_browser["browser_identity"]
# Check if this browser is already in the list
browser_found = False
for browser in config['users'][username].get("browsers", []):
if browser["browser_identity"] == browser_id:
# Update last login time
browser["last_login"] = current_browser["last_login"]
browser["ip_address"] = current_browser["ip_address"] # Update IP in case it changed
browser["session_id"] = current_browser["session_id"] # Update session ID
browser_found = True
break
# If browser not found, add it to the list
if not browser_found:
browsers = config['users'][username].get("browsers", [])
browsers.append(current_browser)
# Keep only the most recent MAX_BROWSER_HISTORY browsers
if len(browsers) > MAX_BROWSER_HISTORY:
browsers = sorted(browsers, key=lambda x: x["last_login"], reverse=True)[:MAX_BROWSER_HISTORY]
config['users'][username]["browsers"] = browsers
save_config(config)
return True
return False
def handle_logout():
"""Handles user logout."""
session.pop('username', None)
return True
def get_current_user_info():
if 'username' in session:
username = session['username']
config = get_config()
# Ensure users exists and is a dictionary
users_dict = config.get('users', {})
if not isinstance(users_dict, dict):
users_dict = {}
user_details = users_dict.get(username)
if user_details:
# Find the current browser
browser_id = generate_browser_fingerprint()
current_browser = None
for browser in user_details.get("browsers", []):
if browser["browser_identity"] == browser_id:
current_browser = browser
break
return {
"username": username,
"ip_address": current_browser["ip_address"] if current_browser else get_real_ip(),
"browser": current_browser
}
return None
def get_active_users_count():
"""Count users with recent activity (within the last hour)."""
config = get_config()
users_dict = config.get('users', {})
if not isinstance(users_dict, dict):
return 0
# This function no longer counts active users since that's now handled by socket connections
# It's kept for backward compatibility
return len(users_dict)
def add_activity_log(username, ip_address, action, details=""):
"""Adds an activity to the logs.json file."""
logs = read_logs()
log_entry = {
"timestamp": datetime.datetime.now().isoformat(),
"username": username,
"ip_address": ip_address,
"action": action,
"details": details
}
logs.insert(0, log_entry) # Add to the beginning to show newest first
# Keep log size manageable
logs = logs[:MAX_LOG_ENTRIES]
write_logs(logs)
def get_recent_logs(count=20):
"""Gets a specified number of recent logs."""
all_logs = read_logs()
return all_logs[:count]
# Need to import datetime for add_activity_log
import datetime