42 lines
1.3 KiB
Python
42 lines
1.3 KiB
Python
|
|
"""Login History model for tracking authentication events"""
|
||
|
|
|
||
|
|
from datetime import UTC, datetime
|
||
|
|
|
||
|
|
from app import db
|
||
|
|
|
||
|
|
|
||
|
|
class LoginHistory(db.Model):
|
||
|
|
"""Tracks login attempts (both success and failure)"""
|
||
|
|
|
||
|
|
__tablename__ = "login_history"
|
||
|
|
|
||
|
|
id = db.Column(db.Integer, primary_key=True)
|
||
|
|
user_id = db.Column(
|
||
|
|
db.Integer, db.ForeignKey("users.id"), nullable=False, index=True
|
||
|
|
)
|
||
|
|
ip_address = db.Column(db.String(45), nullable=True)
|
||
|
|
user_agent = db.Column(db.String(512), nullable=True)
|
||
|
|
success = db.Column(db.Boolean, default=True)
|
||
|
|
created_at = db.Column(
|
||
|
|
db.DateTime, default=lambda: datetime.now(UTC), nullable=False
|
||
|
|
)
|
||
|
|
|
||
|
|
# Relationships
|
||
|
|
user = db.relationship("User", back_populates="login_history")
|
||
|
|
|
||
|
|
def to_dict(self):
|
||
|
|
"""Convert login history to dictionary"""
|
||
|
|
return {
|
||
|
|
"id": self.id,
|
||
|
|
"user_id": self.user_id,
|
||
|
|
"ip_address": self.ip_address,
|
||
|
|
"user_agent": self.user_agent,
|
||
|
|
"success": self.success,
|
||
|
|
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||
|
|
}
|
||
|
|
|
||
|
|
def __repr__(self):
|
||
|
|
return (
|
||
|
|
f"<LoginHistory id={self.id} user_id={self.user_id} "
|
||
|
|
f"success={self.success}>"
|
||
|
|
)
|