fixed some timezone log issues for auth

This commit is contained in:
2025-04-08 16:46:28 -04:00
parent b25ebfe9bb
commit 0a254c9d20
3 changed files with 45 additions and 54 deletions

View File

@@ -520,7 +520,8 @@ def get_latest_auth_logs(reply_type=None, limit=5, time_range=None, offset=0):
print(f"Warning: Unknown timezone '{tz_str}', falling back to UTC.") print(f"Warning: Unknown timezone '{tz_str}', falling back to UTC.")
app_tz = pytz.utc app_tz = pytz.utc
now = datetime.now(app_tz) now = datetime.now(app_tz)
print(f"🕒 Using timezone: {tz_str} → Now: {now.isoformat()}")
query_base = "SELECT * FROM auth_logs" query_base = "SELECT * FROM auth_logs"
filters = [] filters = []
params = [] params = []
@@ -548,6 +549,7 @@ def get_latest_auth_logs(reply_type=None, limit=5, time_range=None, offset=0):
if delta: if delta:
time_filter_dt = now - delta time_filter_dt = now - delta
print(f"🕒 Filtering logs after: {time_filter_dt.isoformat()}")
filters.append("timestamp >= %s") filters.append("timestamp >= %s")
params.append(time_filter_dt) params.append(time_filter_dt)
@@ -575,7 +577,8 @@ def count_auth_logs(reply_type=None, time_range=None):
print(f"Warning: Unknown timezone '{tz_str}', falling back to UTC.") print(f"Warning: Unknown timezone '{tz_str}', falling back to UTC.")
app_tz = pytz.utc app_tz = pytz.utc
now = datetime.now(app_tz) now = datetime.now(app_tz)
print(f"🕒 Using timezone: {tz_str} → Now: {now.isoformat()}")
query_base = "SELECT COUNT(*) FROM auth_logs" query_base = "SELECT COUNT(*) FROM auth_logs"
filters = [] filters = []
params = [] params = []
@@ -603,6 +606,7 @@ def count_auth_logs(reply_type=None, time_range=None):
if delta: if delta:
time_filter_dt = now - delta time_filter_dt = now - delta
print(f"🕒 Filtering logs after: {time_filter_dt.isoformat()}")
filters.append("timestamp >= %s") filters.append("timestamp >= %s")
params.append(time_filter_dt) params.append(time_filter_dt)

View File

@@ -31,40 +31,37 @@
<tr> <tr>
<td>{{ entry.mac_address }}</td> <td>{{ entry.mac_address }}</td>
<td> <!-- Form spans Description and Actions columns -->
<form method="POST" action="{{ url_for('user.update_description_route') }}"> <form method="POST" action="{{ url_for('user.update_description_route') }}">
<td>
<input type="hidden" name="mac_address" value="{{ entry.mac_address }}"> <input type="hidden" name="mac_address" value="{{ entry.mac_address }}">
<input type="text" name="description" value="{{ entry.description or '' }}"> <input type="text" name="description" value="{{ entry.description or '' }}">
</form> </td>
</td>
<td>{{ entry.vendor or "..." }}</td> <td>{{ entry.vendor or "..." }}</td>
<td> <td>
<form method="POST" action="{{ url_for('user.update_vlan_route') }}" class="inline-form"> <form method="POST" action="{{ url_for('user.update_vlan_route') }}" class="inline-form">
<input type="hidden" name="mac_address" value="{{ entry.mac_address }}"> <input type="hidden" name="mac_address" value="{{ entry.mac_address }}">
<select name="group_id" onchange="this.form.submit()"> <select name="group_id" onchange="this.form.submit()">
{% for group in available_groups %} {% for group in available_groups %}
<option value="{{ group.vlan_id }}" {% if group.vlan_id == entry.vlan_id %}selected{% endif %}> <option value="{{ group.vlan_id }}" {% if group.vlan_id == entry.vlan_id %}selected{% endif %}>
VLAN {{ group.vlan_id }}{% if group.description %} - {{ group.description }}{% endif %} VLAN {{ group.vlan_id }}{% if group.description %} - {{ group.description }}{% endif %}
</option> </option>
{% endfor %} {% endfor %}
</select> </select>
</form> </form>
</td> </td>
<td> <td>
<form method="POST" action="{{ url_for('user.update_description_route') }}" style="display:inline;">
<input type="hidden" name="mac_address" value="{{ entry.mac_address }}">
<input type="hidden" name="description" value="{{ entry.description }}">
<button type="submit" title="Save">💾</button> <button type="submit" title="Save">💾</button>
</form> </form> <!-- Closing the description form here -->
<form method="POST" action="{{ url_for('user.delete') }}" style="display:inline;"> <form method="POST" action="{{ url_for('user.delete') }}" style="display:inline;">
<input type="hidden" name="mac_address" value="{{ entry.mac_address }}"> <input type="hidden" name="mac_address" value="{{ entry.mac_address }}">
<button type="submit" onclick="return confirm('Delete this MAC address?')"></button> <button type="submit" onclick="return confirm('Delete this MAC address?')"></button>
</form> </form>
</td> </td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>

View File

@@ -1,6 +1,7 @@
from pyrad.server import Server, RemoteHost from pyrad.server import Server, RemoteHost
from pyrad.dictionary import Dictionary from pyrad.dictionary import Dictionary
from pyrad.packet import AccessAccept, AccessReject from pyrad.packet import AccessAccept, AccessReject
from datetime import datetime, timezone
import mysql.connector import mysql.connector
import os import os
@@ -22,6 +23,7 @@ class MacRadiusServer(Server):
def HandleAuthPacket(self, pkt): def HandleAuthPacket(self, pkt):
username = pkt['User-Name'][0].upper() username = pkt['User-Name'][0].upper()
cursor = self.db.cursor(dictionary=True) cursor = self.db.cursor(dictionary=True)
now_utc = datetime.now(timezone.utc)
# Step 1: Check if the MAC exists in the users table # Step 1: Check if the MAC exists in the users table
cursor.execute("SELECT vlan_id FROM users WHERE mac_address = %s", (username,)) cursor.execute("SELECT vlan_id FROM users WHERE mac_address = %s", (username,))
@@ -31,60 +33,48 @@ class MacRadiusServer(Server):
# Step 2: Handle the Access-Accept or Access-Reject scenario # Step 2: Handle the Access-Accept or Access-Reject scenario
if result: if result:
# MAC found in users table
vlan_id = result['vlan_id'] vlan_id = result['vlan_id']
denied_vlan = os.getenv("DENIED_VLAN", "999")
# Check if the VLAN is a denied VLAN
denied_vlan = os.getenv("DENIED_VLAN", "999") # Get the denied VLAN from environment
if vlan_id == denied_vlan: if vlan_id == denied_vlan:
# Step 3: If the MAC is in a denied VLAN, reject the access
reply.code = AccessReject reply.code = AccessReject
cursor.execute(""" cursor.execute("""
INSERT INTO auth_logs (mac_address, reply, result) INSERT INTO auth_logs (mac_address, reply, result, timestamp)
VALUES (%s, %s, %s) VALUES (%s, %s, %s, %s)
""", (username, "Access-Reject", f"Denied due to VLAN {denied_vlan}")) """, (username, "Access-Reject", f"Denied due to VLAN {denied_vlan}", now_utc))
self.db.commit() self.db.commit()
print(f"[INFO] MAC {username} rejected due to VLAN {denied_vlan}") print(f"[INFO] MAC {username} rejected due to VLAN {denied_vlan}")
else: else:
# Step 4: If the MAC is valid and not in the denied VLAN, accept access and assign VLAN
reply.code = AccessAccept reply.code = AccessAccept
reply.AddAttribute("Tunnel-Type", 13) reply.AddAttribute("Tunnel-Type", 13)
reply.AddAttribute("Tunnel-Medium-Type", 6) reply.AddAttribute("Tunnel-Medium-Type", 6)
reply.AddAttribute("Tunnel-Private-Group-Id", vlan_id) reply.AddAttribute("Tunnel-Private-Group-Id", vlan_id)
# Log successful access
cursor.execute(""" cursor.execute("""
INSERT INTO auth_logs (mac_address, reply, result) INSERT INTO auth_logs (mac_address, reply, result, timestamp)
VALUES (%s, %s, %s) VALUES (%s, %s, %s, %s)
""", (username, "Access-Accept", f"Assigned to VLAN {vlan_id}")) """, (username, "Access-Accept", f"Assigned to VLAN {vlan_id}", now_utc))
self.db.commit() self.db.commit()
print(f"[INFO] MAC {username} accepted and assigned to VLAN {vlan_id}") print(f"[INFO] MAC {username} accepted and assigned to VLAN {vlan_id}")
else: else:
# Step 5: If the MAC is not found in the database, assign to fallback VLAN reply.code = AccessAccept
reply.code = AccessAccept # Still send Access-Accept even for fallback reply["Tunnel-Type"] = 13
reply["Tunnel-Type"] = 13 # VLAN reply["Tunnel-Medium-Type"] = 6
reply["Tunnel-Medium-Type"] = 6 # IEEE-802
reply["Tunnel-Private-Group-Id"] = DEFAULT_VLAN_ID reply["Tunnel-Private-Group-Id"] = DEFAULT_VLAN_ID
# Log fallback assignment
cursor.execute(""" cursor.execute("""
INSERT INTO auth_logs (mac_address, reply, result) INSERT INTO auth_logs (mac_address, reply, result, timestamp)
VALUES (%s, %s, %s) VALUES (%s, %s, %s, %s)
""", (username, "Access-Accept", f"Assigned to fallback VLAN {DEFAULT_VLAN_ID}")) """, (username, "Access-Accept", f"Assigned to fallback VLAN {DEFAULT_VLAN_ID}", now_utc))
self.db.commit() self.db.commit()
print(f"[INFO] MAC {username} not found — assigned to fallback VLAN {DEFAULT_VLAN_ID}") print(f"[INFO] MAC {username} not found — assigned to fallback VLAN {DEFAULT_VLAN_ID}")
# Send the reply packet (whether accept or reject)
self.SendReplyPacket(pkt.fd, reply) self.SendReplyPacket(pkt.fd, reply)
cursor.close() cursor.close()
if __name__ == '__main__': if __name__ == '__main__':
srv = MacRadiusServer(dict=Dictionary("dictionary")) srv = MacRadiusServer(dict=Dictionary("dictionary"))
srv.hosts["0.0.0.0"] = RemoteHost("0.0.0.0", os.getenv("RADIUS_SECRET", "testing123").encode(), "localhost") srv.hosts["0.0.0.0"] = RemoteHost("0.0.0.0", os.getenv("RADIUS_SECRET", "testing123").encode(), "localhost")