Esempio n. 1
0
class User(db.Model, BaseMixin):
    __tablename__ = 'users'

    username = db.Column(db.String, nullable=False)
    _password = db.Column(db.LargeBinary(60))
    is_admin = db.Column(db.Boolean)
    email = db.Column(db.String)
    free_user = db.Column(db.Boolean, default=True)
    pro_user = db.Column(db.Boolean, default=False)
    #reviere = db.relationship('Revier', backref="User", lazy=False)
    #tagebucheintraege = db.relationship('Tagebucheintrag', backref='User', lazy=False)

    def __init__(self, username, password, email):
        self.username = username
        self._password = self.hash_pw(password.encode('uft-8'))
        self.email = email

    def hash_pw(self, password):
        return bcrypt.hashpw(password, bcrypt.gensalt(12))
    
    def check_pw(self, password, hashed_pw):
        return bcrypt.checkpw(password.encode('utf-8'), hashed_pw)

    @classmethod
    def find_by_username(cls, username):
        return cls.query.filter_by(username=username).first()
Esempio n. 2
0
class User(db.Model, BaseMixin):
    __tablename__ = 'users'

    username = db.Column(db.String(60), nullable=False)
    _password = db.Column(db.LargeBinary(60))
    vorname = db.Column(db.String(60))
    nachname = db.Column(db.String(60))
    is_admin = db.Column(db.Boolean)
    email = db.Column(db.String(60))
    key_ID = db.Column(db.String(60))
    coffee_count = db.Column(db.Integer, default=0)
    #kassenbuch_eintraege = db.relationship("Kassenbuch", backref="User", lazy=False)

    def __init__(self, username, password, email):
        self.username = username
        self._password = self.hash_pw(password.encode('utf-8'))
        self.email = email


    def hash_pw(self, password):
        return bcrypt.hashpw(password, bcrypt.gensalt(12))
    
    def check_pw(self, password, hashed_pw):
        return bcrypt.checkpw(password.encode('utf-8'), hashed_pw)

    @classmethod
    def find_by_username(cls, username):
        return cls.query.filter_by(username=username).first()
Esempio n. 3
0
class Bots(db.Model):
    __table_args__ = {"schema": settings.SQLALCHEMY_DATABASE_SCHEMA}
    __tablename__ = "bots"
    id = db.Column(db.BigInteger(), primary_key = True, autoincrement = False)
    username = db.Column(db.String(255), nullable = False)
    fullname = db.Column(db.String(255), default = '')
    email = db.Column(db.Text, nullable = False)
    password = db.Column(db.String(64), nullable = False)
    proxy = db.Column(db.String(64), nullable = True)
    profile_pic_url = db.Column(db.Text, nullable = False)
    external_url = db.Column(db.String(64), nullable = True)
    biography = db.Column(db.Text, nullable = True)
    gender = db.Column(db.String(10), nullable = True)
    private = db.Column(db.Boolean, nullable = False, default = False)
    checkpoint = db.Column(db.LargeBinary(), nullable = True)
    created_on = db.Column(db.Date, default = date.today())
    updated_on = db.Column(db.Date,
                           default = date.today(),
                           onupdate = date.today())

    def __repr__(self):
        return "<Bot(username={username}, fullname={fullname}, email={email}, password={password}, " \
               "proxy={proxy}, external_url={external_url}, gender={gender}, is_private={private})>" \
            .format(
                username = self.username,
                fullname = self.fullname,
                email = self.email,
                password = self.password,
                proxy = self.proxy,
                external_url = self.external_url,
                gender = self.gender,
                private = bool(self.private)
            )

    pass
Esempio n. 4
0
class User(UserMixin, SurrogatePK, Model, EntityBase):
    """A user of the app."""

    __tablename__ = "users"
    account = Column(db.String(80), unique=True, nullable=False)
    email = Column(db.String(80), unique=True, nullable=False)
    #: The hashed password
    password = Column(db.LargeBinary(128), nullable=True)
    created_at = Column(db.DateTime,
                        nullable=False,
                        default=dt.datetime.utcnow)
    first_name = Column(db.String(30), nullable=True)
    last_name = Column(db.String(30), nullable=True)
    active = Column(db.Boolean(), default=False)
    is_admin = Column(db.Boolean(), default=False)

    def __init__(self, account, email, password=None, **kwargs):
        """Create instance."""
        db.Model.__init__(self, account=account, email=email, **kwargs)
        if password:
            self.set_password(password)
        else:
            self.password = None

    def get_id(self):
        """获取用户ID"""
        return self.id

    def set_password(self, password):
        """Set password."""
        self.password = bcrypt.generate_password_hash(password)

    def check_password(self, value):
        """Check password."""
        return bcrypt.check_password_hash(self.password, value)

    @property
    def full_name(self):
        """Full user name."""
        return f"{self.first_name} {self.last_name}"

    def __repr__(self):
        """Represent instance as a unique string."""
        return f"<User({self.account!r})>"

    @classmethod
    def verify_auth_token(cls, token):
        data = jwt.decode(token,
                          current_app.config["SECRET_KEY"],
                          algorithms=['HS256'])
        return cls.query.get(data["id"])

    def generate_token(self):
        return jwt.encode({"id": self.id},
                          current_app.config["SECRET_KEY"],
                          algorithm='HS256')
Esempio n. 5
0
class User(UserMixin, SurrogatePK, Model):
    """A user of the app."""

    __tablename__ = "users"
    username = Column(db.String(80), unique=True, nullable=False)
    email = Column(db.String(80), unique=True, nullable=False)
    #: The hashed password
    password = Column(db.LargeBinary(128), nullable=True)
    created_at = Column(db.DateTime,
                        nullable=False,
                        default=dt.datetime.utcnow)
    first_name = Column(db.String(30), nullable=True)
    last_name = Column(db.String(30), nullable=True)
    active = Column(db.Boolean(), default=False)
    is_admin = Column(db.Boolean(), default=False)

    def __init__(self, username, email, password=None, **kwargs):
        """Create instance."""
        db.Model.__init__(self, username=username, email=email, **kwargs)
        if password:
            self.set_password(password)
        else:
            self.password = None

    def set_password(self, password):
        """Set password."""
        self.password = bcrypt.generate_password_hash(password)

    def check_password(self, value):
        """Check password."""
        return bcrypt.check_password_hash(self.password, value)

    @property
    def full_name(self):
        """Full user name."""
        return f"{self.first_name} {self.last_name}"

    def __repr__(self):
        """Represent instance as a unique string."""
        return f"<User({self.username!r})>"
Esempio n. 6
0
class User(db.Model, BaseMixin):
    __tablename__ = 'users'

    username = db.Column(db.String, nullable=False)
    _password = db.Column(db.LargeBinary(60))
    is_admin = db.Column(db.Boolean)
    email = db.Column(db.String)

    def __init__(self, username, password, email):
        self.username = username
        self._password = self.hash_pw(password.encode('utf-8'))
        self.email = email

    def hash_pw(self, password):
        return bcrypt.hashpw(password, bcrypt.gensalt(12))

    def check_pw(self, password, hashed_pw):
        return bcrypt.checkpw(password.encode('utf-8'), hashed_pw)

    @classmethod
    def find_by_username(cls, username):
        return cls.query.filter_by(username=username).first()
Esempio n. 7
0
class User(BaseMixin, db.Model):
    __tablename__ = "users"
    
    userID = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String, nullable=False)
    _password = db.Column(db.LargeBinary(60))
    email = db.Column(db.String, nullable=False)
    is_active = db.Column(db.Boolean, default=True)
    is_admin = db.Column(db.Boolean, default=False)
    
    def __init__(self, username, password, email):
        self.username = username
        self._password = self.hash_pw(password.encode('utf-8'))
        self.email = email
        
    def hash_pw(self, password): 
        return bcrypt.hashpw(password, bcrypt.gensalt(13))
    
    def check_pw(self, password, hashed_pw):
        return bcrypt.checkpw(password.encode('utf-8'), hashed_pw)

    @classmethod
    def find_by_username(cls, username):
        return cls.query.filter_by(username=username).first()
Esempio n. 8
0
class User(UserMixin, SurrogatePK, Model):
    """A user of the app."""

    __tablename__ = 'users'
    username = Column(db.String(80), unique=True, nullable=False)
    email = Column(db.String(80), unique=True, nullable=False)
    #: The hashed password
    password = Column(db.LargeBinary(128), nullable=True)
    first_name = Column(db.String(30), nullable=True)
    last_name = Column(db.String(30), nullable=True)
    active = Column(db.Boolean(), default=False)
    is_admin = Column(db.Boolean(), default=False)
    email_confirmed = Column(db.Boolean(), nullable=True, default=False)
    email_confirmed_at = Column(db.DateTime(timezone=True), nullable=True)
    locale = db.Column(db.String(length=2), default='en')
    created_at = Column(db.DateTime(timezone=True),
                        nullable=False,
                        default=maya.now().datetime)
    last_seen = db.Column(db.DateTime(timezone=True))
    last_message_read_time = db.Column(db.DateTime(timezone=True))

    notifications = db.relationship('Notification',
                                    backref='user',
                                    lazy='dynamic')
    tasks = db.relationship('Task', backref='user', lazy='dynamic')
    messages = db.relationship('Message',
                               back_populates='user',
                               lazy='dynamic')

    def __init__(self,
                 username: str,
                 email: str,
                 password: str = None,
                 **kwargs) -> None:
        """Create instance."""
        db.Model.__init__(self, username=username, email=email, **kwargs)
        if password:
            self.set_password(password)
        else:
            self.password = None

    def set_password(self, password: str) -> None:
        """Set password."""
        self.password = bcrypt.generate_password_hash(password)

    def check_password(self, value: str) -> bool:
        """Check password."""
        is_good_password: bool = bcrypt.check_password_hash(
            self.password, value)
        return is_good_password

    @property
    def full_name(self) -> str:
        """Full user name."""
        return '{0} {1}'.format(self.first_name, self.last_name)

    def __repr__(self) -> str:
        """Represent instance as a unique string."""
        return '<User({username!r})>'.format(username=self.username)

    def get_reset_password_token(self, expires_in: int = 600) -> str:
        token: str = jwt.encode(
            {
                'reset_password': self.id,
                'exp': time() + expires_in
            },
            current_app.config['SECRET_KEY'],
            algorithm='HS256')
        return token

    @staticmethod
    def verify_reset_password_token(token) -> Union['User', None]:
        try:
            user_id = jwt.decode(token,
                                 current_app.config['SECRET_KEY'],
                                 algorithms=['HS256'])['reset_password']
        except InvalidTokenError:
            return None
        user: User = User.query.get(user_id)
        return user

    def confirm_email(self) -> None:
        self.email_confirmed = True
        self.email_confirmed_at = maya.now().datetime()

    def get_confirmation_token(self) -> str:
        token: str = jwt.encode({'confirm_email': self.id},
                                current_app.config['SECRET_KEY'],
                                algorithm='HS256')
        return token

    @staticmethod
    def verify_confirmation_token(token: str) -> Union['User', None]:
        try:
            user_id = jwt.decode(token,
                                 current_app.config['SECRET_KEY'],
                                 algorithms=['HS256'])['confirm_email']
        except PyJWTError:
            return None
        user: User = User.query.get(user_id)
        return user

    def avatar(self, size):
        digest = md5(self.email.lower().encode('utf-8')).hexdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(
            digest, size)

    def add_notification(self, name, data):
        notification = self.notifications.filter_by(user=self,
                                                    name=name).first()

        if notification:
            notification.update(payload=data)
        else:
            notification = Notification.create(name=name,
                                               payload=data,
                                               user=self)
        return notification

    def launch_task(self, name, description, *args, **kwargs):
        rq_job = current_app.task_queue.enqueue('app.task.tasks.' + name,
                                                *args, **kwargs)
        task = Task(id=rq_job.get_id(),
                    name=name,
                    description=description,
                    user=self)
        db.session.add(task)
        return task

    def get_tasks_in_progress(self):
        return Task.query.filter_by(user=self, complete=False).all()

    def get_task_in_progress(self, name):
        return Task.query.filter_by(user=self, name=name,
                                    complete=False).first()

    def add_message(self, contents):
        message = Message.create(user=self, body=contents)
        return message

    def new_messages(self):
        last_read_time = self.last_message_read_time or maya.when(
            '1900-1-1').datetime()
        return Message.query.filter_by(user=self).filter(
            Message.timestamp > last_read_time).count()