user.py 1.41 KB
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version     : Python 3.11.4
# @Software    : Sublime Text 4
# @Author      : StudentCWZ
# @Email       : StudentCWZ@outlook.com
# @Date        : 2023/10/28 22:12
# @File        : user.py
# @Description :
"""

from sqlalchemy.ext.hybrid import hybrid_property

from application.extensions.init_bcrypt import bcrypt
from application.extensions.init_sqlalchemy import db


class User(db.Model):
    """Basic user model"""

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(80), unique=True, nullable=False)
    _password = db.Column("password", db.String(255), nullable=False)
    active = db.Column(db.Boolean, default=True)

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def password(self, password: str):
        self._password = bcrypt.generate_password_hash(password).decode('utf-8')

    def check_password(self, password: str):
        # 判断传过来的密码是否与数据库存的密码一致
        return bcrypt.check_password_hash(self._password, password)

    def to_dict(self) -> dict:
        """object to dict"""
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
        }

    def __repr__(self) -> str:
        return f'<User {self.username}>'