Ejemplo n.º 1
0
class User(Base):
    """
    Class for generating valid user and ensuring types are correct
  
    Parameters: 
    id (integer): The id of the user
    name (string): The name of the user
    age (integer): Current age
    number(string): String representation of a US phone number
    photo(string): The URL location of the photo
    bio(string): Text describing the user
    Returns:
    User object
    """

    __tablename__ = "user"
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String)
    age = sa.Column(sa.Integer)
    number = sa.Column(PhoneNumberType())
    photo = sa.Column(sa.String)
    bio = sa.Column(sa.String)

    @validates("number")
    def validate_phone(self, key, number):
        if not number:
            raise NonUSPhoneNumberException("Missing Phone Number")
        number = "".join(c for c in number if c.isdigit())
        if len(number) != 10:
            raise NonUSPhoneNumberException(f"Invalid phone length {number}")
        return number

    def __repr__(self):
        return f"<User(name={self.name!r} age={self.age})>"
Ejemplo n.º 2
0
class SignUpRecord(db.Model):
    __tablename__ = 'sign_up'
    id = db.Column(db.Integer, primary_key=True)
    event = db.Column(db.Text)
    first_name = db.Column(db.Text)
    last_name = db.Column(db.Text)
    phone_number = db.Column(PhoneNumberType())
    email = db.Column(db.String(100))
    address = db.Column(db.Text)
    city = db.Column(db.Text)
    zip_code = db.Column(db.Text)
    receive_emails = db.Column(db.Boolean)
    receive_texts = db.Column(db.Boolean)
    already_signed_up = db.Column(db.Boolean)
    sign_up_time = db.Column(db.DateTime)

    def __init__(self, event, first_name, last_name, phone_number, email, address, city, zip_code, receive_emails, receive_texts, already_signed_up, sign_up_time):
        self.event = event
        self.first_name = first_name
        self.last_name = last_name
        self.phone_number = phone_number
        self.email = email
        self.address = address
        self.city = city
        self.zip_code = zip_code
        self.receive_emails = receive_emails
        self.receive_texts = receive_texts
        self.already_signed_up = already_signed_up
        self.sign_up_time = sign_up_time

    def __repr__(self):
        return "{'first_name': '%s', 'last_name': '%s', 'email': '%s'}" %(self.first_name, self.last_name, self.email)
class User(base):
    __tablename__ = 'user'
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.Unicode(255), unique=True)
    email = sa.Column(sa.Unicode(255))
    phone = sa.Column(PhoneNumberType(region='ES', max_length=25), unique=True)
    favorite_color_id = sa.Column(sa.Integer, sa.ForeignKey(Color.id))
    favorite_color = relationship(Color)
Ejemplo n.º 4
0
        class User(self.Base):
            __tablename__ = 'user'
            id = sa.Column(sa.Integer, primary_key=True)
            fav_color = sa.Column(ColorType)
            phone_number = sa.Column(PhoneNumberType(country_code='FI'))
            number_of_friends = sa.Column(NumberRangeType)

            def __repr__(self):
                return 'User(%r)' % self.id
Ejemplo n.º 5
0
class Agent(Thing):
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
    type = Column(Unicode, nullable=False)
    name = Column(CIText())
    name.comment = """
        The name of the organization or person.
    """
    tax_id = Column(Unicode(length=STR_SM_SIZE), check_lower('tax_id'))
    tax_id.comment = """
        The Tax / Fiscal ID of the organization, 
        e.g. the TIN in the US or the CIF/NIF in Spain.
    """
    country = Column(DBEnum(enums.Country))
    country.comment = """
        Country issuing the tax_id number.
    """
    telephone = Column(PhoneNumberType())
    email = Column(EmailType, unique=True)

    __table_args__ = (UniqueConstraint(
        tax_id, country, name='Registration Number per country.'),
                      UniqueConstraint(tax_id,
                                       name,
                                       name='One tax ID with one name.'),
                      db.Index('agent_type', type, postgresql_using='hash'))

    @declared_attr
    def __mapper_args__(cls):
        """
        Defines inheritance.

        From `the guide <http://docs.sqlalchemy.org/en/latest/orm/
        extensions/declarative/api.html
        #sqlalchemy.ext.declarative.declared_attr>`_
        """
        args = {POLYMORPHIC_ID: cls.t}
        if cls.t == 'Agent':
            args[POLYMORPHIC_ON] = cls.type
        if JoinedTableMixin in cls.mro():
            args[INHERIT_COND] = cls.id == Agent.id
        return args

    @property
    def events(self) -> list:
        # todo test
        return sorted(chain(self.events_agent, self.events_to),
                      key=attrgetter('created'))

    @validates('name')
    def does_not_contain_slash(self, _, value: str):
        if '/' in value:
            raise ValidationError('Name cannot contain slash \'')
        return value

    def __repr__(self) -> str:
        return '<{0.t} {0.name}>'.format(self)
Ejemplo n.º 6
0
class Service(db.Model, ActiveRecord):
    __searchable__ = ['title', 'location']
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False, unique=True)
    title = db.Column(db.String(255), nullable=False, unique=True)
    description = db.Column(db.Text(255), nullable=False)
    location = db.Column(db.String(255), nullable=False)
    contact = db.Column(PhoneNumberType(region='GH'))
    charge = db.Column(db.Numeric(10, 2), nullable=False)
    img = db.Column(db.String(255), nullable=False)
    cat_id = db.Column(db.Integer, db.ForeignKey('category.id', ondelete='CASCADE'))
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
Ejemplo n.º 7
0
class Kyc(db.Model, ActiveRecord, Timestamp):
    id = db.Column(db.Integer, primary_key=True, nullable=False, unique=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='cascade'), nullable=False)
    business_name = db.Column(db.String(100), nullable=False, unique=True)
    ident = db.Column(db.String(100), nullable=False, unique=True)
    ident_name = db.Column(db.String(100), nullable=False, )
    about_business = db.Column(db.Text, nullable=False, unique=True)
    phone_number = db.Column(PhoneNumberType(region='GH'), nullable=False, unique=True)
    country = db.Column(db.String(100), nullable=False)
    file = db.Column(db.String(100), nullable=True)
    status = db.Column(db.Enum('Approved', 'Pending', 'Disapproved', 'Suspended', 'Processing'), nullable=False,
                       default='Pending')
Ejemplo n.º 8
0
class User(db.Model, login.UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), info={'label': 'Name'})
    email = db.Column(EmailType, unique=True, nullable=False, info={'label': 'Email'})
    phone_number = db.Column(PhoneNumberType(), info={'label': 'Phone Number'})
    password = db.Column(PasswordType(schemes=[
            'pbkdf2_sha512',
            'md5_crypt'
        ]), nullable=False, info={'label': 'Password'})

    def __repr__(self):
        return self.email
Ejemplo n.º 9
0
class Venue(db.Model):
    __tablename__ = 'venue'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    city = db.Column(db.String(120), nullable=False)
    state = db.Column(db.String(120))
    address = db.Column(db.String(120))
    phone = db.Column(PhoneNumberType(), nullable=False)
    image_link = db.Column(URLType)
    facebook_link = db.Column(URLType, nullable=False, unique=True)
    website = db.Column(URLType)
    genres = db.Column(db.ARRAY(db.String))
    seeking_talent = db.Column(db.Boolean, default=False)
    seeking_description = db.Column(db.String)
    shows = db.relationship('Show', backref='location', lazy=True)
Ejemplo n.º 10
0
class User(Base):
    __tablename__ = "users"

    user_id = Column(Integer, primary_key=True)
    phone_number = Column(PhoneNumberType(region="UA"))
    first_name = Column(String(255))
    last_name = Column(String(255))
    roles = relationship(
        "Role",
        secondary=association_table,
        back_populates="users",
    )

    full_name = Contact.full_name

    def __str__(self):
        return (f"{self.user_id}: {self.phone_number.e164} "
                f"({self.full_name}) {self.roles}")
Ejemplo n.º 11
0
class Users(Base):
    __tablename__ = 'users'
    __table_args__ = {'extend_existing': True}

    TYPE_GENDER = (
        ('m', u'Мужской'),
        ('f', u'Женский'),
        ('n', u'Не установлен'),
    )

    TYPE_STATUS = ()

    TYPE_TYPE = ()

    id           = Column(Integer, primary_key=True)
    firstname    = Column(String(128), nullable=False)
    lastname     = Column(String(128), nullable=False)
    gender       = Column(ChoiceType(TYPE_GENDER))
    phone        = Column(PhoneNumberType())
    city_id      = Column(Integer, ForeignKey('cities.id'), nullable=False)
    address      = Column(Text)
    time_zone    = Column(TimezoneType(backend='pytz'))
    bio          = Column(Text)
    created      = Column(DateTime, nullable=False)
    last_visit   = Column(DateTime)
    email        = Column(String(256))
    password     = Column(PasswordType(schemes=['md5_crypt']))
    # uStatus      = Column(ChoiceType(TYPE_STATUS))
    birthdate    = Column(Date)
    # uType        = Column(ChoiceType(TYPE_TYPE))
    userpic_type = Column(String(1))
    userpic_id   = Column(Integer)

    rels         = relationship('UsersRels', backref='users')
    chats        = relationship('UsersChat', backref='users')
    values       = relationship('UsersValues', backref='users')
    msgr_log     = relationship('MsgrLog', backref='users')
    msgr_threads = relationship('UsersMsgrThreads', backref='users')

    def __init__(self):
        pass

    def __repr__(self):
        return '<User([{}] {} {})>'.format(self.id, self.firstname, self.lastname)
Ejemplo n.º 12
0
    class User(db.Model):
        uuid = db.Column(UUIDType(), primary_key=True)
        username = db.Column(db.String(20), unique=True)
        passwd = db.Column(PasswordType(schemes=('pbkdf2_sha512', )),
                           nullable=False)  #automatically applies SHA512

        name = db.Column(db.String(150), nullable=True)
        phone = db.Column(PhoneNumberType(region='SG'), nullable=True)
        pdpa = db.Column(db.String(20), nullable=True)
        picture = db.Column(db.LargeBinary, nullable=True)

        last_activity_time = db.Column(db.DateTime, nullable=True)
        created_time = db.Column(db.DateTime, nullable=False)
        mc_expiry_time = db.Column(db.DateTime, nullable=True)

        __tablename__ = 'Users'

        def __repr__(self):
            return f'<User: {self.uuid}>'
Ejemplo n.º 13
0
class User(UserMixin, db.Model):
    """User account model."""

    __tablename__ = 'Users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, unique=False)
    email = db.Column(EmailType)
    password = db.Column(db.String(200),
                         primary_key=False,
                         unique=False,
                         nullable=False)

    phone_number = db.Column(PhoneNumberType())

    created_on = db.Column(db.DateTime,
                           index=False,
                           unique=False,
                           nullable=True)

    last_login = db.Column(db.DateTime,
                           index=False,
                           unique=False,
                           nullable=True)

    def set_number(self, phone_number):
        """return user number"""
        self.phone_number = phone_number

    def get_number(self):
        """return user number"""
        return self.phone_number

    def set_password(self, password):
        """Create hashed password."""
        self.password = generate_password_hash(password, method='sha256')

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

    def __repr__(self):
        return '<User {}>'.format(self.name)
Ejemplo n.º 14
0
class SignInRecord(db.Model):
    __tablename__ = 'sign_in'
    id = db.Column(db.Integer, primary_key=True)
    event = db.Column(db.Text)
    first_name = db.Column(db.Text)
    last_name = db.Column(db.Text)
    phone_number = db.Column(PhoneNumberType())
    email = db.Column(db.String(100))
    sign_in_time = db.Column(db.DateTime)

    def __init__(self, event, first_name, last_name, phone_number, email, sign_in_time):
        self.event = event
        self.first_name = first_name
        self.last_name = last_name
        self.phone_number = phone_number
        self.email = email
        self.sign_in_time = sign_in_time

    def __repr__(self):
        return "{'first_name': '%s', 'last_name': '%s', 'email': '%s'}" %(self.first_name, self.last_name, self.email)
Ejemplo n.º 15
0
class User(Base, BaseModel):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True, autoincrement=True)
    first_name = Column(String(100), nullable=False)
    last_name = Column(String(100), nullable=False)
    email = Column(EmailType)
    phone = Column(PhoneNumberType())
    role = Column(ChoiceType(Role, impl=Integer()), nullable=False)
    is_enabled = Column(Boolean, nullable=False, default=True)

    last_signed_in_at = Column(DateTime)

    @hybrid_property
    def is_admin(self):
        role = self.role
        return role and role >= Role.ADMIN

    @hybrid_property
    def name(self):
        return f'{self.first_name} {self.last_name}'
Ejemplo n.º 16
0
class SignUpRecord(db.Model):
    __tablename__ = 'email_reminders'
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.Text)
    last_name = db.Column(db.Text)
    phone_number = db.Column(PhoneNumberType())
    email = db.Column(db.String(100))
    membership_level = db.Column(db.Text)
    sign_up_time = db.Column(db.DateTime)

    def __init__(self, first_name, last_name, phone_number, email,
                 membership_level, sign_up_time):
        self.first_name = first_name
        self.last_name = last_name
        self.phone_number = phone_number
        self.email = email
        self.membership_level = membership_level
        self.sign_up_time = sign_up_time

    def __repr__(self):
        return "{'first_name': '%s', 'last_name': '%s', 'email': '%s', 'membership_level': '%s', 'sign_up_time':'%s'}" % (
            self.first_name, self.last_name, self.email, self.membership_level,
            self.sign_up_time)
Ejemplo n.º 17
0
class UserVersion(CustomDeclarativeBase):
    __tablename__ = "user_version"

    # primary key column
    user_version_id = Column(Integer, nullable=False)

    user_id = Column(Integer,
                     ForeignKey("user.user_id",
                                name="FK-user_version-user_id-user-user_id"),
                     nullable=False)

    as_of = Column(ArrowType, nullable=False)

    first_name = Column(Unicode(length=100), nullable=True)
    last_name = Column(Unicode(length=100), nullable=True)
    user_name = Column(Unicode(length=100), nullable=False)

    # from https://sqlalchemy-utils.readthedocs.io/en/latest/data_types.html#sqlalchemy_utils.types.phone_number.PhoneNumberType:
    #
    # Changes PhoneNumber objects to a string representation on the way in and changes them back to PhoneNumber
    # objects on the way out. If E164 is used as storing format, no country code is needed for parsing the database
    # value to PhoneNumber object.
    phone_number = Column(PhoneNumberType(
        region=constants.PHONE_NUMBER_DEFAULT_REGION,
        max_length=constants.PHONE_NUMBER_MAX_LENGTH),
                          nullable=True)

    profile_photo_set_id = Column(
        Integer,
        ForeignKey(
            "photo_set.photo_set_id",
            name="FK-user_version-profile_photo_set_id-photo_set-photo_set_id"
        ),
        nullable=True)

    profile_photo_set = relationship("ProfilePhotoSet",
                                     back_populates="user_version")

    is_contact = Column(Boolean, nullable=False)
    is_mutual_contact = Column(Boolean, nullable=False)
    is_verified = Column(Boolean, nullable=False)
    is_support = Column(Boolean, nullable=False)
    restriction_reason = Column(Unicode(length=255))
    is_scam = Column(Boolean, nullable=False)
    have_access = Column(Boolean, nullable=False)

    user_type = Column(ChoiceType(dbme.UserTypeEnum, impl=Unicode(length=50)),
                       nullable=False)

    language_code = Column(Unicode(length=20), nullable=True)

    user = relationship("User", back_populates="versions")

    __table_args__ = (
        PrimaryKeyConstraint("user_version_id",
                             name="PK-user_version-user_version_id"),
        Index("IXUQ-user_version-user_id-as_of",
              "user_id",
              "as_of",
              unique=True),
        Index("IX-user_version-phone_number", "phone_number"),
        Index("IX-user_version-user_type", "user_type"),
    )
Ejemplo n.º 18
0
 def test_phone_number_type_has_no_length_validation(self):
     self.init(type_=PhoneNumberType(country_code='FI'))
     field = self._get_field('test_column')
     for validator in field.validators:
         assert validator.__class__ != Length
Ejemplo n.º 19
0
 def test_phone_number_country_code_passed_to_field(self):
     self.init(type_=PhoneNumberType(region='SE'))
     form = self.form_class()
     assert form.test_column.region == 'SE'
Ejemplo n.º 20
0
 class User(Base):
     __tablename__ = 'user'
     id = sa.Column(sa.Integer, autoincrement=True, primary_key=True)
     name = sa.Column(sa.Unicode(255))
     phone_number = sa.Column(PhoneNumberType())
Ejemplo n.º 21
0
 def test_uses_phonenumber_class_as_python_type(self):
     assert PhoneNumberType().python_type is PhoneNumber
Ejemplo n.º 22
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)