Log login attempts

This commit is contained in:
Peter Stockings
2026-01-30 19:07:09 +11:00
parent b6443bc1e2
commit 4dcf589b63
4 changed files with 74 additions and 2 deletions

View File

@@ -1,9 +1,10 @@
from flask import Blueprint, render_template, redirect, url_for, flash
from flask import Blueprint, render_template, redirect, url_for, flash, request
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_user, login_required, logout_user
from forms.login import LoginForm
from forms.signup import SignupForm
from extensions import db
from utils import get_client_ip
auth = Blueprint('auth', __name__)
@@ -83,6 +84,17 @@ def create_person(name, email, password_hash):
return row['person_id']
def record_login_attempt(email, success, person_id=None):
"""
Record a login attempt in the database.
"""
sql = """
INSERT INTO login_attempts (email, ip_address, success, user_agent, person_id)
VALUES (%s, %s, %s, %s, %s)
"""
db.execute(sql, [email, get_client_ip(), success, request.user_agent.string, person_id], commit=True)
# ---------------------
# Blueprint endpoints
# ---------------------
@@ -109,9 +121,11 @@ def login():
person = get_person_by_email(form.email.data)
if person and check_password_hash(person.password_hash, form.password.data):
login_user(person)
record_login_attempt(form.email.data, True, person.id)
flash("Logged in successfully.", "success")
return redirect(url_for('calendar.get_calendar', person_id=person.id))
else:
record_login_attempt(form.email.data, False, person.id if person else None)
flash("Invalid email or password.", "danger")
return render_template('auth/login.html', form=form)