Get IP from proxy headers if available

This commit is contained in:
Peter Stockings
2025-12-02 16:17:20 +11:00
parent 4227be5a80
commit 416f6d423d

View File

@@ -6,6 +6,20 @@ from jinja2_fragments import render_block
auth = Blueprint('auth', __name__)
def get_client_ip():
"""Get real client IP address, checking proxy headers first"""
# Check common proxy headers in order of preference
if request.headers.get('X-Forwarded-For'):
# X-Forwarded-For can contain multiple IPs, get the first (original client)
return request.headers.get('X-Forwarded-For').split(',')[0].strip()
elif request.headers.get('X-Real-IP'):
return request.headers.get('X-Real-IP')
elif request.headers.get('CF-Connecting-IP'): # Cloudflare
return request.headers.get('CF-Connecting-IP')
else:
# Fallback to direct connection IP
return request.remote_addr
class User(UserMixin):
def __init__(self, id, username, password_hash, created_at, theme_preference='light'):
self.id = id
@@ -41,19 +55,19 @@ def login():
user_data = db.get_user_by_username(username)
if not user_data:
# Record failed login attempt
db.record_login(None, request.remote_addr, str(request.user_agent), False, "User not found")
# Record failed login attempt with real IP
db.record_login(None, get_client_ip(), str(request.user_agent), False, "User not found")
return render_template("login.html", error="User does not exist")
if not check_password_hash(user_data['password_hash'], password):
# Record failed login attempt
db.record_login(user_data['id'], request.remote_addr, str(request.user_agent), False, "Invalid password")
# Record failed login attempt with real IP
db.record_login(user_data['id'], get_client_ip(), str(request.user_agent), False, "Invalid password")
return render_template("login.html", error="Invalid username or password")
user = User(id=str(user_data['id']), username=user_data['username'], password_hash=user_data['password_hash'], created_at=user_data['created_at'], theme_preference=user_data.get('theme_preference', 'light'))
# Record successful login
db.record_login(user.id, request.remote_addr, str(request.user_agent), True)
# Record successful login with real IP
db.record_login(user.id, get_client_ip(), str(request.user_agent), True)
login_user(user)