51 lines
1.6 KiB
Python
51 lines
1.6 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
数据库模型 - 用户管理
|
|
"""
|
|
from flask_sqlalchemy import SQLAlchemy
|
|
from werkzeug.security import generate_password_hash, check_password_hash
|
|
from flask_login import UserMixin
|
|
|
|
db = SQLAlchemy()
|
|
|
|
class User(UserMixin, db.Model):
|
|
"""用户模型"""
|
|
__tablename__ = 'users'
|
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
username = db.Column(db.String(80), unique=True, nullable=False)
|
|
password_hash = db.Column(db.String(200), nullable=False)
|
|
created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
|
|
|
|
def set_password(self, password):
|
|
self.password_hash = generate_password_hash(password)
|
|
|
|
def check_password(self, password):
|
|
return check_password_hash(self.password_hash, password)
|
|
|
|
def to_dict(self):
|
|
return {
|
|
'id': self.id,
|
|
'username': self.username,
|
|
'created_at': self.created_at.isoformat() if self.created_at else None
|
|
}
|
|
|
|
|
|
def init_default_users():
|
|
"""初始化默认用户(如果不存在)"""
|
|
default_users = [
|
|
{'username': 'admin', 'password': 'abcd1234'},
|
|
{'username': 'caixianming', 'password': 'cxm123456'}
|
|
]
|
|
|
|
for user_data in default_users:
|
|
# 检查用户是否已存在
|
|
existing = User.query.filter_by(username=user_data['username']).first()
|
|
if not existing:
|
|
user = User(username=user_data['username'])
|
|
user.set_password(user_data['password'])
|
|
db.session.add(user)
|
|
print(f"✅ 创建默认用户: {user_data['username']}")
|
|
|
|
db.session.commit()
|