Beispiel #1
0
class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer(), primary_key=True)
    timestamp = db.Column(db.DateTime(),
                          default=datetime.strftime(datetime.utcnow),
                          index=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(EmailType(), unique=True, nullable=False)
    password = db.Column(db.String)
    verification = db.Column(db.String(6),
                             default=None,
                             unique=False,
                             nullable=True)

    def __init__(self, username, email, password):
        self.username = username
        self.email = email
        self.password = password

    def __repr__(self):
        return '<id {}>'.format(self, id)

    def serialize(self):
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'password': self.password,
            'verification': self.verification,
        }
Beispiel #2
0
class User(db.Model):
    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(EmailType(), unique=True, nullable=False)
    avatar = db.Column(db.String(40))

    fullname = db.Column(db.String(20))
    bio = db.Column(db.Text())

    posts = db.relationship("Post", back_populates="user")

    likes = db.relationship("Post", secondary=Likes, back_populates="likes")

    comments = db.relationship("Comments", back_populates="user")

    follows = db.relation("User",
                          secondary=Follows,
                          primaryjoin=Follows.c.user_id == id,
                          secondaryjoin=Follows.c.followed_user_id == id,
                          backref="children")

    followers = db.relation("User",
                            secondary=Follows,
                            primaryjoin=Follows.c.followed_user_id == id,
                            secondaryjoin=Follows.c.user_id == id,
                            backref="parents")

    def __repr__(self):
        return "<User %r>" % self.username
Beispiel #3
0
class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(length=32, collation=COL_ASCII_GENERAL_CI),
                         unique=True,
                         nullable=False)
    email = db.Column(EmailType(length=255, collation=COL_ASCII_GENERAL_CI),
                      unique=True,
                      nullable=True)
    password_hash = db.Column(PasswordType(max_length=255, schemes=['argon2']),
                              nullable=False)
    status = db.Column(ChoiceType(UserStatusType, impl=db.Integer()),
                       nullable=False)
    level = db.Column(ChoiceType(UserLevelType, impl=db.Integer()),
                      nullable=False)

    created_time = db.Column(db.DateTime(timezone=False),
                             default=datetime.utcnow)
    last_login_date = db.Column(db.DateTime(timezone=False),
                                default=None,
                                nullable=True)
    last_login_ip = db.Column(db.Binary(length=16),
                              default=None,
                              nullable=True)

    torrents = db.relationship('Torrent',
                               back_populates='user',
                               lazy="dynamic")

    # session = db.relationship('Session', uselist=False, back_populates='user')

    def __init__(self, username, email, password):
        self.username = username
        self.email = email
        self.password_hash = password
        self.status = UserStatusType.INACTIVE
        self.level = UserLevelType.REGULAR

    def __repr__(self):
        return '<User %r>' % self.username

    @classmethod
    def by_id(cls, id):
        return cls.query.get(id)

    @classmethod
    def by_username(cls, username):
        user = cls.query.filter_by(username=username).first()
        return user

    @classmethod
    def by_email(cls, email):
        user = cls.query.filter_by(email=email).first()
        return user

    @property
    def is_admin(self):
        return self.level is UserLevelType.ADMIN or self.level is UserLevelType.SUPERADMIN
Beispiel #4
0
class MailLogMixin:
    address = sa.Column(EmailType(), nullable=False)
    subject = sa.Column(sa.Unicode, nullable=False)
    status = sa.Column(sa.Enum(EmailLogStatus, name='enum_email_logs_status'), nullable=False)
    status_updated = sa.Column(ArrowType, nullable=True)
    message_id = sa.Column(sa.Unicode)
    message_uuid = sa.Column(sa.Unicode)
    error_detail = sa.Column(sa.Unicode)
    class User(Base):
        __tablename__ = 'user'
        id = sa.Column(sa.Integer, primary_key=True)
        email = sa.Column(EmailType)
        short_email = sa.Column(EmailType(length=70))

        def __repr__(self):
            return 'User(%r)' % self.id
Beispiel #6
0
class User(Base):  # type: ignore
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True, index=True, nullable=False)
    email = Column(EmailType(128), unique=True, index=True, nullable=False)
    first_name = Column(Unicode(255), nullable=False)
    last_name = Column(Unicode(255), nullable=False)
    bio = Column(Unicode(255))
    is_active = Column(Boolean, default=False)
Beispiel #7
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, info={'label': 'ID'})
    email = db.Column(EmailType(),
                      index=True,
                      unique=True,
                      info={'label': 'Email'})
    name = db.Column(db.String,
                     index=True,
                     nullable=False,
                     info={'label': 'Name'})
    password = db.Column(PasswordType(schemes=['pbkdf2_sha512']),
                         nullable=False,
                         info={'label': 'Password'})
    active = db.Column(db.Boolean,
                       default=False,
                       server_default=expression.false(),
                       info={'label': 'Active'})
    admin = db.Column(db.Boolean,
                      nullable=False,
                      default=False,
                      server_default=expression.false(),
                      info={'label': 'Admin'})

    tokens = db.relationship('Token',
                             backref='owner',
                             lazy='dynamic',
                             passive_deletes=True,
                             passive_updates=True)

    @property
    def is_authenticated(self):
        return self.active

    @property
    def is_active(self):
        return self.active

    @property
    def is_anonymous(self):
        return False

    def get_token(self, token_id):
        for token in self.tokens:
            if token.id == token_id:
                return token
        return None

    def get_id(self):
        return str(self.id)

    def __repr__(self):
        return '<User %r>' % self.id
Beispiel #8
0
class User(TorModel):
    __tablename__ = 'users'

    email = Column(EmailType(120), unique=True, nullable=False)

    first_name = Column(Unicode(25), nullable=False)
    last_name = Column(Unicode(25), nullable=False)

    phone = Column(String(15))  # PhoneNumberType

    password = Column(PasswordType(schemes=['pbkdf2_sha512', 'md5_crypt'],
                                   deprecated=['md5_crypt']),
                      info={'validators': []},
                      nullable=False)

    last_ip = Column(IPAddressType())

    type = Column(String(50))

    __mapper_args__ = {'polymorphic_identity': 'user', 'polymorphic_on': type}

    @property
    def full_name(self):
        return self.first_name + ' ' + self.last_name

    @classmethod
    def get_by_username(cls, username):
        if not username:
            return None

        return cls.query.filter(cls.username == username).first()

    @classmethod
    def get_by_email(cls, email):
        if not email:
            return None

        return cls.query.filter(cls.email == email).first()

    @classmethod
    def get_by_phone(cls, phone):
        if not phone:
            return None

        return cls.query.filter(cls.phone == phone).first()
Beispiel #9
0
class Author(db.Model):
    __tablename__ = 'authors'
    __table_args__ = (CheckConstraint('registered_date <= visited_data',
                                      name='visited_datetime'))

    author_id = Column(UUIDType(binary=False), primary_key=True, index=True)
    email = Column(EmailType(), nullable=False, unique=True, index=True)
    password = Column(PasswordType(schemes=['pbkdf2_sha512']), nullable=False)

    first_name = Column(String(35), nullable=False)
    last_name = Column(String(35), nullable=False)

    registered_date = Column(DateTime(timezone=False),
                             server_default=func.now(),
                             nullable=False)
    visited_data = Column(DateTime(timezone=False),
                          server_onupdate=func.now(),
                          nullable=False)
Beispiel #10
0
class Auth(Base):  # type: ignore
    __tablename__ = 'credentials'

    id = Column(Integer, primary_key=True, index=True)
    email = Column(EmailType(128), unique=True, index=True, nullable=False)
    hashed_password = Column(String(128), nullable=False)
    user_id = Column(Integer,
                     ForeignKey('users.id', ondelete='CASCADE'),
                     nullable=False,
                     index=True)

    @staticmethod
    def check_password(raw_pass: str, pass_hash: str) -> bool:
        return pbkdf2_sha256.verify(raw_pass, pass_hash)

    @staticmethod
    def get_pass_hash(raw_pass: str):
        return pbkdf2_sha256.hash(raw_pass)
Beispiel #11
0
class User(UserMixin, db.Model):
    __tablename__ = 'user'

    id = Column(UUIDType(binary=False), primary_key=True)
    username = Column(String(100), unique=True, nullable=False, index=True)
    name = Column(String(100), nullable=False)
    email = Column(EmailType(100), nullable=False)
    password_hash = Column(String(128), nullable=False)

    @property
    def password(self):
        raise AttributeError("Password is write only")

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)
Beispiel #12
0
class User(Base):
    __tablename__ = 'user'
    uuid = Column(UUIDType(binary=False), primary_key=True, default=uuid.uuid4)
    email = Column(EmailType(128), unique=True, nullable=False)
    username = Column(String(32), unique=True, nullable=False)
    password = Column(PasswordType(schemes=['pbkdf2_sha512']))
    firstname = Column(String(32), nullable=False)
    lastname = Column(String(32), nullable=False)

    status = Column(String(32), default='active')

    session_login = Column(Boolean, default=False)
    session_count = Column(Integer, default=0)

    roles = db.relationship('UserRole', back_populates='user')

    def get_id(self):
        return self.uuid

    @property
    def is_active(self):
        return self.status == 'active'

    @property
    def is_anonymous(self):
        return False

    @property
    def is_authenticated(self):
        return self.session_login

    def get_roles(self):
        user_roles = []
        for role in self.roles:
            user_roles.append(role.role_name)
        return user_roles

    def assign(self, roles):
        for role in roles:
            user_role = UserRole(user_uuid=self.uuid, role_name=role)
            db.session.add(user_role)
            db.session.commit()
Beispiel #13
0
class User(db.Model):
    """
    This is a base user Model
    """
    __tablename__ = 'users'

    id = db.Column(Integer, primary_key=True)
    fullname = db.Column(String(100), nullable=False)
    username = db.Column(String(20), nullable=False, unique=True)
    password = db.Column(String(50), nullable=False)
    email = db.Column(EmailType(), nullable=False, unique=True)

    def __init__(self, fullname, username, password, email):
        self.fullname = fullname
        self.username = username
        self.password = password
        self.email = email

    def __repr__(self):
        return "<User(fullname='%s', username='******')>" % (self.fullname,
                                                         self.username)
Beispiel #14
0
class User(Base):
    __tablename__ = "user"

    id = Column(Integer, unique=True, primary_key=True)
    email = Column(EmailType(length=128), nullable=False)
    password = Column(PasswordType(schemes=['pbkdf2_sha512', 'md5_crypt'],
                                   deprecated=['md5_crypt']),
                      nullable=False)
    name = Column(String(128))

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.id)
Beispiel #15
0
class Invitation(Base):

    read = update = delete = AccessibleIfUserMatches('invited_by')

    token = sa.Column(sa.String(), nullable=False, unique=True)
    role_id = sa.Column(
        sa.ForeignKey('roles.id'),
        nullable=False,
    )
    role = relationship(
        "Role",
        cascade="save-update, merge, refresh-expire, expunge",
        passive_deletes=True,
        uselist=False,
    )
    groups = relationship(
        "Group",
        secondary="group_invitations",
        cascade="save-update, merge, refresh-expire, expunge",
        passive_deletes=True,
    )
    streams = relationship(
        "Stream",
        secondary="stream_invitations",
        cascade="save-update, merge, refresh-expire, expunge",
        passive_deletes=True,
    )
    admin_for_groups = sa.Column(psql.ARRAY(sa.Boolean), nullable=False)
    can_save_to_groups = sa.Column(psql.ARRAY(sa.Boolean), nullable=False)
    user_email = sa.Column(EmailType(), nullable=True)
    invited_by = relationship(
        "User",
        secondary="user_invitations",
        cascade="save-update, merge, refresh-expire, expunge",
        passive_deletes=True,
        uselist=False,
    )
    used = sa.Column(sa.Boolean, nullable=False, default=False)
    user_expiration_date = sa.Column(sa.DateTime, nullable=True)
Beispiel #16
0
class User(BaseModel):
    __tablename__ = "users"

    email = db.Column(EmailType(length=255), unique=True)
    username = db.Column(db.String(32), unique=True, nullable=False)
    password_hash = db.Column(PasswordType(max_length=255, schemes=['argon2']), nullable=False)
    status = db.Column(ChoiceType(UserStatus, impl=db.Integer()), nullable=False)
    level = db.Column(ChoiceType(UserLevel, impl=db.Integer()), nullable=False)
    created_time = db.Column(db.DateTime(timezone=False), default=datetime.utcnow, nullable=False)
    last_login_date = db.Column(db.DateTime(timezone=False), default=None)

    def __init__(self, username, password, email=None):
        self.username = username
        self.password_hash = password
        self.email = email
        self.status = UserStatus.ACTIVE  # if I add email verification later, this will change.
        self.level = UserLevel.STANDARD

    @classmethod
    def by_username(cls, username):
        user = cls.query.filter_by(username=username).first()
        return user

    @classmethod
    def by_id(cls, uid):
        user = cls.query.filter_by(id=uid).first()
        return user

    @property
    def is_active(self):
        return self.status == UserStatus.ACTIVE

    @property
    def is_mod(self):
        return self.level >= UserLevel.MOD

    @property
    def is_admin(self):
        return self.level >= UserLevel.ADMIN
Beispiel #17
0
class User(db.Model):
    __tablename__ = "users"

    id = db.Column(db.BigInteger(),
                   primary_key=True,
                   nullable=False,
                   autoincrement=True)
    # name = db.Column(db.Unicode(), nullable=False)
    email = db.Column(EmailType(), index=True, nullable=False)
    password = db.Column(
        PasswordType(schemes=["pbkdf2_sha512", "md5_crypt"],
                     deprecated=["md5_crypt"]))
    first_name = db.Column(db.String(), nullable=False)
    last_name = db.Column(db.String(), nullable=False)
    is_active = db.Column(db.Boolean(), default=False, nullable=False)

    def verify_password(self, password):
        """
        Verfiy the give password with the DB passowrd values
        """

        return self.password == password

    def to_dict(self):
        """
        Return the dict for Sanic it is very useful for
        sending json if the instance SELECTED based on 
        query condtion.
        """
        properties = ["id", "email", "is_active"]
        return {prop: getattr(self, prop, None) for prop in properties}

    def __str__(self):
        return "{}<{}>".format(self.name, self.id)

    def __repr__(self):
        return self.__str__()
Beispiel #18
0
class Monkey(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    email = db.Column(EmailType(), nullable=False, unique=True)
    age = db.Column(db.Integer, nullable=False)

    friends = db.relationship(
        'Monkey', secondary=monkey_friends, 
        primaryjoin=id==monkey_friends.c.monkey_id,
        secondaryjoin=id==monkey_friends.c.friend_id,
        backref='friended_by',
        foreign_keys=[monkey_friends.c.monkey_id, monkey_friends.c.friend_id]
    )

    best_friend = db.relationship(
        'Monkey', secondary=best_friends, 
        primaryjoin=id==best_friends.c.monkey_id,
        secondaryjoin=id==best_friends.c.friend_id,
        foreign_keys=[best_friends.c.monkey_id, best_friends.c.friend_id], 
        remote_side=[id], uselist=False, post_update=True, 
        backref='best_friended_by'
    )

    def __init__(self, name=None, email=None, age=None, friends=[], 
                 best_friend=None):
        self.name = name
        self.email = email
        self.age = age
        self.friends = friends
        self.best_friend = best_friend

    def __repr__(self):
        return '<{cls} id={id}, name={name}>'.format(
            id=self.id,
            cls=self.__class__.__name__,
            name=self.name
        )
Beispiel #19
0
class User(BaseModel):
    __tablename__ = "user"

    id = Column(Integer, primary_key=True, autoincrement=True)
    first_name = Column(String(length=50))
    last_name = Column(String(length=50))
    email = Column(EmailType(length=50), unique=True)
    password = Column(
        PasswordType(schemes=["pbkdf2_sha512", "md5_crypt"],
                     deprecated=["md5_crypt"]))
    city = Column(String)
    district = Column(String)
    projects = relationship("Project",
                            secondary="project_responsibility",
                            back_populates="responsible")
    votes = relationship("Project",
                         secondary="user_project_votes",
                         back_populates="project_votes")
    roles = relationship("Role",
                         secondary="user_roles",
                         back_populates="users")

    def __repr__(self):
        return f"{self.first_name} {self.last_name} from {self.city}"
Beispiel #20
0
class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(length=32, collation=COL_ASCII_GENERAL_CI),
                         unique=True,
                         nullable=False)
    email = db.Column(EmailType(length=255, collation=COL_ASCII_GENERAL_CI),
                      unique=True,
                      nullable=True)
    password_hash = db.Column(PasswordType(max_length=255, schemes=['argon2']),
                              nullable=False)
    status = db.Column(ChoiceType(UserStatusType, impl=db.Integer()),
                       nullable=False)
    level = db.Column(ChoiceType(UserLevelType, impl=db.Integer()),
                      nullable=False)

    created_time = db.Column(db.DateTime(timezone=False),
                             default=datetime.utcnow)
    last_login_date = db.Column(db.DateTime(timezone=False),
                                default=None,
                                nullable=True)
    last_login_ip = db.Column(db.Binary(length=16),
                              default=None,
                              nullable=True)

    torrents = db.relationship('Torrent',
                               back_populates='user',
                               lazy="dynamic")

    # session = db.relationship('Session', uselist=False, back_populates='user')

    def __init__(self, username, email, password):
        self.username = username
        self.email = email
        self.password_hash = password
        self.status = UserStatusType.INACTIVE
        self.level = UserLevelType.REGULAR

    def __repr__(self):
        return '<User %r>' % self.username

    def validate_authorization(self, password):
        ''' Returns a boolean for whether the user can be logged in '''
        checks = [
            # Password must match
            password == self.password_hash,
            # Reject inactive and banned users
            self.status == UserStatusType.ACTIVE
        ]
        return all(checks)

    @classmethod
    def by_id(cls, id):
        return cls.query.get(id)

    @classmethod
    def by_username(cls, username):
        user = cls.query.filter_by(username=username).first()
        return user

    @classmethod
    def by_email(cls, email):
        user = cls.query.filter_by(email=email).first()
        return user

    @classmethod
    def by_username_or_email(cls, username_or_email):
        return cls.by_username(username_or_email) or cls.by_email(
            username_or_email)

    @property
    def is_admin(self):
        return self.level >= UserLevelType.ADMIN

    @property
    def is_superadmin(self):
        return self.level == UserLevelType.SUPERADMIN

    @property
    def is_trusted(self):
        return self.level >= UserLevelType.TRUSTED
Beispiel #21
0
class AnalysisService(Base):
    __tablename__ = 'analysis_services'

    read = create = update = delete = accessible_by_groups_members

    name = sa.Column(
        sa.String,
        unique=True,
        index=True,
        nullable=False,
        doc='Unique name/identifier of the analysis service.',
    )

    display_name = sa.Column(
        sa.String, nullable=False, doc='Display name of the analysis service.'
    )

    description = sa.Column(
        sa.String,
        nullable=True,
        doc=(
            'Long-form description of what the analysis service does,'
            ' what it returns, and what it requires. Could include'
            ' links to documentation and code here.'
        ),
    )

    version = sa.Column(
        sa.String,
        nullable=True,
        doc='Semantic version (or githash) of the analysis service.',
    )

    contact_name = sa.Column(
        sa.String,
        nullable=True,
        doc=(
            'Name of person responsible for the service (ie. the maintainer). '
            ' This person does not need to be part of this SkyPortal instance.'
        ),
    )

    contact_email = sa.Column(
        EmailType(),
        nullable=True,
        doc='Email address of the person responsible for the service.',
    )

    url = sa.Column(
        URLType,
        nullable=False,
        doc=(
            "URL to running service accessible to this SkyPortal instance. "
            " For example, http://localhost:5000/analysis/<service_name>."
        ),
    )

    optional_analysis_parameters = sa.Column(
        JSONType,
        nullable=True,
        default=dict,
        doc=(
            'Optional parameters to be passed to the analysis service, along with '
            'possible values to be shown in the UI. '
        ),
    )

    authentication_type = sa.Column(
        allowed_external_authentication_types,
        nullable=False,
        doc=(
            f'''Service authentiction method. One of: {', '.join(f"'{t}'" for t in AUTHENTICATION_TYPES)}.'''
            ' See https://docs.python-requests.org/en/master/user/authentication/'
        ),
    )

    _authinfo = sa.Column(
        StringEncryptedType(JSONType, cfg['app.secret_key'], AesEngine, 'pkcs5'),
        nullable=True,
        doc=('Contains authentication credentials for the service.'),
    )

    enabled = sa.Column(sa.Boolean, nullable=False, default=True)

    analysis_type = sa.Column(
        allowed_analysis_types,
        nullable=False,
        doc=f'''Type of analysis. One of: {', '.join(f"'{t}'" for t in ANALYSIS_TYPES)}''',
    )

    input_data_types = sa.Column(
        ARRAY(allowed_analysis_input_types),
        default=[],
        doc=(
            'List of allowed_analysis_input_types required by the service.'
            ' This data will be assembled and sent over to the analysis service.'
        ),
    )

    groups = relationship(
        "Group",
        secondary="group_analysisservices",
        cascade="save-update, merge, refresh-expire, expunge",
        passive_deletes=True,
        doc="Groups that can access to this analysis service.",
    )

    timeout = sa.Column(
        sa.Float,
        default=3600.0,
        doc="Max time in seconds to wait for the analysis service to complete.",
    )

    upload_only = sa.Column(
        sa.Boolean,
        default=False,
        doc=(
            "If true, the analysis service is an upload type, where the user is responsible"
            " for providing the input data to the service. If false, the service is "
            " called using the data provided in input_data_types"
        ),
    )

    obj_analyses = relationship(
        'ObjAnalysis',
        back_populates='analysis_service',
        cascade='save-update, merge, refresh-expire, expunge, delete-orphan, delete',
        passive_deletes=True,
        doc="Instances of analysis applied to specific objects",
    )

    @property
    def authinfo(self):
        if self._authinfo is None:
            return {}
        else:
            return json.loads(self._authinfo)

    @authinfo.setter
    def authinfo(self, value):
        self._authinfo = value
Beispiel #22
0
class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(length=32, collation=COL_ASCII_GENERAL_CI),
                         unique=True,
                         nullable=False)
    email = db.Column(EmailType(length=255, collation=COL_ASCII_GENERAL_CI),
                      unique=True,
                      nullable=True)
    password_hash = db.Column(PasswordType(max_length=255, schemes=['argon2']),
                              nullable=False)
    status = db.Column(ChoiceType(UserStatusType, impl=db.Integer()),
                       nullable=False)
    level = db.Column(ChoiceType(UserLevelType, impl=db.Integer()),
                      nullable=False)

    created_time = db.Column(db.DateTime(timezone=False),
                             default=datetime.utcnow)
    last_login_date = db.Column(db.DateTime(timezone=False),
                                default=None,
                                nullable=True)
    last_login_ip = db.Column(db.Binary(length=16),
                              default=None,
                              nullable=True)

    nyaa_torrents = db.relationship('NyaaTorrent',
                                    back_populates='user',
                                    lazy='dynamic')
    nyaa_comments = db.relationship('NyaaComment',
                                    back_populates='user',
                                    lazy='dynamic')

    sukebei_torrents = db.relationship('SukebeiTorrent',
                                       back_populates='user',
                                       lazy='dynamic')
    sukebei_comments = db.relationship('SukebeiComment',
                                       back_populates='user',
                                       lazy='dynamic')

    def __init__(self, username, email, password):
        self.username = username
        self.email = email
        self.password_hash = password
        self.status = UserStatusType.INACTIVE
        self.level = UserLevelType.REGULAR

    def __repr__(self):
        return '<User %r>' % self.username

    def validate_authorization(self, password):
        ''' Returns a boolean for whether the user can be logged in '''
        checks = [
            # Password must match
            password == self.password_hash,
            # Reject inactive and banned users
            self.status == UserStatusType.ACTIVE
        ]
        return all(checks)

    def gravatar_url(self):
        # from http://en.gravatar.com/site/implement/images/python/
        size = 120
        # construct the url
        default_avatar = flask.url_for('static',
                                       filename='img/avatar/default.png',
                                       _external=True)
        gravatar_url = 'https://www.gravatar.com/avatar/{}?{}'.format(
            md5(self.email.encode('utf-8').lower()).hexdigest(),
            urlencode({
                'd': default_avatar,
                's': str(size)
            }))
        return gravatar_url

    @property
    def userlevel_str(self):
        if self.level == UserLevelType.REGULAR:
            return 'User'
        elif self.level == UserLevelType.TRUSTED:
            return 'Trusted'
        elif self.level >= UserLevelType.MODERATOR:
            return 'Moderator'

    @property
    def userstatus_str(self):
        if self.status == UserStatusType.INACTIVE:
            return 'Inactive'
        elif self.status == UserStatusType.ACTIVE:
            return 'Active'
        elif self.status == UserStatusType.BANNED:
            return 'Banned'

    @property
    def userlevel_color(self):
        if self.level == UserLevelType.REGULAR:
            return 'default'
        elif self.level == UserLevelType.TRUSTED:
            return 'success'
        elif self.level >= UserLevelType.MODERATOR:
            return 'purple'

    @property
    def ip_string(self):
        if self.last_login_ip:
            return str(ip_address(self.last_login_ip))

    @classmethod
    def by_id(cls, id):
        return cls.query.get(id)

    @classmethod
    def by_username(cls, username):
        user = cls.query.filter_by(username=username).first()
        return user

    @classmethod
    def by_email(cls, email):
        user = cls.query.filter_by(email=email).first()
        return user

    @classmethod
    def by_username_or_email(cls, username_or_email):
        return cls.by_username(username_or_email) or cls.by_email(
            username_or_email)

    @property
    def is_moderator(self):
        return self.level >= UserLevelType.MODERATOR

    @property
    def is_superadmin(self):
        return self.level == UserLevelType.SUPERADMIN

    @property
    def is_trusted(self):
        return self.level >= UserLevelType.TRUSTED
Beispiel #23
0
class User(Base):
    """An application user."""

    username = sa.Column(SlugifiedStr,
                         nullable=False,
                         unique=True,
                         doc="The user's username.")

    first_name = sa.Column(sa.String,
                           nullable=True,
                           doc="The User's first name.")
    last_name = sa.Column(sa.String,
                          nullable=True,
                          doc="The User's last name.")
    contact_email = sa.Column(
        EmailType(),
        nullable=True,
        doc="The phone number at which the user prefers to receive "
        "communications.",
    )
    contact_phone = sa.Column(
        PhoneNumberType(),
        nullable=True,
        doc="The email at which the user prefers to receive "
        "communications.",
    )
    oauth_uid = sa.Column(sa.String, unique=True, doc="The user's OAuth UID.")
    preferences = sa.Column(JSONB,
                            nullable=True,
                            doc="The user's application settings.")

    roles = relationship(
        'Role',
        secondary='user_roles',
        back_populates='users',
        passive_deletes=True,
        doc='The roles assumed by this user.',
    )
    role_ids = association_proxy(
        'roles',
        'id',
        creator=lambda r: Role.query.get(r),
    )
    tokens = relationship(
        'Token',
        cascade='save-update, merge, refresh-expire, expunge',
        back_populates='created_by',
        passive_deletes=True,
        doc="This user's tokens.",
        foreign_keys="Token.created_by_id",
    )
    acls = relationship(
        "ACL",
        secondary="user_acls",
        passive_deletes=True,
        doc="ACLs granted to user, separate from role-level ACLs",
    )

    @property
    def gravatar_url(self):
        """The Gravatar URL inferred from the user's contact email, or, if the
        contact email is null, the username."""
        email = self.contact_email if self.contact_email is not None else self.username

        digest = md5(email.lower().encode('utf-8')).hexdigest()
        # return a transparent png if not found on gravatar
        return f'https://secure.gravatar.com/avatar/{digest}?d=blank'

    @property
    def _acls_from_roles(self):
        """List of the ACLs associated with the user's role(s)."""
        return list({acl for role in self.roles for acl in role.acls})

    @property
    def permissions(self):
        """List of the names of all of the user's ACLs (role-level + individual)."""
        return list({acl.id
                     for acl in self.acls
                     }.union({acl.id
                              for acl in self._acls_from_roles}))

    @classmethod
    def user_model(cls):
        """The base model for User subclasses."""
        return User

    def is_authenticated(self):
        """Boolean flag indicating whether the User is currently
        authenticated."""
        return True

    def is_active(self):
        """Boolean flag indicating whether the User is currently active."""
        return True

    is_admin = property(is_admin)
Beispiel #24
0
class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(length=32, collation=COL_ASCII_GENERAL_CI),
                         unique=True,
                         nullable=False)
    email = db.Column(EmailType(length=255, collation=COL_ASCII_GENERAL_CI),
                      unique=True,
                      nullable=True)
    password_hash = db.Column(PasswordType(max_length=255, schemes=['argon2']),
                              nullable=False)
    status = db.Column(ChoiceType(UserStatusType, impl=db.Integer()),
                       nullable=False)
    level = db.Column(ChoiceType(UserLevelType, impl=db.Integer()),
                      nullable=False)

    created_time = db.Column(db.DateTime(timezone=False),
                             default=datetime.utcnow)
    last_login_date = db.Column(db.DateTime(timezone=False),
                                default=None,
                                nullable=True)
    last_login_ip = db.Column(db.Binary(length=16),
                              default=None,
                              nullable=True)
    registration_ip = db.Column(db.Binary(length=16),
                                default=None,
                                nullable=True)

    nyaa_torrents = db.relationship('NyaaTorrent',
                                    back_populates='user',
                                    lazy='dynamic')
    nyaa_comments = db.relationship('NyaaComment',
                                    back_populates='user',
                                    lazy='dynamic')

    sukebei_torrents = db.relationship('SukebeiTorrent',
                                       back_populates='user',
                                       lazy='dynamic')
    sukebei_comments = db.relationship('SukebeiComment',
                                       back_populates='user',
                                       lazy='dynamic')

    bans = db.relationship('Ban', uselist=True, foreign_keys='Ban.user_id')

    def __init__(self, username, email, password):
        self.username = username
        self.email = email
        self.password_hash = password
        self.status = UserStatusType.INACTIVE
        self.level = UserLevelType.REGULAR

    def __repr__(self):
        return '<User %r>' % self.username

    def validate_authorization(self, password):
        ''' Returns a boolean for whether the user can be logged in '''
        checks = [
            # Password must match
            password == self.password_hash,
            # Reject inactive and banned users
            self.status == UserStatusType.ACTIVE
        ]
        return all(checks)

    def gravatar_url(self):
        if 'DEFAULT_GRAVATAR_URL' in app.config:
            default_url = app.config['DEFAULT_GRAVATAR_URL']
        else:
            default_url = flask.url_for('static',
                                        filename='img/avatar/default.png',
                                        _external=True)
        if app.config['ENABLE_GRAVATAR']:
            # from http://en.gravatar.com/site/implement/images/python/
            params = {
                # Image size (https://en.gravatar.com/site/implement/images/#size)
                's': 120,
                # Default image (https://en.gravatar.com/site/implement/images/#default-image)
                'd': default_url,
                # Image rating (https://en.gravatar.com/site/implement/images/#rating)
                # Nyaa: PG-rated, Sukebei: X-rated
                'r': 'pg' if app.config['SITE_FLAVOR'] == 'nyaa' else 'x',
            }
            # construct the url
            return 'https://www.gravatar.com/avatar/{}?{}'.format(
                md5(self.email.encode('utf-8').lower()).hexdigest(),
                urlencode(params))
        else:
            return default_url

    @property
    def userlevel_str(self):
        level = ''
        if self.level == UserLevelType.REGULAR:
            level = 'User'
        elif self.level == UserLevelType.TRUSTED:
            level = 'Trusted'
        elif self.level == UserLevelType.MODERATOR:
            level = 'Moderator'
        elif self.level >= UserLevelType.SUPERADMIN:
            level = 'Administrator'
        if self.is_banned:
            level = 'BANNED ' + level
        return level

    @property
    def userstatus_str(self):
        if self.status == UserStatusType.INACTIVE:
            return 'Inactive'
        elif self.status == UserStatusType.ACTIVE:
            return 'Active'
        elif self.status == UserStatusType.BANNED:
            return 'Banned'

    @property
    def userlevel_color(self):
        color = ''
        if self.level == UserLevelType.REGULAR:
            color = 'default'
        elif self.level == UserLevelType.TRUSTED:
            color = 'success'
        elif self.level >= UserLevelType.MODERATOR:
            color = 'purple'
        if self.is_banned:
            color += ' strike'
        return color

    @property
    def ip_string(self):
        if self.last_login_ip:
            return str(ip_address(self.last_login_ip))

    @property
    def reg_ip_string(self):
        if self.registration_ip:
            return str(ip_address(self.registration_ip))

    @classmethod
    def by_id(cls, id):
        return cls.query.get(id)

    @classmethod
    def by_username(cls, username):
        def isascii(s):
            return len(s) == len(s.encode())

        if not isascii(username):
            return None

        user = cls.query.filter_by(username=username).first()
        return user

    @classmethod
    def by_email(cls, email):
        user = cls.query.filter_by(email=email).first()
        return user

    @classmethod
    def by_username_or_email(cls, username_or_email):
        return cls.by_username(username_or_email) or cls.by_email(
            username_or_email)

    @property
    def is_moderator(self):
        return self.level >= UserLevelType.MODERATOR

    @property
    def is_superadmin(self):
        return self.level == UserLevelType.SUPERADMIN

    @property
    def is_trusted(self):
        return self.level >= UserLevelType.TRUSTED

    @property
    def is_banned(self):
        return self.status == UserStatusType.BANNED

    @property
    def is_active(self):
        return self.status != UserStatusType.INACTIVE

    @property
    def age(self):
        '''Account age in seconds'''
        return (datetime.utcnow() - self.created_time).total_seconds()

    @property
    def created_utc_timestamp(self):
        ''' Returns a UTC POSIX timestamp, as seconds '''
        return (self.created_time - UTC_EPOCH).total_seconds()
Beispiel #25
0
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "amenities",
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column("title", sa.String(), nullable=False),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("title"),
    )
    op.create_table(
        "users",
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column("first_name", sa.String(), nullable=False),
        sa.Column("last_name", sa.String(), nullable=False),
        sa.Column("dob", sa.Date(), nullable=True),
        sa.Column("phone_number", sa.String(), nullable=True),
        sa.Column("email", EmailType(length=255), nullable=False),
        sa.Column("hashed_password", sa.Text(), nullable=True),
        sa.Column("email_verified", sa.Boolean(), nullable=False),
        sa.Column("phone_verified", sa.Boolean(), nullable=False),
        sa.Column("is_suspended", sa.Boolean(), nullable=False),
        sa.Column("suspended_reason", sa.String(), nullable=True),
        sa.Column("role",
                  ChoiceType(enums.UserRole, impl=sa.String()),
                  nullable=False),
        sa.Column("gender",
                  ChoiceType(enums.Gender, impl=sa.String()),
                  nullable=True),
        sa.Column("city", sa.String(), nullable=True),
        sa.Column("description", sa.String(), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("email"),
        sa.UniqueConstraint("phone_number"),
    )
    op.create_table(
        "apartments",
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column("name", sa.String(), nullable=False),
        sa.Column("monthly_price", sa.Float(), nullable=False),
        sa.Column("utilities_price", sa.Float(), nullable=False),
        sa.Column("address", sa.String(), nullable=False),
        sa.Column("country", sa.String(), nullable=False),
        sa.Column("state", sa.String(), nullable=False),
        sa.Column("city", sa.String(), nullable=False),
        sa.Column("description", sa.String(), nullable=False),
        sa.Column("house_type",
                  ChoiceType(enums.HouseType, impl=sa.String()),
                  nullable=False),
        sa.Column(
            "furnish_type",
            ChoiceType(enums.FurnishType, impl=sa.String()),
            nullable=False,
        ),
        sa.Column("bedrooms", sa.Integer(), nullable=False),
        sa.Column("bathrooms", sa.Integer(), nullable=False),
        sa.Column("size", sa.Float(), nullable=False),
        sa.Column("available_from", sa.Date(), nullable=False),
        sa.Column("available_to", sa.Date(), nullable=False),
        sa.Column(
            "location",
            geoalchemy2.types.Geometry(
                geometry_type="POINT",
                management=True,
                from_text="ST_GeomFromEWKT",
                name="geometry",
            ),
            nullable=True,
        ),
        sa.Column(
            "landlord_id",
            UUIDType(binary=False),
            nullable=False,
        ),
        sa.Column(
            "tenant_id",
            UUIDType(binary=False),
            nullable=True,
        ),
        sa.ForeignKeyConstraint(
            ["landlord_id"],
            ["users.id"],
        ),
        sa.ForeignKeyConstraint(
            ["tenant_id"],
            ["users.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_table(
        "bank_details",
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column("user_id", UUIDType(binary=False), nullable=True),
        sa.Column("account_name", sa.String(), nullable=False),
        sa.Column("account_number", sa.String(), nullable=False),
        sa.ForeignKeyConstraint(
            ["user_id"],
            ["users.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_table(
        "looking_for",
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column(
            "tenant_id",
            UUIDType(binary=False),
            nullable=True,
        ),
        sa.Column("house_type",
                  ChoiceType(enums.HouseType, impl=sa.String()),
                  nullable=False),
        sa.Column("city", sa.String(), nullable=False),
        sa.Column("max_budget", sa.Float(), nullable=False),
        sa.ForeignKeyConstraint(
            ["tenant_id"],
            ["users.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_table(
        "social_accounts",
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column("id_token", sa.String(), nullable=True),
        sa.Column("account_id", sa.String(), nullable=True),
        sa.Column(
            "account_email",
            EmailType(length=255),
            nullable=True,
        ),
        sa.Column("access_token", sa.String(), nullable=True),
        sa.Column(
            "account_type",
            ChoiceType(enums.SocialAccountType, impl=sa.String()),
            nullable=False,
        ),
        sa.Column(
            "user_id",
            UUIDType(binary=False),
            nullable=False,
        ),
        sa.ForeignKeyConstraint(
            ["user_id"],
            ["users.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("access_token"),
        sa.UniqueConstraint("account_email",
                            "account_type",
                            name="uix_email_type"),
        sa.UniqueConstraint("account_id", "account_type", name="uix_id_type"),
        sa.UniqueConstraint("id_token"),
    )
    op.create_table(
        "apartment_applications",
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column(
            "apartment_id",
            UUIDType(binary=False),
            nullable=False,
        ),
        sa.Column(
            "tenant_id",
            UUIDType(binary=False),
            nullable=False,
        ),
        sa.Column("is_rejected", sa.Boolean(), nullable=False),
        sa.Column("is_considered", sa.Boolean(), nullable=False),
        sa.ForeignKeyConstraint(
            ["apartment_id"],
            ["apartments.id"],
        ),
        sa.ForeignKeyConstraint(
            ["tenant_id"],
            ["users.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_table(
        "apartments_amenities_association",
        sa.Column(
            "apartment_id",
            UUIDType(binary=False),
            nullable=True,
        ),
        sa.Column(
            "amenity_id",
            UUIDType(binary=False),
            nullable=True,
        ),
        sa.ForeignKeyConstraint(
            ["amenity_id"],
            ["amenities.id"],
        ),
        sa.ForeignKeyConstraint(
            ["apartment_id"],
            ["apartments.id"],
        ),
    )
    op.create_table(
        "booking_requests",
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column(
            "tenant_id",
            UUIDType(binary=False),
            nullable=False,
        ),
        sa.Column(
            "apartment_id",
            UUIDType(binary=False),
            nullable=False,
        ),
        sa.Column(
            "apartment_application_id",
            UUIDType(binary=False),
            nullable=True,
        ),
        sa.Column(
            "status",
            ChoiceType(enums.BookingRequestStatus, impl=sa.String()),
            nullable=False,
        ),
        sa.ForeignKeyConstraint(
            ["apartment_application_id"],
            ["apartment_applications.id"],
        ),
        sa.ForeignKeyConstraint(
            ["apartment_id"],
            ["apartments.id"],
        ),
        sa.ForeignKeyConstraint(
            ["tenant_id"],
            ["users.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_table(
        "contracts",
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column(
            "apartment_application_id",
            UUIDType(binary=False),
            nullable=True,
        ),
        sa.Column("landlord_has_signed", sa.Boolean(), nullable=False),
        sa.Column("landlord_signed_on", sa.DateTime(), nullable=True),
        sa.Column("tenant_has_signed", sa.Boolean(), nullable=False),
        sa.Column("tenant_signed_on", sa.DateTime(), nullable=True),
        sa.Column("landlord_has_provided_keys", sa.Boolean(), nullable=False),
        sa.Column("landlord_provided_keys_on", sa.DateTime(), nullable=True),
        sa.Column("tenant_has_received_keys", sa.Boolean(), nullable=False),
        sa.Column("tenant_received_keys_on", sa.DateTime(), nullable=True),
        sa.Column("landlord_declined", sa.Boolean(), nullable=False),
        sa.Column("landlord_declined_on", sa.DateTime(), nullable=True),
        sa.Column("tenant_declined", sa.Boolean(), nullable=False),
        sa.Column("tenant_declined_on", sa.DateTime(), nullable=True),
        sa.Column("canceled", sa.Boolean(), nullable=False),
        sa.Column("canceled_on", sa.DateTime(), nullable=True),
        sa.Column("expired", sa.Boolean(), nullable=False),
        sa.Column("expired_on", sa.DateTime(), nullable=True),
        sa.ForeignKeyConstraint(
            ["apartment_application_id"],
            ["apartment_applications.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_table(
        "invoices",
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("id", UUIDType(binary=False), nullable=False),
        sa.Column("status",
                  ChoiceType(enums.InvoiceStatus, impl=sa.String()),
                  nullable=False),
        sa.Column("type",
                  ChoiceType(enums.InvoiceType, impl=sa.String()),
                  nullable=False),
        sa.Column("user_id", UUIDType(binary=False), nullable=True),
        sa.Column(
            "apartment_application_id",
            UUIDType(binary=False),
            nullable=True,
        ),
        sa.Column("amount", sa.Float(), nullable=False),
        sa.Column("description", sa.String(), nullable=True),
        sa.Column("payment_id", sa.String(), nullable=True),
        sa.Column("payment_action_date", sa.Date(), nullable=True),
        sa.Column("next_date", sa.Date(), nullable=False),
        sa.ForeignKeyConstraint(
            ["apartment_application_id"],
            ["apartment_applications.id"],
        ),
        sa.ForeignKeyConstraint(
            ["user_id"],
            ["users.id"],
        ),
        sa.PrimaryKeyConstraint("id"),
    )