Exemplo n.º 1
0
class PackageSwitch(BaseModel):
    __tablename__ = 'package_switch'
    TYPE = {1: 'switch pay per port', 2: 'switch pay per minute'}
    SUB_TYPE = {1: 'hosted_switch', 2: 'on_premise', 3: 'one_time'}
    package_switch_uuid = Column \
        (String(36), primary_key=True, default=generate_uuid_str(),
         server_default=func.uuid_generate_v4())

    package_name = Column(String(64), unique=True)

    type = Column(ChoiceType(TYPE), default=1)
    sub_type = Column(ChoiceType(SUB_TYPE), nullable=True)
    #switch_uuid = Column(String(128),index=True)
    #Column(ForeignKey('switch.switch_uuid', ondelete='CASCADE'), index=True)
    switch_port = Column(Integer())
    minute_count = Column(Integer())
    amount = Column(Integer())
    enabled = Column(Boolean, default=True)
    start_date = Column(DateTime(True),
                        nullable=False,
                        server_default=func.now())
    expire_date = Column(DateTime(True), nullable=True)
    create_on = Column(DateTime(True),
                       nullable=True,
                       server_default=func.now())

    licenses = relationship('LicenseSwitch',
                            uselist=True,
                            back_populates='package')
    #switch = relationship('Switch', uselist=False, back_populates='packages')
    rate_per_port = column_property(
        case([(switch_port > 0, cast(amount, Float).op('/')(switch_port))],
             else_=None))
Exemplo n.º 2
0
class TransactionLog(BaseModel):
    __tablename__ = 'transaction_log'
    TYPE = {1: 'paypal', 2: 'stripe'}
    STATUS = {1: 'success', -1: 'fail'}
    transaction_log_uuid = Column(String(36),
                                  primary_key=True,
                                  default=generate_uuid_str(),
                                  server_default=func.uuid_generate_v4())
    transaction_time = Column(DateTime(True),
                              nullable=False,
                              server_default=func.now())
    license_lrn_uuid = Column(String(36))
    license_switch_uuid = Column(String(36))
    user_uuid = Column(ForeignKey('user.user_uuid', ondelete='CASCADE'),
                       nullable=True,
                       index=True)
    type = Column(ChoiceType(TYPE), default=1)
    amount_total = Column(Numeric, nullable=False, server_default='0')
    amount_lrn = Column(Numeric, nullable=False, server_default='0')
    amount_switch = Column(Numeric, nullable=False, server_default='0')
    transaction_fee = Column(Numeric, nullable=False, server_default='0')
    transaction_id = Column(String(255))
    transaction_type = Column(String(255))
    from_ip = Column(String(36))
    transaction_src = Column(JSON())
    status = Column(ChoiceType(STATUS), default=-1)
    result = Column(Text())
    payment_uuid = Column(ForeignKey('payment.payment_uuid',
                                     ondelete='CASCADE'),
                          index=True)

    user_name = column_property(
        select([User.name
                ]).where(user_uuid == User.user_uuid).correlate_except(User))
Exemplo n.º 3
0
    def new_sms_handler(pdu, client, **kwargs):
        global kannel
        dump_pdu(pdu)
        if client == kannel:
            #here is inbound route
            answer_pdu=smpp.make_pdu('data_sm',
                                client=kannel,
                                message_payload=pdu.short_message.encode(),
                                source_addr=pdu.source_addr,
                                destination_addr=pdu.destination_addr,
                                esm_class=consts.SMPP_MSGMODE_FORWARD,
                                data_coding=consts.SMPP_ENCODING_DEFAULT,
                                dest_addr_ton=consts.SMPP_TON_INTL,
                                dest_addr_npi=consts.SMPP_NPI_ISDN,
                                source_addr_ton=consts.SMPP_TON_INTL,
                                source_addr_npi=consts.SMPP_NPI_ISDN,
                                service_type='VMA',
                                registered_delivery=0,
                                alert_on_message_delivery=None
                                )

            kannel.send_pdu(answer_pdu)

        else:
            #here is outbound route
            kannel.send_pdu(pdu)
        return generate_uuid_str()()
Exemplo n.º 4
0
class Switch(BaseModel):
    __tablename__ = 'switch'
    switch_uuid = Column \
        (String(36), primary_key=True, default=generate_uuid_str(),
         server_default=func.uuid_generate_v4())
    switch_ip = Column(String(16))
    enabled = Column(Boolean, default=True)
    current_port_count = Column(Integer())
    minute_remaining = Column(Integer())
    expired_on = Column(DateTime(True), nullable=True)
    email = Column(String(256))
Exemplo n.º 5
0
class Payment(BaseModel):
    __tablename__ = 'payment'
    TYPE = {1: 'paypal', 2: 'stripe'}
    payment_uuid = Column(String(36),
                          primary_key=True,
                          default=generate_uuid_str(),
                          server_default=func.uuid_generate_v4())
    user_uuid = Column(ForeignKey('user.user_uuid', ondelete='CASCADE'),
                       index=True)
    license_lrn_uuid = Column(ForeignKey('license_lrn.license_lrn_uuid',
                                         ondelete='CASCADE'),
                              nullable=True,
                              index=True)
    license_switch_uuid = Column(ForeignKey(
        'license_switch.license_switch_uuid', ondelete='CASCADE'),
                                 nullable=True,
                                 index=True)
    switch_uuid = Column(String(64), index=True)
    amount_lrn = Column(Numeric, nullable=False, server_default='0')
    amount_switch = Column(Numeric, nullable=False, server_default='0')
    #amount_total = Column(Numeric, nullable=False, server_default='0')
    paid_time = Column(DateTime(True),
                       nullable=False,
                       server_default=func.now())
    type = Column(ChoiceType(TYPE), default=1)
    description = Column(Text)

    user = relationship('User')

    amount_total = column_property(amount_lrn.op('+')(amount_switch))
    user_email = column_property(
        select([User.email
                ]).where(User.user_uuid == user_uuid).correlate_except(User))

    @property
    def license_uuid(self):
        if self.license_lrn_uuid:
            return self.license_lrn_uuid
        if self.license_switch_uuid:
            return self.license_switch_uuid
        return None

    @property
    def license(self):
        if self.license_lrn_uuid:
            return LicenseLrn.get(self.license_lrn_uuid)
        if self.license_switch_uuid:
            return LicenseSwitch.get(self.license_switch_uuid)
        return None

    def apply_mail(self, template_name):
        return _apply_mail(self, template_name, 'payment')
Exemplo n.º 6
0
class Plan(BaseModel):
    __tablename__ = 'plan'
    TYPE = {
        1: 'switch pay per port',
        2: 'switch pay per minute',
        3: 'LRN pay per CPS',
        4: 'LRN pay per DIP'
    }
    plan_uuid = Column(String(36),
                       primary_key=True,
                       default=generate_uuid_str(),
                       server_default=func.uuid_generate_v4())

    type = Column(ChoiceType(TYPE), default=1)
    amount = Column(Numeric, nullable=False, server_default='0')
Exemplo n.º 7
0
class Notification(BaseModel, ModelUsingFiles):
    __tablename__ = 'notification'

    notification_uuid = Column(String(36),
                               primary_key=True,
                               default=generate_uuid_str(),
                               server_default=func.uuid_generate_v4())
    user_uuid = Column(ForeignKey('user.user_uuid', ondelete='CASCADE'),
                       nullable=True,
                       index=True)

    subject = Column(String(64), nullable=False)
    content = Column(Text, nullable=False)
    created_on = Column(DateTime(True),
                        nullable=False,
                        server_default=func.now())
    user = relationship('User')
Exemplo n.º 8
0
class PackageLrn(BaseModel):
    __tablename__ = 'package_lrn'
    TYPE = {3: 'LRN pay per CPS', 4: 'LRN pay per DIP'}
    package_lrn_uuid = Column \
        (String(36), primary_key=True, default=generate_uuid_str(),
         server_default=func.uuid_generate_v4())
    package_name = Column(String(64), unique=True)
    cps = Column(Integer())
    type = Column(ChoiceType(TYPE), default=3)
    lrn_port = Column(Integer())
    dip_count = Column(Integer())
    amount = Column(Integer())
    enabled = Column(Boolean, default=True)
    licenses = relationship('LicenseLrn',
                            uselist=True,
                            back_populates='package')
    create_on = Column(DateTime(True),
                       nullable=True,
                       server_default=func.now())
Exemplo n.º 9
0
class LicenseSwitch(BaseModel):
    __tablename__ = 'license_switch'
    # __table_args__ = (
    #     UniqueConstraint('package_switch_uuid', 'user_uuid', name='uq_license_switch_package_switch_uuid_user_uuid'),
    # )
    DURATION = {1: '1 month', 3: '3 months', 6: '6 months', 12: '12 months'}
    license_switch_uuid = Column \
        (String(36), primary_key=True, default=generate_uuid_str(),
         server_default=func.uuid_generate_v4())
    package_switch_uuid = Column(ForeignKey(
        'package_switch.package_switch_uuid', ondelete='CASCADE'),
                                 index=True)
    ip = Column(String(16), nullable=False, index=True)
    user_uuid = Column(ForeignKey('user.user_uuid', ondelete='CASCADE'),
                       index=True)
    start_time = Column(DateTime(True),
                        nullable=False,
                        server_default=func.now())
    end_time = Column(DateTime(True), nullable=True)
    ordered_amount = Column(Integer)
    cost = Column(Numeric, nullable=False, server_default='0')
    is_enabled = Column(Boolean, default=True)
    duration = Column(ChoiceType(DURATION), server_default='1')

    #switch_uuid = Column(ForeignKey('dnl_license_info.uuid', ondelete='CASCADE'), index=True)

    package = relationship('PackageSwitch',
                           uselist=False,
                           back_populates='licenses')
    user = relationship('User')

    user_email = column_property(
        select([User.email
                ]).where(user_uuid == User.user_uuid).correlate_except(User))

    enabled = column_property(
        select([
            and_(PackageSwitch.enabled, is_enabled, end_time > func.now())
        ]).where(package_switch_uuid == PackageSwitch.package_switch_uuid).
        correlate_except(PackageSwitch))

    type = column_property(
        select([PackageSwitch.type]).where(
            package_switch_uuid ==
            PackageSwitch.package_switch_uuid).correlate_except(PackageSwitch))

    switch_uuid = Column(String(128), index=True)
    # switch_uuid = column_property(
    #     select([PackageSwitch.switch_uuid]).where(
    #         package_switch_uuid == PackageSwitch.package_switch_uuid).correlate_except(PackageSwitch))

    switch_port = column_property(
        select([PackageSwitch.switch_port]).where(
            package_switch_uuid ==
            PackageSwitch.package_switch_uuid).correlate_except(PackageSwitch))
    minute_count = column_property(
        select([PackageSwitch.minute_count]).where(
            package_switch_uuid ==
            PackageSwitch.package_switch_uuid).correlate_except(PackageSwitch))
    amount = column_property(
        select([PackageSwitch.amount]).where(
            package_switch_uuid ==
            PackageSwitch.package_switch_uuid).correlate_except(PackageSwitch))
    package_name = column_property(
        select([PackageSwitch.package_name]).where(
            package_switch_uuid ==
            PackageSwitch.package_switch_uuid).correlate_except(PackageSwitch))

    @property
    def dur_months(self):
        return rev(self.DURATION)[self.duration]

    def renew(self):
        months = self.dur_months
        self.start_time = add_months(self.start_time, months)
        self.end_time = add_months(self.end_time, months)

    def apply_mail(self, template_name):
        return _apply_mail(self, template_name, 'license')

    def add_history(self, gw):
        lic = self
        lic_user = lic.user
        icls = DnlLicenseInfo
        inq = icls.filter(icls.uuid == lic.switch_uuid).first()
        hist = None
        if inq:
            if lic.end_time:
                days = (lic.end_time - lic.start_time).days
            else:
                days = 89
            if lic.package.type == 'switch pay per port':
                mcls = LicenseUpdateHistory
                # mcls(uuid=lic.switch_uuid,license_channel=lic.amount,license_cps=inq.max_cps).save()
                hist = mcls(uuid=lic.switch_uuid,
                            license_channel=lic.amount,
                            license_cps=inq.max_cps,
                            license_day=days,
                            client_name=lic_user.name,
                            operator=gw)
            if lic.package.type == 'switch pay per minute':
                mcls = LicenseUpdateHistory
                hist = mcls(uuid=lic.switch_uuid,
                            license_channel=lic.amount,
                            license_cps=inq.max_cps,
                            license_day=days,
                            client_name=lic_user.name,
                            operator=gw)
        return hist
Exemplo n.º 10
0
class LicenseLrn(BaseModel):
    __tablename__ = 'license_lrn'
    # __table_args__ = (
    #     UniqueConstraint('package_lrn_uuid', 'user_uuid', name='uq_license_lrn_package_lrn_uuid_user_uuid'),
    # )
    DURATION = {1: '1 month', 3: '3 months', 6: '6 months', 12: '12 months'}
    license_lrn_uuid = Column \
        (String(36), primary_key=True, default=generate_uuid_str(),
         server_default=func.uuid_generate_v4())
    package_lrn_uuid = Column(ForeignKey('package_lrn.package_lrn_uuid',
                                         ondelete='CASCADE'),
                              index=True)
    user_uuid = Column(ForeignKey('user.user_uuid', ondelete='CASCADE'),
                       index=True)
    ip = Column(String(16), nullable=False, index=True)
    start_time = Column(DateTime(True),
                        nullable=False,
                        server_default=func.now())
    end_time = Column(DateTime(True), nullable=True)
    ordered_amount = Column(Integer)
    cost = Column(Numeric, nullable=False, server_default='0')
    is_enabled = Column(Boolean, default=True)
    duration = Column(ChoiceType(DURATION), server_default='1')

    package = relationship('PackageLrn',
                           uselist=False,
                           back_populates='licenses')
    user = relationship('User')

    user_email = column_property(
        select([User.email
                ]).where(user_uuid == User.user_uuid).correlate_except(User))
    cps = column_property(
        select([
            PackageLrn.cps
        ]).where(package_lrn_uuid ==
                 PackageLrn.package_lrn_uuid).correlate_except(PackageLrn))
    type = column_property(
        select([
            PackageLrn.type
        ]).where(package_lrn_uuid ==
                 PackageLrn.package_lrn_uuid).correlate_except(PackageLrn))
    lrn_port = column_property(
        select([
            PackageLrn.lrn_port
        ]).where(package_lrn_uuid ==
                 PackageLrn.package_lrn_uuid).correlate_except(PackageLrn))
    dip_count = column_property(
        select([
            PackageLrn.dip_count
        ]).where(package_lrn_uuid ==
                 PackageLrn.package_lrn_uuid).correlate_except(PackageLrn))
    amount = column_property(
        select([
            PackageLrn.amount
        ]).where(package_lrn_uuid ==
                 PackageLrn.package_lrn_uuid).correlate_except(PackageLrn))
    enabled = column_property(
        select([
            and_(PackageLrn.enabled, is_enabled, end_time > func.now())
        ]).where(package_lrn_uuid ==
                 PackageLrn.package_lrn_uuid).correlate_except(PackageLrn))
    package_name = column_property(
        select([
            PackageLrn.package_name
        ]).where(package_lrn_uuid ==
                 PackageLrn.package_lrn_uuid).correlate_except(PackageLrn))

    def renew(self):
        months = self.dur_months
        self.start_time = add_months(self.start_time, months)
        self.end_time = add_months(self.end_time, months)

    def apply_mail(self, template_name):
        return _apply_mail(self, template_name, 'license')

    @property
    def dur_months(self):
        return rev(self.DURATION)[self.duration]

    def add_history(self, gw):
        lic = self
        mcls = LrnPermissionUpdateHistory
        lic_user = lic.user
        return mcls(switch_ip=lic.ip,
                    permit_cps=1000,
                    client_name=lic_user.name,
                    operator=gw)
Exemplo n.º 11
0
class User(BaseModel, AuthUser, RbacUser, ModelUsingFiles):
    __tablename__ = 'user'
    user_uuid = Column(String(36),
                       primary_key=True,
                       default=generate_uuid_str(),
                       server_default=func.uuid_generate_v4())
    # name = Column(String(64), index=True)
    email = Column(String(128), nullable=False, unique=True, index=True)
    password = Column(String(72))
    is_admin = Column(Boolean(), default=False)
    last_login = Column(DateTime(timezone=True))
    is_active = Column(Boolean(), default=False)
    confirmed_on = Column(DateTime(True))
    created_on = Column(DateTime(True), server_default=func.now())
    # addons
    logo_file_uuid = FileModelField(FileModel,
                                    nullable=True,
                                    backend=FILE_BACKEND)
    logo = file_relationship(FileModel, 'User', 'logo_file_uuid')

    first_name = Column(String(32), nullable=True, index=True)
    last_name = Column(String(32), nullable=True, index=True)

    # alerts flags
    alert_payment_received = Column(Boolean(), server_default='true')
    alert_license_expired = Column(Boolean(), server_default='true')
    alert_license_will_expired = Column(Boolean(), server_default='true')
    alert_license_purchased = Column(Boolean(), server_default='true')

    user_id = synonym('user_uuid')
    name = synonym('email')
    user_name = synonym('email')
    is_confirmed = column_property(confirmed_on.isnot(None))

    full_name = column_property(func.concat(first_name, ' ', last_name))

    @classmethod
    def init(cls):
        adm = cls.get(settings.ADMIN_UUID)
        if not adm:
            cls(user_uuid=settings.ADMIN_UUID,
                email=settings.ADMIN_EMAIL,
                passwd=settings.ADMIN_PWD,
                is_admin=True,
                is_active=True).save()
        test = cls.get(settings.TEST_USER_UUID)
        if not test:
            cls(user_uuid=settings.TEST_USER_UUID,
                email=settings.TEST_USER_EMAIL,
                passwd=settings.ADMIN_PWD,
                is_admin=False,
                is_active=True).save()

    @hybrid_property
    def passwd(self):
        return '********'  # self.password

    @passwd.setter
    def passwd(self, value):
        self.password = get_hashed_password(value)

    @classmethod
    def get_user_from_credentials(cls, credentials):
        try:
            return cls.filter(
                or_(User.name == credentials['email'],
                    User.email == credentials['email'])).one()
        except:  # errors.NoResultFound:
            cls.query().session.rollback()
            return None

    def get_token_data(self):
        return dict(user_uuid=self.user_uuid)

    @classmethod
    def get_user_from_token_data(cls, token_data):
        if 'user_uuid' in token_data:
            return cls.filter(
                User.user_uuid == token_data['user_uuid']).first()
        return None

    @classmethod
    def get_user_by_id(cls, user_uuid):
        try:
            return cls.filter(User.user_uuid == user_uuid).one()
        except errors.NoResultFound:  # pragma: no cover
            return None

    def can_login(self, req, resp):
        if self.is_active:
            return True
        else:
            resources.BaseResource.set_response(
                resp,
                resources.responses.
                UnAuthorizedErrorResponse(data=resources.errors.Error(
                    10000,
                    'You are not allowed to login. You must to finish confirm procedure or ask admin to activate account',
                    'account disabled')))
            return False
        request_ip = helpers.get_request_ip(req)
        if request_ip in settings.ALWAYS_ALLOWED_AUTH_IPS:
            return True
        # try:
        #    UserAuthIp.filter(UserAuthIp.ip == request_ip, UserAuthIp.user_uuid == self.user_uuid).one()
        #    return True
        # except errors.NoResultFound:
        #    if not UserAuthIp.filter(UserAuthIp.user_uuid == self.user_uuid).count():
        #        return True
        resources.BaseResource.set_response(
            resp,
            resources.responses.UnAuthorizedErrorResponse(
                data=resources.errors.Error(
                    10000, 'You are not allowed to login from the IP {}'.
                    format(request_ip), 'ip_not_allowed')))
        return False

    # noinspection PyMethodMayBeStatic,PyUnusedLocal
    def can_restore(self, object_revision):
        return True

    def get_id(self):
        return self.user_uuid

    def user_type(self):
        return self.get_role().get_name()

    def get_role(self):
        if self.is_admin:
            return AdminRole
        else:
            return UserRole
        return RbacRoleNoRole

    def before_save(self):
        super().before_save()
        if (not self.name) and self.email:
            self.name = self.email
        if (not self.email) and self.name:
            self.email = self.name

    def apply_mail(self, template_name):
        return _apply_mail(self, template_name, 'user')

    @property
    def reset_password_url(self):
        if self.token:
            return '{}{}{}/auth/reset_password/{}'.format(
                settings.API_SCHEME, settings.API_HOST, settings.API_BASE_PATH,
                self.token)
        return ''

    @property
    def confirm_url(self):
        if self.token:
            return '{}{}{}/registration/confirm/{}'.format(
                settings.API_SCHEME, settings.API_HOST, settings.API_BASE_PATH,
                self.token)
        return ''

    @property
    def login_url(self):
        return '{}{}{}/auth/'.format(settings.API_SCHEME, settings.API_HOST,
                                     settings.API_BASE_PATH)