class Link(db.Model): id = db.Column(db.String, primary_key=True, info={'label': 'ID'}) active = db.Column(db.Boolean, default=True, server_default=expression.true(), info={'label': 'Active'}) url = db.Column(URLType(), nullable=False, info={'label': 'URL'}) token_id = db.Column(db.String, db.ForeignKey('token.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False) def __init__(self, token, url): self.token_id = token.id self.generate_id() self.url = url def generate_id(self): self.id = _get_random_id(app.config['LINK_LENGTH'], Link, RemovedLink) return self.id def delete(self): db.session.add(RemovedLink(self)) db.session.delete(self) db.session.commit() def __repr__(self): return '<Link %r %r %r>' % (self.token_id, self.id, self.url)
class Pokemon(db.Model): __tablename__ = 'pokemon' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32)) stage = db.Column(db.Integer) galar_dex = db.Column(db.Integer) base_stats = db.Column(ScalarListType(int)) abilities = db.Column(ScalarListType()) types = db.Column(ScalarListType()) level_up_moves = db.Column(NestedMutableJson) egg_moves = db.Column(ScalarListType()) tms = db.Column(ScalarListType(int)) trs = db.Column(ScalarListType(int)) image = db.Column(URLType()) def __init__(self, id_no, name, stage, galar_dex, base_stats, abilities, types, level_up_moves, egg_moves, tms, trs): self.id = id_no self.name = name self.stage = stage self.galar_dex = galar_dex self.base_stats = base_stats self.abilities = abilities self.types = types self.level_up_moves = level_up_moves self.egg_moves = egg_moves self.tms = tms self.trs = trs def set_image_url(self, url): self.image = url
class Link(Base): __tablename__ = 'link' id = Column(Integer, primary_key=True, autoincrement=True) url = Column(URLType(), nullable=False) name = Column(Unicode(128)) public = Column(Boolean, default=True) last_modified = Column(BigInteger, nullable=False, default=_now)
class TestRail(Base): __tablename__ = 'testrail' id = Column(Integer, primary_key=True, autoincrement=True) project_id = Column(Integer, nullable=False) test_rail_server = Column(URLType()) public = Column(Boolean, default=True) last_modified = Column(BigInteger, nullable=False, default=_now) project_id = Column(Integer, ForeignKey('project.id')) project = relationship('Project', back_populates="testrail")
class JenkinsJob(Base): __tablename__ = 'jenkins_job' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(Unicode(128), nullable=False) jenkins_server = Column(URLType()) public = Column(Boolean, default=True) last_modified = Column(BigInteger, nullable=False, default=_now) project_id = Column(Integer, ForeignKey('project.id')) project = relationship('Project', back_populates="jenkins_jobs")
class Deployment(Base): __tablename__ = 'deployment' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(Unicode(128), nullable=False) endpoint = Column(URLType(), nullable=False) project_id = Column(Integer, ForeignKey('project.id')) project = relationship('Project', back_populates="deployments") last_modified = Column(BigInteger, nullable=False, default=_now) public = Column(Boolean, default=True)
class ProjectTest(Base): __tablename__ = 'project_test' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(Unicode(128), nullable=False) url = Column(URLType()) last_modified = Column(BigInteger, nullable=False, default=_now) operational = Column(Boolean, default=False) jenkins_pipeline = Column(Boolean, default=False) public = Column(Boolean, default=True) project_id = Column(Integer, ForeignKey('project.id')) project = relationship('Project', back_populates="tests")
def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table( 'Athlete_Fact', sa.Column('id', sa.Integer(), nullable=False), sa.Column('objecttypeid', sa.String(), nullable=True), sa.Column('ath_id', sa.Integer(), nullable=True), sa.Column('last_updated_datetime_utc', sa.DateTime(), nullable=True), sa.Column('filename', sa.String(), nullable=True), sa.Column('url', URLType(), nullable=True), sa.Column('exp_datetime_utc', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint( ['ath_id'], ['Athlete.ath_id'], ), sa.PrimaryKeyConstraint('id')) op.create_index(op.f('ix_Athlete_Fact_ath_id'), 'Athlete_Fact', ['ath_id'], unique=False) op.create_index(op.f('ix_Athlete_Fact_objecttypeid'), 'Athlete_Fact', ['objecttypeid'], unique=False) """op.drop_table('spatial_ref_sys')
class Group(Base): __tablename__ = 'group' name = Column(Unicode(128), primary_key=True) home = Column(URLType()) lead_id = Column(Integer, ForeignKey('user.id')) lead = relationship('User', foreign_keys='Group.lead_id') last_modified = Column(BigInteger, nullable=False, default=_now) def __init__(self, name=None, home=None, lead=None): super(Group, self).__init__() self.name = name self.home = home self.lead = lead def __repr__(self): return self.name def to_json(self): res = super(Group, self).to_json() if self.lead: res['lead'] = self.lead.to_json() return res
class ListingImage(db.Model): __tablename__ = "listing_image" id = db.Column(db.Integer, primary_key=True) url = db.Column(URLType(300))
from geoalchemy2 import Geometry from sqlalchemy import (MetaData, Table, Column, Integer, String, Date, DECIMAL, Float, SmallInteger, ForeignKey, UniqueConstraint) from sqlalchemy_utils import URLType metadata = MetaData() Flats = Table( 'flats', metadata, Column('id', Integer, primary_key=True), Column('url', URLType(length=400), unique=True, nullable=False), Column('avatar', URLType(length=400)), Column('published', Date, nullable=False), Column('price', DECIMAL(10, 2), nullable=False), Column('rate', DECIMAL(10, 2), nullable=False), Column('area', Float, nullable=False), Column('living_area', Float), Column('kitchen_area', Float), Column('rooms', SmallInteger, nullable=False), Column('floor', SmallInteger, nullable=False), Column('total_floor', SmallInteger, nullable=False), Column('ceiling_height', Float), Column('geolocation_id', Integer, ForeignKey('geolocations.id', ondelete='CASCADE'), nullable=False), UniqueConstraint('rooms', 'floor', 'total_floor', 'geolocation_id')) Geolocations = Table( 'geolocations', metadata, Column('id', Integer, primary_key=True), Column('point',
class Client(db.Model): """A client is the app which want to use the resource of a user. It is suggested that the client is registered by a user on your site, but it is not required. The client should contain at least these information: client_id: A random string client_secret: A random string client_type: A string represents if it is confidential redirect_uris: A list of redirect uris default_redirect_uri: One of the redirect uris default_scopes: Default scopes of the client But it could be better, if you implemented: allowed_grant_types: A list of grant types allowed_response_types: A list of response types validate_scopes: A function to validate scopes """ __tablename__ = 'oauth2CLIENT' name = db.Column( db.String(40), info=dict(label='Name', description='Name of application (displayed to users).', validators=[validators.Required()])) """Human readable name of the application.""" description = db.Column( db.Text(), default=u'', info=dict( label='Description', description='Optional. Description of the application' ' (displayed to users).', )) """Human readable description.""" website = db.Column( URLType(), info=dict( label='Website URL', description='URL of your application (displayed to users).', ), default=u'', ) user_id = db.Column(db.ForeignKey('user.id')) """Creator of the client application.""" client_id = db.Column(db.String(255), primary_key=True) """Client application ID.""" client_secret = db.Column(db.String(255), unique=True, index=True, nullable=False) """Client application secret.""" is_confidential = db.Column(db.Boolean, default=True) """Determine if client application is public or not.""" is_internal = db.Column(db.Boolean, default=False) """Determins if client application is an internal application.""" _redirect_uris = db.Column(db.Text) """A newline-separated list of redirect URIs. First is the default URI.""" _default_scopes = db.Column(db.Text) """A space-separated list of default scopes of the client. The value of the scope parameter is expressed as a list of space-delimited, case-sensitive strings. """ user = db.relationship('User') """Relationship to user.""" @property def allowed_grant_types(self): return current_app.config['OAUTH2_ALLOWED_GRANT_TYPES'] @property def allowed_response_types(self): return current_app.config['OAUTH2_ALLOWED_RESPONSE_TYPES'] # def validate_scopes(self, scopes): # return self._validate_scopes @property def client_type(self): if self.is_confidential: return 'confidential' return 'public' @property def redirect_uris(self): if self._redirect_uris: return self._redirect_uris.splitlines() return [] @redirect_uris.setter def redirect_uris(self, value): """Validate and store redirect URIs for client.""" if isinstance(value, six.text_type): value = value.split("\n") value = [v.strip() for v in value] for v in value: validate_redirect_uri(v) self._redirect_uris = "\n".join(value) or "" @property def default_redirect_uri(self): try: return self.redirect_uris[0] except IndexError: pass @property def default_scopes(self): """List of default scopes for client.""" if self._default_scopes: return self._default_scopes.split(" ") return [] @default_scopes.setter def default_scopes(self, scopes): """Set default scopes for client.""" validate_scopes(scopes) self._default_scopes = " ".join(set(scopes)) if scopes else "" def validate_scopes(self, scopes): """Validate if client is allowed to access scopes.""" try: validate_scopes(scopes) return True except ScopeDoesNotExists: return False def gen_salt(self): self.reset_client_id() self.reset_client_secret() def reset_client_id(self): self.client_id = gen_salt( current_app.config.get('OAUTH2_CLIENT_ID_SALT_LEN')) def reset_client_secret(self): self.client_secret = gen_salt( current_app.config.get('OAUTH2_CLIENT_SECRET_SALT_LEN'))
def do_upgrade(): """ Implement your upgrades here """ if not op.has_table('oauth2CLIENT'): op.create_table('oauth2CLIENT', db.Column('name', db.String(length=40), nullable=True), db.Column('description', db.Text(), nullable=True), db.Column('website', URLType(), nullable=True), db.Column('user_id', db.Integer(15, unsigned=True), nullable=True), db.Column('client_id', db.String(length=255), nullable=False), db.Column('client_secret', db.String(length=255), nullable=False), db.Column('is_confidential', db.Boolean(), nullable=True), db.Column('is_internal', db.Boolean(), nullable=True), db.Column('_redirect_uris', db.Text(), nullable=True), db.Column('_default_scopes', db.Text(), nullable=True), db.ForeignKeyConstraint( ['user_id'], ['user.id'], ), db.PrimaryKeyConstraint('client_id'), mysql_charset='utf8', mysql_engine='MyISAM') else: warnings.warn("*** Creation of table 'oauth2CLIENT' skipped!") if not op.has_table('oauth2TOKEN'): op.create_table('oauth2TOKEN', db.Column('id', db.Integer(15, unsigned=True), autoincrement=True, nullable=False), db.Column('client_id', db.String(length=40), nullable=False), db.Column('user_id', db.Integer(15, unsigned=True), nullable=True), db.Column('token_type', db.String(length=255), nullable=True), db.Column('access_token', db.String(length=255), nullable=True), db.Column('refresh_token', db.String(length=255), nullable=True), db.Column('expires', db.DateTime(), nullable=True), db.Column('_scopes', db.Text(), nullable=True), db.Column('is_personal', db.Boolean(), nullable=True), db.Column('is_internal', db.Boolean(), nullable=True), db.ForeignKeyConstraint( ['client_id'], ['oauth2CLIENT.client_id'], ), db.ForeignKeyConstraint( ['user_id'], ['user.id'], ), db.PrimaryKeyConstraint('id'), db.UniqueConstraint('access_token'), db.UniqueConstraint('refresh_token'), mysql_charset='utf8', mysql_engine='MyISAM') else: warnings.warn("*** Creation of table 'oauth2TOKEN' skipped!")
class Groups(Base): __tablename__ = 'groups' id = Column(Integer(), primary_key=True) url = Column(URLType(), unique=True) is_active = Column(Boolean(create_constraint=True))
def upgrade(): op.create_table( "event_log", sa.Column("id", sa.Integer(), nullable=False), sa.Column("ts", sa.String(), nullable=False), sa.Column("channel", sa.String(), nullable=False), sa.PrimaryKeyConstraint("id"), ) op.create_table( "json_cache", sa.Column("id", sa.Integer(), nullable=False), sa.Column("name", sa.String(), nullable=False), sa.Column("body", JSONType(), nullable=True), sa.Column("created_datetime", sa.DateTime(timezone=True), nullable=False), sa.Column("created_timezone", TimezoneType(), nullable=True), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("name"), ) op.create_table( "memo", sa.Column("id", sa.Integer(), nullable=False), sa.Column("keyword", sa.String(), nullable=False), sa.Column("text", sa.Text(), nullable=False), sa.Column("author", sa.String(), nullable=False), sa.Column("created_datetime", sa.DateTime(timezone=True), nullable=False), sa.Column("created_timezone", TimezoneType(), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "rss_feed_url", sa.Column("id", sa.Integer(), nullable=False), sa.Column("url", sa.String(), nullable=False), sa.Column("channel", sa.String(), nullable=False), sa.Column("updated_datetime", sa.DateTime(timezone=True), nullable=False), sa.Column("updated_timezone", TimezoneType(), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "saomd_notice", sa.Column("id", sa.Integer(), nullable=False), sa.Column("notice_id", sa.Integer(), nullable=False), sa.Column("server", ChoiceType(Server, impl=sa.Integer()), nullable=False), sa.Column("title", sa.String(), nullable=False), sa.Column("duration", sa.String(), nullable=True), sa.Column("short_description", sa.String(), nullable=True), sa.Column("is_deleted", sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "toranoana_author", sa.Column("id", sa.Integer(), nullable=False), sa.Column("code", sa.String(), nullable=False), sa.Column("name", sa.String(), nullable=False), sa.PrimaryKeyConstraint("id"), ) op.create_table( "toranoana_character", sa.Column("id", sa.Integer(), nullable=False), sa.Column("code", sa.String(), nullable=False), sa.Column("name", sa.String(), nullable=False), sa.Column("name_ko", sa.String(), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "toranoana_circle", sa.Column("id", sa.Integer(), nullable=False), sa.Column("code", sa.String(), nullable=False), sa.Column("name", sa.String(), nullable=False), sa.PrimaryKeyConstraint("id"), ) op.create_table( "toranoana_coupling", sa.Column("id", sa.Integer(), nullable=False), sa.Column("code", sa.String(), nullable=False), sa.Column("name", sa.String(), nullable=False), sa.Column("name_ko", sa.String(), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "toranoana_genre", sa.Column("id", sa.Integer(), nullable=False), sa.Column("code", sa.String(), nullable=False), sa.Column("name", sa.String(), nullable=False), sa.Column("name_ko", sa.String(), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "toranoana_tag", sa.Column("id", sa.Integer(), nullable=False), sa.Column("code", sa.String(), nullable=False), sa.Column("name", sa.String(), nullable=False), sa.Column("name_ko", sa.String(), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "toranoana_item", sa.Column("id", sa.Integer(), nullable=False), sa.Column("code", sa.String(), nullable=False), sa.Column("title", sa.String(), nullable=False), sa.Column("image_url", URLType(), nullable=False), sa.Column("price", sa.Integer(), nullable=False), sa.Column("stock", ChoiceType(Stock, impl=sa.Integer()), nullable=False), sa.Column("genre_id", sa.Integer(), nullable=False), sa.Column( "male_target", ChoiceType(Target, impl=sa.Integer()), nullable=False, ), sa.Column( "female_target", ChoiceType(Target, impl=sa.Integer()), nullable=False, ), sa.Column("checked_datetime", sa.DateTime(timezone=True), nullable=False), sa.Column("checked_timezone", TimezoneType(), nullable=True), sa.Column("updated_datetime", sa.DateTime(timezone=True), nullable=False), sa.Column("updated_timezone", TimezoneType(), nullable=True), sa.Column("is_deleted", sa.Boolean(), nullable=False), sa.ForeignKeyConstraint( ["genre_id"], ["toranoana_genre.id"], ), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("code"), ) op.create_table( "toranoana_watch", sa.Column("id", sa.Integer(), nullable=False), sa.Column("print_target_id", sa.String(), nullable=False), sa.Column("genre_id", sa.Integer(), nullable=True), sa.Column("male", ChoiceType(Target, impl=sa.Integer()), nullable=False), sa.Column("female", ChoiceType(Target, impl=sa.Integer()), nullable=False), sa.ForeignKeyConstraint( ["genre_id"], ["toranoana_genre.id"], ), sa.PrimaryKeyConstraint("id"), ) op.create_table( "toranoana_itemauthor", sa.Column("item_id", sa.Integer(), nullable=False), sa.Column("author_id", sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ["author_id"], ["toranoana_author.id"], ), sa.ForeignKeyConstraint( ["item_id"], ["toranoana_item.id"], ), sa.PrimaryKeyConstraint("item_id", "author_id"), ) op.create_table( "toranoana_itemcharacter", sa.Column("item_id", sa.Integer(), nullable=False), sa.Column("character_id", sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ["character_id"], ["toranoana_character.id"], ), sa.ForeignKeyConstraint( ["item_id"], ["toranoana_item.id"], ), sa.PrimaryKeyConstraint("item_id", "character_id"), ) op.create_table( "toranoana_itemcircle", sa.Column("item_id", sa.Integer(), nullable=False), sa.Column("circle_id", sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ["circle_id"], ["toranoana_circle.id"], ), sa.ForeignKeyConstraint( ["item_id"], ["toranoana_item.id"], ), sa.PrimaryKeyConstraint("item_id", "circle_id"), ) op.create_table( "toranoana_itemcoupling", sa.Column("item_id", sa.Integer(), nullable=False), sa.Column("coupling_id", sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ["coupling_id"], ["toranoana_coupling.id"], ), sa.ForeignKeyConstraint( ["item_id"], ["toranoana_item.id"], ), sa.PrimaryKeyConstraint("item_id", "coupling_id"), ) op.create_table( "toranoana_itemtag", sa.Column("item_id", sa.Integer(), nullable=False), sa.Column("tag_id", sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ["item_id"], ["toranoana_item.id"], ), sa.ForeignKeyConstraint( ["tag_id"], ["toranoana_tag.id"], ), sa.PrimaryKeyConstraint("item_id", "tag_id"), )
class User(DatabaseObject): DOMAIN_CHARS = digits + ascii_lowercase LINUX_EPOCH = datetime(1970, 1, 1, 0, 0) MIN_PASSWORD_LENGTH = 1 if options.debug else 12 OTP_LENGTH = 8 OTP_STEP = 30 OTP_ISSUER = "XSS-Hunter" FULL_NAME_LENGTH = 120 _full_name = Column(Unicode(FULL_NAME_LENGTH)) FULL_NAME_SCHEMA = { "type": "string", "minLength": 1, "maxLength": FULL_NAME_LENGTH } USERNAME_LENGTH = 80 _username = Column(Unicode(USERNAME_LENGTH), unique=True, nullable=False) USERNAME_SCHEMA = { "type": "string", "minLength": 1, "maxLength": USERNAME_LENGTH } _password = Column(String(120)) EMAIL_LENGTH = 120 _email = Column(String(EMAIL_LENGTH), unique=True, nullable=False) EMAIL_SCHEMA = { "type": "string", "format": "email", "minLength": 1, "maxLength": EMAIL_LENGTH } DOMAIN_LENGTH = 32 _domain = Column(String(DOMAIN_LENGTH), unique=True) DOMAIN_SCHEMA = { "type": "string", "maxLength": DOMAIN_LENGTH, "minLength": 1 } _pgp_key = Column(Text()) _chainload_uri = Column(URLType()) email_enabled = Column(Boolean, default=False) _locked = Column(Boolean, default=False) _last_login = Column(DateTime) _otp_enabled = Column(Boolean, default=False) _otp_secret = Column(EncryptedType(String(128), options.database_secret)) _password_reset_token_expires = Column(DateTime, default=LINUX_EPOCH) _password_reset_token = Column(String(128), nullable=False, default=lambda: urandom(32).encode('hex')) _api_key = Column(String(128), nullable=False, default=lambda: urandom(32).encode('hex')) injections = relationship("InjectionRecord", backref=backref("user", lazy="select"), cascade="all,delete,delete-orphan") permissions = relationship("Permission", backref=backref("user", lazy="select"), cascade="all,delete,delete-orphan") @classmethod def by_domain(cls, domain): return DBSession().query(cls).filter_by(_domain=domain).first() @classmethod def by_username(cls, username): username = ''.join(username[:80].split()) return DBSession().query(cls).filter_by(_username=username).first() @classmethod def by_api_key(cls, api_key): return DBSession().query(cls).filter_by( _api_key=sha512(api_key).digest()).first() @staticmethod def hash_password(password, salt=None): """ BCrypt has a max lenght of 72 chars, we first throw the plaintext thru SHA256 to support passwords greater than 72 chars. """ if salt is None: salt = bcrypt.gensalt(10) return bcrypt.hashpw(sha512(password).digest(), salt) @property def permission_names(self): """ Return a list with all permissions accounts granted to the user """ return [permission.name for permission in self.permissions] def has_permission(self, permission): """ Return True if 'permission' is in permissions_names """ return True if permission in self.permission_names else False def compare_password(self, in_password): return self.hash_password(in_password, self.password) == self.password def generate_password_reset_token(self): """ Generates a new password reset token and returns it, also save the new token as a hash in the database. """ token = urandom(32).encode('hex') self._password_reset_token = sha512(token).hexdigest() expires_at = datetime.utcnow() + timedelta(hours=1) self._password_reset_token_expires = expires_at return token def generate_api_key(self): token = urandom(32).encode('hex') self._api_key = sha512(token).hexdigest() return token def validate_password_reset_token(self, token): """ You can't do a remote timing attack since we hash the input token, well unless you can generate lots of sha512 collisions, in which case you earned it buddy. """ if datetime.utcnow() < self._password_reset_token_expires: if sha512(token).hexdigest() == self._password_reset_token: # Token can only be used once, override old value with garbage self._password_reset_token = urandom(32).encode('hex') self._password_reset_token_expires = User.LINUX_EPOCH return True return False @property def full_name(self): return self._full_name @full_name.setter def full_name(self, in_fullname): assert isinstance(in_fullname, basestring) self._full_name = in_fullname[:self.FULL_NAME_LENGTH].strip() @property def username(self): return self._username @username.setter def username(self, in_username): assert isinstance(in_username, basestring) self.username = ''.join(in_username.split())[:self.USERNAME_LENGTH] @property def password(self): return self._password @password.setter def password(self, in_password): if len(in_password) < self.MIN_PASSWORD_LENGTH: raise ValueError("Password must be %d+ chars" % (self.MIN_PASSWORD_LENGTH)) self._password = self.hash_password(in_password) @property def pgp_key(self): return self._pgp_key @pgp_key.setter def pgp_key(self, in_pgp_key): self._pgp_key = in_pgp_key @property def email(self): return self._email @email.setter def email(self, in_email): in_email = in_email.strip() @property def domain(self): return self._domain @domain.setter def domain(self, set_domain): assert isinstance(set_domain, basestring) if not 0 < len(set_domain) <= 32: raise ValueError("Invalid domain length") if any(char not in self.DOMAIN_CHARS for char in set_domain): raise ValueError("Invalid domain, domains can only contain %s" % (self.DOMAIN_CHARS)) # Check for duplicates if self.by_domain(set_domain) is not None: raise ValueError("Duplicate domain") else: self._domain = set_domain @property def last_login(self): return time.mktime(self._last_login.timetuple()) @last_login.setter def last_login(self, value): self._last_login = value @property def locked(self): return self._locked @locked.setter def locked(self, value): """ Lock account and revoke all API keys """ assert isinstance(value, bool) if value: self._locked = True self._api_key = urandom(32).encode('hex') else: self._locked = False def validate_otp(self, value): """ Validate a one-time password """ try: self._otp.verify(value.encode("ascii", "ignore"), time()) return True except InvalidToken: return False @property def otp_enabled(self): return self._otp_enabled @otp_enabled.setter def otp_enabled(self, value): """ Ensures that when 2fa is enabled/disabled we always use a fresh key """ assert isinstance(value, bool) if value: self._otp_enabled = True self._otp_secret = urandom(64).encode('hex') else: self._otp_enabled = False self._otp_secret = "" @property def _otp(self): """ Current one time password implementation, time-based "TOTP" https://cryptography.io/en/latest/hazmat/primitives/twofactor/ """ if not self._otp_enabled or len(self._otp_secret) < 1: raise ValueError("2FA/OTP is not enabled for this user") key = self._otp_secret.decode('hex') return TOTP(key, self.OTP_LENGTH, SHA512(), self.OTP_STEP, backend=default_backend()) @property def otp_provisioning_uri(self): """ Generate an enrollment URI for Authetnicator apps """ return self._otp.get_provisioning_uri(self.username, self.OTP_ISSUER) def to_dict(self): return { "id": self.id, "created": self.created, "full_name": self.full_name, "email": self.email, "username": self.username, "pgp_key": self.pgp_key, "domain": self.domain, "email_enabled": self.email_enabled } def to_admin_dict(self): data = self.to_dict() data["updated"] = self.updated data["locked"] = self.locked data["last_login"] = self.last_login return data def __str__(self): return self.username + " - ( " + self.full_name + " )"
class Article(Base): __tablename__ = "tagger_article" hn_id = Column(Integer(), primary_key=True) # 0 successfully parsed, # 1 hn id not found, # 2 no url # 3 waiting for prediction_text parsing # 4 goose failure / no text # 5 db save failure of text # 6 parsing prediction text # 10 tagged # 11 processed for tagging, no tags assigned # 12 tagging error # 13 selected for tagging state = Column(Integer(), nullable=False) parsed = Column(DateTime()) title = Column(String(2000)) article_url = Column(URLType(), nullable=True) score = Column(Integer()) number_of_comments = Column(Integer(), nullable=True) timestamp = Column(Integer()) rank = Column(Integer(), nullable=True) tagged = Column(Boolean(), default=False) imported = Column(Boolean(), default=False) submitter_id = Column(String(15), ForeignKey("tagger_user.id")) submitter = relationship("User", back_populates="articles") text = relationship("ArticleText", uselist=False, back_populates="article") tags = relationship("Tag", secondary=article_tags_table) def __unicode__(self): return self.title def site(self): if not self.article_url: return None else: netloc = urlparse(self.get_absolute_url()).netloc path = netloc.split(".") try: return path[-2] + "." + path[-1] except: return netloc def age(self): now = datetime.utcnow() then = datetime.fromtimestamp(self.timestamp) t_delta = now - then delta = t_delta.total_seconds() if delta < 3600: minute_delta = delta / 60 return "%s minutes" % format(minute_delta, ".0f") elif delta < 86400: hour_delta = delta / 3600 return "%s hours" % format(hour_delta, ".0f") else: #Note, timedelta stores seconds and days, hence the odd cases day_delta = t_delta.days + math.floor(t_delta.seconds / 43200) return "%s days" % day_delta def get_absolute_url(self): return self.article_url or "https://news.ycombinator.com/item?id=" + str(self.hn_id)
class OAuthClient(db.Model): """ A client is the app which want to use the resource of a user. It is suggested that the client is registered by a user on your site, but it is not required. The client should contain at least these information: client_id: A random string client_secret: A random string client_type: A string represents if it is confidential redirect_uris: A list of redirect uris default_redirect_uri: One of the redirect uris default_scopes: Default scopes of the client But it could be better, if you implemented: allowed_grant_types: A list of grant types allowed_response_types: A list of response types validate_scopes: A function to validate scopes """ __tablename__ = 'oauth2client' name = db.Column( db.String(40), info=dict(label='Name', description='Name of application (displayed to users).', validators=[validators.Required()])) """ Human readable name of the application. """ description = db.Column( db.Text(), default=u'', info=dict( label='Description', description='Optional. Description of the application' ' (displayed to users).', )) """ Human readable description. """ website = db.Column( URLType(), info=dict( label='Website URL', description='URL of your application (displayed to users).', ), default=u'', ) user_id = db.Column(db.ForeignKey('users.id')) """ Creator of the client application. """ client_id = db.Column(db.String(255), primary_key=True) """ Client application ID. """ client_secret = db.Column(db.String(255), unique=True, index=True, nullable=False) """ Client application secret. """ is_confidential = db.Column(db.Boolean, default=True) """ Determine if client application is public or not. """ is_internal = db.Column(db.Boolean, default=False) """ Determins if client application is an internal application. """ last_activity = db.Column(db.DateTime, nullable=True) """ Datetime that stores the last time this client was accessed. """ _redirect_uris = db.Column(db.Text) """A newline-separated list of redirect URIs. First is the default URI.""" _default_scopes = db.Column(db.Text) """A space-separated list of default scopes of the client. The value of the scope parameter is expressed as a list of space-delimited, case-sensitive strings. """ user = db.relationship('User') """ Relationship to user. """ @property def allowed_grant_types(self): return current_app.config['OAUTH2_ALLOWED_GRANT_TYPES'] @property def allowed_response_types(self): return current_app.config['OAUTH2_ALLOWED_RESPONSE_TYPES'] # def validate_scopes(self, scopes): # return self._validate_scopes @property def client_type(self): if self.is_confidential: return 'confidential' return 'public' @property def redirect_uris(self): if self._redirect_uris: return self._redirect_uris.splitlines() return [] @redirect_uris.setter def redirect_uris(self, value): """ Validate and store redirect URIs for client. """ if isinstance(value, six.text_type): value = value.split("\n") value = [v.strip() for v in value] for v in value: self.validate_redirect_uri_form(v) self._redirect_uris = "\n".join(value) or "" @staticmethod def validate_redirect_uri_form(value): """ Validate a redirect URI. A redirect URL must utilize https or redirect to localhost. :param value: Value to validate. :raises: InvalidRedirectURIError, InsecureTransportError """ sch, netloc, path, par, query, fra = urlparse(value) if not (sch and netloc): raise InvalidRedirectURIError() if sch != 'https': if ':' in netloc: netloc, port = netloc.split(':', 1) if not (netloc in ('localhost', '127.0.0.1') and sch == 'http'): raise InsecureTransportError() return True @property def default_redirect_uri(self): try: return self.redirect_uris[0] except IndexError: pass @property def default_scopes(self): """ List of default scopes for client. """ if self._default_scopes: return self._default_scopes.split(" ") return [] def validate_scopes(self, scopes): """ Validate if client is allowed to access scopes. """ from .registry import scopes as scopes_registry for s in set(scopes): if s not in scopes_registry: return False return True def gen_salt(self): self.reset_client_id() self.reset_client_secret() def reset_client_id(self): self.client_id = gen_salt( current_app.config.get('OAUTH2_CLIENT_ID_SALT_LEN')) def reset_client_secret(self): self.client_secret = gen_salt( current_app.config.get('OAUTH2_CLIENT_SECRET_SALT_LEN'))
class Project(Base): __tablename__ = 'project' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(Unicode(128), nullable=False) bz_product = Column(Unicode(128)) bz_component = Column(Unicode(128)) description = Column(UnicodeText) long_description = Column(UnicodeText) irc = Column(Unicode(128)) public = Column(Boolean, default=True) active = Column(Boolean, default=True) # all project links homepage = Column(URLType()) repositories = relationship('Link', secondary=project_repos) tags = relationship('Tag', secondary=project_tags) languages = relationship('Language', secondary=project_langs) testrail = relationship('TestRail', back_populates="project") # all tests tests = relationship('ProjectTest', back_populates="project") jenkins_jobs = relationship('JenkinsJob', back_populates="project") # dev folks dev_primary_id = Column(Integer, ForeignKey('user.id')) dev_primary = relationship('User', foreign_keys='Project.dev_primary_id') dev_secondary_id = Column(Integer, ForeignKey('user.id')) dev_secondary = relationship('User', foreign_keys='Project.dev_secondary_id') # ops folks op_primary_id = Column(Integer, ForeignKey('user.id')) op_primary = relationship('User', foreign_keys='Project.op_primary_id') op_secondary_id = Column(Integer, ForeignKey('user.id')) op_secondary = relationship('User', foreign_keys='Project.op_secondary_id') # qa folks qa_primary_id = Column(Integer, ForeignKey('user.id')) qa_primary = relationship('User', foreign_keys='Project.qa_primary_id') qa_secondary_id = Column(Integer, ForeignKey('user.id')) qa_secondary = relationship('User', foreign_keys='Project.qa_secondary_id') qa_group_name = Column(Unicode(128), ForeignKey('group.name')) qa_group = relationship('Group', foreign_keys='Project.qa_group_name') deployments = relationship('Deployment', back_populates="project") last_modified = Column(BigInteger, nullable=False, default=_now) def __repr__(self): return '%s' % self.name def to_json(self): res = super(Project, self).to_json() res['deployments'] = [depl.to_json() for depl in self.deployments] res['tests'] = [test.to_json() for test in self.tests] res['jenkins_jobs'] = [job.to_json() for job in self.jenkins_jobs] res['testrail'] = [tr.to_json() for tr in self.testrail] for field in ('qa_primary', 'qa_secondary', 'dev_primary', 'dev_secondary', 'op_primary', 'op_secondary'): user = getattr(self, field, None) if user is not None: res[field] = user.to_json() if self.qa_group is not None: res['qa_group'] = self.qa_group.to_json() for rel in ('tags', 'languages', 'repositories'): res[rel] = [ item.to_json() for item in getattr(self, rel) if item is not None ] return res def index(self): res = self.name res += ' ' + ' '.join([tag.name for tag in self.tags]) res += ' ' + ' '.join([str(lang) for lang in self.languages]) if self.long_description: res += ' ' + self.long_description if self.description: res += ' ' + self.description if self.irc: res += ' ' + self.irc for user in (self.dev_primary, self.dev_secondary, self.op_primary, self.op_secondary, self.qa_primary, self.qa_secondary): if user is not None: res += ' ' + user.fullname() if self.qa_group_name: res += ' ' + self.qa_group_name return res
def upgrade(): op.create_table( 'event_log', sa.Column('id', sa.Integer(), nullable=False), sa.Column('ts', sa.String(), nullable=False), sa.Column('channel', sa.String(), nullable=False), sa.PrimaryKeyConstraint('id'), ) op.create_table( 'json_cache', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('body', JSONType(), nullable=True), sa.Column('created_datetime', sa.DateTime(timezone=True), nullable=False), sa.Column('created_timezone', TimezoneType(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name'), ) op.create_table( 'memo', sa.Column('id', sa.Integer(), nullable=False), sa.Column('keyword', sa.String(), nullable=False), sa.Column('text', sa.Text(), nullable=False), sa.Column('author', sa.String(), nullable=False), sa.Column('created_datetime', sa.DateTime(timezone=True), nullable=False), sa.Column('created_timezone', TimezoneType(), nullable=True), sa.PrimaryKeyConstraint('id'), ) op.create_table( 'rss_feed_url', sa.Column('id', sa.Integer(), nullable=False), sa.Column('url', sa.String(), nullable=False), sa.Column('channel', sa.String(), nullable=False), sa.Column('updated_datetime', sa.DateTime(timezone=True), nullable=False), sa.Column('updated_timezone', TimezoneType(), nullable=True), sa.PrimaryKeyConstraint('id'), ) op.create_table( 'saomd_notice', sa.Column('id', sa.Integer(), nullable=False), sa.Column('notice_id', sa.Integer(), nullable=False), sa.Column('server', ChoiceType(Server, impl=sa.Integer()), nullable=False), sa.Column('title', sa.String(), nullable=False), sa.Column('duration', sa.String(), nullable=True), sa.Column('short_description', sa.String(), nullable=True), sa.Column('is_deleted', sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint('id'), ) op.create_table( 'toranoana_author', sa.Column('id', sa.Integer(), nullable=False), sa.Column('code', sa.String(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.PrimaryKeyConstraint('id'), ) op.create_table( 'toranoana_character', sa.Column('id', sa.Integer(), nullable=False), sa.Column('code', sa.String(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('name_ko', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id'), ) op.create_table( 'toranoana_circle', sa.Column('id', sa.Integer(), nullable=False), sa.Column('code', sa.String(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.PrimaryKeyConstraint('id'), ) op.create_table( 'toranoana_coupling', sa.Column('id', sa.Integer(), nullable=False), sa.Column('code', sa.String(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('name_ko', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id'), ) op.create_table( 'toranoana_genre', sa.Column('id', sa.Integer(), nullable=False), sa.Column('code', sa.String(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('name_ko', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id'), ) op.create_table( 'toranoana_tag', sa.Column('id', sa.Integer(), nullable=False), sa.Column('code', sa.String(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('name_ko', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id'), ) op.create_table( 'toranoana_item', sa.Column('id', sa.Integer(), nullable=False), sa.Column('code', sa.String(), nullable=False), sa.Column('title', sa.String(), nullable=False), sa.Column('image_url', URLType(), nullable=False), sa.Column('price', sa.Integer(), nullable=False), sa.Column('stock', ChoiceType(Stock, impl=sa.Integer()), nullable=False), sa.Column('genre_id', sa.Integer(), nullable=False), sa.Column( 'male_target', ChoiceType(Target, impl=sa.Integer()), nullable=False, ), sa.Column( 'female_target', ChoiceType(Target, impl=sa.Integer()), nullable=False, ), sa.Column('checked_datetime', sa.DateTime(timezone=True), nullable=False), sa.Column('checked_timezone', TimezoneType(), nullable=True), sa.Column('updated_datetime', sa.DateTime(timezone=True), nullable=False), sa.Column('updated_timezone', TimezoneType(), nullable=True), sa.Column('is_deleted', sa.Boolean(), nullable=False), sa.ForeignKeyConstraint( ['genre_id'], ['toranoana_genre.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('code'), ) op.create_table( 'toranoana_watch', sa.Column('id', sa.Integer(), nullable=False), sa.Column('print_target_id', sa.String(), nullable=False), sa.Column('genre_id', sa.Integer(), nullable=True), sa.Column('male', ChoiceType(Target, impl=sa.Integer()), nullable=False), sa.Column('female', ChoiceType(Target, impl=sa.Integer()), nullable=False), sa.ForeignKeyConstraint( ['genre_id'], ['toranoana_genre.id'], ), sa.PrimaryKeyConstraint('id'), ) op.create_table( 'toranoana_itemauthor', sa.Column('item_id', sa.Integer(), nullable=False), sa.Column('author_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ['author_id'], ['toranoana_author.id'], ), sa.ForeignKeyConstraint( ['item_id'], ['toranoana_item.id'], ), sa.PrimaryKeyConstraint('item_id', 'author_id'), ) op.create_table( 'toranoana_itemcharacter', sa.Column('item_id', sa.Integer(), nullable=False), sa.Column('character_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ['character_id'], ['toranoana_character.id'], ), sa.ForeignKeyConstraint( ['item_id'], ['toranoana_item.id'], ), sa.PrimaryKeyConstraint('item_id', 'character_id'), ) op.create_table( 'toranoana_itemcircle', sa.Column('item_id', sa.Integer(), nullable=False), sa.Column('circle_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ['circle_id'], ['toranoana_circle.id'], ), sa.ForeignKeyConstraint( ['item_id'], ['toranoana_item.id'], ), sa.PrimaryKeyConstraint('item_id', 'circle_id'), ) op.create_table( 'toranoana_itemcoupling', sa.Column('item_id', sa.Integer(), nullable=False), sa.Column('coupling_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ['coupling_id'], ['toranoana_coupling.id'], ), sa.ForeignKeyConstraint( ['item_id'], ['toranoana_item.id'], ), sa.PrimaryKeyConstraint('item_id', 'coupling_id'), ) op.create_table( 'toranoana_itemtag', sa.Column('item_id', sa.Integer(), nullable=False), sa.Column('tag_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ['item_id'], ['toranoana_item.id'], ), sa.ForeignKeyConstraint( ['tag_id'], ['toranoana_tag.id'], ), sa.PrimaryKeyConstraint('item_id', 'tag_id'), )
def upgrade(): op.create_table( 'users', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('email', sa.String(length=255), nullable=True), sa.Column('password', sa.String(length=255), nullable=True), sa.Column('name', sa.String(length=255), nullable=True), sa.Column('active', sa.Boolean(), nullable=True), sa.Column('confirmed_at', sa.DateTime(), nullable=True), sa.Column('last_login_at', sa.DateTime(), nullable=True), sa.Column('login_count', sa.Integer(), nullable=True), sa.Column('registered_at', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email')) op.create_table( 'roles', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=80), nullable=True), sa.Column('description', sa.String(length=255), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name')) op.create_table('roles_users', sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('role_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint( ['role_id'], ['roles.id'], ), sa.ForeignKeyConstraint( ['user_id'], ['users.id'], ), sa.PrimaryKeyConstraint()) op.create_table( 'oauth2client', sa.Column('name', sa.String(length=40), nullable=True), sa.Column('description', sa.Text(), nullable=True), sa.Column('website', URLType(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('client_id', sa.String(length=255), nullable=False), sa.Column('client_secret', sa.String(length=255), nullable=False), sa.Column('is_confidential', sa.Boolean(), nullable=True), sa.Column('is_internal', sa.Boolean(), nullable=True), sa.Column('last_activity', sa.DateTime, nullable=True), sa.Column('_redirect_uris', sa.Text(), nullable=True), sa.Column('_default_scopes', sa.Text(), nullable=True), sa.ForeignKeyConstraint(['user_id'], ['users.id'], onupdate="CASCADE", ondelete="CASCADE"), sa.PrimaryKeyConstraint('client_id')) op.create_table( 'oauth2token', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('client_id', sa.String(length=40), nullable=False), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('token_type', sa.String(length=255), nullable=True), sa.Column('access_token', sa.String(length=255), nullable=True), sa.Column('refresh_token', sa.String(length=255), nullable=True), sa.Column('expires', sa.DateTime(), nullable=True), sa.Column('_scopes', sa.Text(), nullable=True), sa.Column('is_personal', sa.Boolean(), nullable=True), sa.Column('is_internal', sa.Boolean(), nullable=True), sa.ForeignKeyConstraint(['client_id'], ['oauth2client.client_id'], onupdate="CASCADE", ondelete="CASCADE"), sa.ForeignKeyConstraint(['user_id'], ['users.id'], onupdate="CASCADE", ondelete="CASCADE"), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('access_token'), sa.UniqueConstraint('refresh_token'))