63 lines
2.0 KiB
Python
63 lines
2.0 KiB
Python
#!/usr/bin/python3
|
|
|
|
import sqlite3
|
|
import hashlib
|
|
import cgi
|
|
import os
|
|
import http.cookies
|
|
import time
|
|
|
|
# Get form data
|
|
form = cgi.FieldStorage()
|
|
username = form.getvalue('username')
|
|
password = form.getvalue('password')
|
|
|
|
# Connect to SQLite and check credentials
|
|
db = sqlite3.connect('/var/lib/monotreme/data/monotreme.db')
|
|
cursor = db.cursor()
|
|
|
|
# Fetch the user's stored hashed password
|
|
cursor.execute("SELECT password_hash FROM users WHERE username=?", (username,))
|
|
result = cursor.fetchone()
|
|
|
|
if result:
|
|
stored_password_hash = result[0]
|
|
# Hash the entered password and compare it
|
|
entered_password_hash = hashlib.sha256(password.encode()).hexdigest()
|
|
|
|
if entered_password_hash == stored_password_hash:
|
|
# Create a session token and expiration time (e.g., 24 hours from now)
|
|
session_token = hashlib.sha256(os.urandom(32)).hexdigest()
|
|
expires_at = int(time.time()) + 86400 # 24 hours
|
|
|
|
# Log session creation for debugging
|
|
with open("/tmp/login_session_creation.log", "a") as f:
|
|
f.write(f"Creating session for user {username}\n")
|
|
f.write(f"Session Token: {session_token}\n")
|
|
f.write(f"Expires At: {expires_at}\n")
|
|
|
|
# Store the session in the sessions table
|
|
cursor.execute("INSERT INTO sessions (session_id, username, expires_at) VALUES (?, ?, ?)",
|
|
(session_token, username, expires_at))
|
|
db.commit()
|
|
|
|
# Set the session cookie
|
|
print("Content-Type: text/html")
|
|
print(f"Set-Cookie: session_id={session_token}; Path=/; HttpOnly")
|
|
print()
|
|
|
|
# Show success message or redirect to user panel
|
|
print("<h1>Login successful!</h1>")
|
|
print("<a href='/user_panel/'>Go to your dashboard</a>")
|
|
else:
|
|
print("Content-Type: text/html")
|
|
print()
|
|
print("<h1>Invalid username or password</h1>")
|
|
else:
|
|
print("Content-Type: text/html")
|
|
print()
|
|
print("<h1>Invalid username or password</h1>")
|
|
|
|
# Close the database connection
|
|
db.close()
|