43 lines
1.6 KiB
Python
43 lines
1.6 KiB
Python
from datetime import datetime
|
|
from flask_login import UserMixin
|
|
from app import db, bcrypt
|
|
|
|
|
|
class User(UserMixin, db.Model):
|
|
"""User model for authentication."""
|
|
|
|
__tablename__ = 'users'
|
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
username = db.Column(db.String(80), unique=True, nullable=False, index=True)
|
|
email = db.Column(db.String(120), unique=True, nullable=False, index=True)
|
|
password_hash = db.Column(db.String(128), nullable=False)
|
|
is_admin = db.Column(db.Boolean, default=False, nullable=False, index=True)
|
|
created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
|
|
|
|
# Relationships
|
|
sets = db.relationship('Set', backref='added_by', lazy='dynamic',
|
|
foreign_keys='Set.user_id')
|
|
instructions = db.relationship('Instruction', backref='uploaded_by',
|
|
lazy='dynamic')
|
|
|
|
def __repr__(self):
|
|
return f'<User {self.username}>'
|
|
|
|
def set_password(self, password):
|
|
"""Hash and set the user's password."""
|
|
self.password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
|
|
|
|
def check_password(self, password):
|
|
"""Check if the provided password matches the hash."""
|
|
return bcrypt.check_password_hash(self.password_hash, password)
|
|
|
|
def to_dict(self):
|
|
"""Convert user to dictionary."""
|
|
return {
|
|
'id': self.id,
|
|
'username': self.username,
|
|
'email': self.email,
|
|
'created_at': self.created_at.isoformat()
|
|
}
|