2023-04-20 13:10:16 +00:00
|
|
|
from uuid import uuid4
|
|
|
|
|
|
|
|
from flask_login import UserMixin, AnonymousUserMixin
|
|
|
|
from sqlalchemy import func
|
|
|
|
from sqlalchemy.ext.hybrid import hybrid_property
|
|
|
|
from werkzeug.security import generate_password_hash, check_password_hash
|
|
|
|
|
|
|
|
from app import db
|
2023-04-21 12:58:47 +00:00
|
|
|
from app.models.utils import BaseModel
|
2023-04-20 13:10:16 +00:00
|
|
|
from app.logger import log
|
|
|
|
from app import schema as s
|
|
|
|
|
|
|
|
|
2023-05-04 11:18:49 +00:00
|
|
|
def gen_uniq_id() -> str:
|
2023-04-20 13:10:16 +00:00
|
|
|
return str(uuid4())
|
|
|
|
|
|
|
|
|
2023-04-21 12:58:47 +00:00
|
|
|
class User(BaseModel, UserMixin):
|
2023-04-20 13:10:16 +00:00
|
|
|
__tablename__ = "users"
|
|
|
|
|
2023-05-04 11:18:49 +00:00
|
|
|
username = db.Column(db.String(64), unique=True, default=gen_uniq_id)
|
|
|
|
password_hash = db.Column(db.String(256), default="")
|
|
|
|
is_activated = db.Column(db.Boolean, default=False)
|
2023-05-05 14:05:35 +00:00
|
|
|
wallet_id = db.Column(db.String(64), nullable=True)
|
2023-05-04 11:18:49 +00:00
|
|
|
avatar_img = db.Column(db.Text, nullable=True)
|
2023-04-21 12:58:47 +00:00
|
|
|
# Relationships
|
|
|
|
stars = db.relationship("Book", secondary="books_stars", back_populates="stars")
|
|
|
|
books = db.relationship("Book")
|
2023-04-20 13:10:16 +00:00
|
|
|
|
|
|
|
@hybrid_property
|
|
|
|
def password(self):
|
|
|
|
return self.password_hash
|
|
|
|
|
|
|
|
@password.setter
|
|
|
|
def password(self, password):
|
|
|
|
self.password_hash = generate_password_hash(password)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def authenticate(cls, user_id, password):
|
|
|
|
user = cls.query.filter(
|
2023-04-20 14:37:38 +00:00
|
|
|
func.lower(cls.username) == func.lower(user_id),
|
2023-04-20 13:10:16 +00:00
|
|
|
).first()
|
|
|
|
if not user:
|
|
|
|
log(log.WARNING, "user:[%s] not found", user_id)
|
|
|
|
|
|
|
|
if user is not None and check_password_hash(user.password, password):
|
|
|
|
return user
|
|
|
|
|
|
|
|
def __repr__(self):
|
2023-04-20 14:37:38 +00:00
|
|
|
return f"<{self.id}: {self.username}>"
|
2023-04-20 13:10:16 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def json(self):
|
|
|
|
u = s.User.from_orm(self)
|
|
|
|
return u.json()
|
|
|
|
|
|
|
|
|
|
|
|
class AnonymousUser(AnonymousUserMixin):
|
|
|
|
pass
|