Пример #1
0
class HostGroup(Base):
    """
	Host group object.
	"""
    __tablename__ = 'hosts_groups'
    __table_args__ = (Comment('Host groups'),
                      Index('hosts_groups_u_hgname', 'name', unique=True), {
                          'mysql_engine': 'InnoDB',
                          'mysql_charset': 'utf8',
                          'info': {
                              'cap_menu':
                              'BASE_HOSTS',
                              'cap_read':
                              'HOSTS_LIST',
                              'cap_create':
                              'HOSTS_GROUPS_CREATE',
                              'cap_edit':
                              'HOSTS_GROUPS_EDIT',
                              'cap_delete':
                              'HOSTS_GROUPS_DELETE',
                              'menu_name':
                              _('Host Groups'),
                              'show_in_menu':
                              'admin',
                              'default_sort': ({
                                  'property': 'name',
                                  'direction': 'ASC'
                              }, ),
                              'grid_view': ('hgid', 'name', 'public'),
                              'grid_hidden': ('hgid', ),
                              'form_view':
                              ('name', 'public', 'startoffset', 'endoffset',
                               'startoffset6', 'endoffset6', 'use_hwaddr',
                               'use_dhcp', 'use_banning'),
                              'easy_search': ('name', ),
                              'detail_pane':
                              ('netprofile_core.views', 'dpane_simple'),
                              'create_wizard':
                              SimpleWizard(title=_('Add new host group'))
                          }
                      })
    id = Column('hgid',
                UInt32(),
                Sequence('hosts_groups_hgid_seq'),
                Comment('Host group ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    name = Column(Unicode(255),
                  Comment('Host group name'),
                  nullable=False,
                  info={
                      'header_string': _('Name'),
                      'column_flex': 1
                  })
    public = Column(NPBoolean(),
                    Comment('Is host group globally visible?'),
                    nullable=False,
                    default=True,
                    server_default=npbool(True),
                    info={'header_string': _('Public')})
    ipv4_start_offset = Column('startoffset',
                               UInt16(),
                               Comment('IP allocator start offset'),
                               nullable=False,
                               default=0,
                               server_default=text('0'),
                               info={'header_string': _('IPv4 Start Offset')})
    ipv4_end_offset = Column('endoffset',
                             UInt16(),
                             Comment('IP allocator end offset'),
                             nullable=False,
                             default=0,
                             server_default=text('0'),
                             info={'header_string': _('IPv4 End Offset')})
    ipv6_start_offset = Column('startoffset6',
                               UInt64(),
                               Comment('IPv6 allocator start offset'),
                               nullable=False,
                               default=0,
                               server_default=text('0'),
                               info={'header_string': _('IPv6 Start Offset')})
    ipv6_end_offset = Column('endoffset6',
                             UInt64(),
                             Comment('IPv6 allocator end offset'),
                             nullable=False,
                             default=0,
                             server_default=text('0'),
                             info={'header_string': _('IPv6 End Offset')})
    use_hwaddr = Column(NPBoolean(),
                        Comment('Use unique hardware address check'),
                        nullable=False,
                        default=True,
                        server_default=npbool(True),
                        info={'header_string': _('Unique Hardware Address')})
    use_dhcp = Column(NPBoolean(),
                      Comment('Use DHCP'),
                      nullable=False,
                      default=True,
                      server_default=npbool(True),
                      info={'header_string': _('DHCP')})
    use_banning = Column(NPBoolean(),
                         Comment('Use banning system'),
                         nullable=False,
                         default=True,
                         server_default=npbool(True),
                         info={'header_string': _('Banning System')})

    def __str__(self):
        return str(self.name)
Пример #2
0
class NetworkServiceType(Base):
    """
	Network service type object.
	"""
    __tablename__ = 'nets_hltypes'
    __table_args__ = (Comment('Networks-hosts linkage types'),
                      Index('nets_hltypes_u_name', 'name', unique=True), {
                          'mysql_engine': 'InnoDB',
                          'mysql_charset': 'utf8',
                          'info': {
                              'cap_menu':
                              'BASE_NETS',
                              'cap_read':
                              'NETS_LIST',
                              'cap_create':
                              'NETS_SERVICETYPES_CREATE',
                              'cap_edit':
                              'NETS_SERVICETYPES_EDIT',
                              'cap_delete':
                              'NETS_SERVICETYPES_DELETE',
                              'menu_name':
                              _('Services'),
                              'show_in_menu':
                              'admin',
                              'default_sort': ({
                                  'property': 'name',
                                  'direction': 'ASC'
                              }, ),
                              'grid_view': ('hltypeid', 'name', 'unique'),
                              'grid_hidden': ('hltypeid', ),
                              'form_view': ('name', 'unique'),
                              'easy_search': ('name', ),
                              'detail_pane':
                              ('netprofile_core.views', 'dpane_simple'),
                              'create_wizard':
                              SimpleWizard(
                                  title=_('Add new network service type'))
                          }
                      })
    id = Column('hltypeid',
                UInt32(),
                Sequence('nets_hltypes_hltypeid_seq', start=101, increment=1),
                Comment('Networks-hosts linkage type ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    name = Column(Unicode(255),
                  Comment('Networks-hosts linkage type name'),
                  nullable=False,
                  info={
                      'header_string': _('Name'),
                      'column_flex': 1
                  })
    unique = Column(NPBoolean(),
                    Comment('Is unique per network?'),
                    nullable=False,
                    default=False,
                    server_default=npbool(False),
                    info={'header_string': _('Unique')})

    services = relationship('NetworkService',
                            backref=backref('type', innerjoin=True))

    def __str__(self):
        req = getattr(self, '__req__', None)
        if req:
            return req.localizer.translate(_(self.name))
        return str(self.name)
Пример #3
0
class Network(Base):
    """
	Network object.
	"""
    __tablename__ = 'nets_def'
    __table_args__ = (
        Comment('Networks'), Index('nets_def_u_name', 'name', unique=True),
        Index('nets_def_u_ipaddr', 'ipaddr', unique=True),
        Index('nets_def_u_ip6addr', 'ip6addr',
              unique=True), Index('nets_def_i_domainid', 'domainid'),
        Index('nets_def_i_netgid',
              'netgid'), Index('nets_def_i_rtid',
                               'rtid'), Index('nets_def_i_mgmtdid', 'mgmtdid'),
        Trigger('after', 'insert',
                't_nets_def_ai'), Trigger('after', 'update', 't_nets_def_au'),
        Trigger('after', 'delete', 't_nets_def_ad'), {
            'mysql_engine': 'InnoDB',
            'mysql_charset': 'utf8',
            'info': {
                'cap_menu':
                'BASE_NETS',
                'cap_read':
                'NETS_LIST',
                'cap_create':
                'NETS_CREATE',
                'cap_edit':
                'NETS_EDIT',
                'cap_delete':
                'NETS_DELETE',
                'menu_name':
                _('Networks'),
                'show_in_menu':
                'modules',
                'menu_main':
                True,
                'default_sort': ({
                    'property': 'name',
                    'direction': 'ASC'
                }, ),
                'grid_view':
                ('netid', 'name', 'domain', 'group', 'ipaddr', 'ip6addr',
                 MarkupColumn(
                     name='state',
                     header_string=_('State'),
                     template=TemplateObject(
                         'netprofile_networks:templates/networks_icons.mak'),
                     column_width=40,
                     column_resizable=False)),
                'grid_hidden': ('netid', 'domain', 'group'),
                'form_view': ('name', 'domain', 'group', 'management_device',
                              'enabled', 'public', 'ipaddr', 'cidr', 'ip6addr',
                              'cidr6', 'vlanid', 'routing_table', 'gueststart',
                              'guestend', 'gueststart6', 'guestend6', 'descr'),
                'easy_search': ('name', ),
                'detail_pane': ('netprofile_core.views', 'dpane_simple'),
                'create_wizard':
                SimpleWizard(title=_('Add new network'))
            }
        })
    id = Column('netid',
                UInt32(),
                Sequence('nets_def_netid_seq'),
                Comment('Network ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    name = Column(Unicode(255),
                  Comment('Network name'),
                  nullable=False,
                  info={
                      'header_string': _('Name'),
                      'column_flex': 1
                  })
    domain_id = Column('domainid',
                       UInt32(),
                       ForeignKey('domains_def.domainid',
                                  name='nets_def_fk_domainid',
                                  onupdate='CASCADE'),
                       Comment('Domain ID'),
                       nullable=False,
                       info={
                           'header_string': _('Domain'),
                           'filter_type': 'nplist',
                           'column_flex': 1
                       })
    group_id = Column('netgid',
                      UInt32(),
                      ForeignKey('nets_groups.netgid',
                                 name='nets_def_fk_netgid',
                                 ondelete='SET NULL',
                                 onupdate='CASCADE'),
                      Comment('Network group ID'),
                      nullable=True,
                      default=None,
                      server_default=text('NULL'),
                      info={
                          'header_string': _('Group'),
                          'filter_type': 'nplist',
                          'column_flex': 1
                      })
    management_device_id = Column('mgmtdid',
                                  UInt32(),
                                  ForeignKey('devices_network.did',
                                             name='nets_def_fk_mgmtdid',
                                             ondelete='SET NULL',
                                             onupdate='CASCADE'),
                                  Comment('Management device ID'),
                                  nullable=True,
                                  default=None,
                                  server_default=text('NULL'),
                                  info={
                                      'header_string': _('Management Device'),
                                      'filter_type': 'none'
                                  })
    enabled = Column(NPBoolean(),
                     Comment('Is network enabled?'),
                     nullable=False,
                     default=True,
                     server_default=npbool(True),
                     info={'header_string': _('Enabled')})
    public = Column(NPBoolean(),
                    Comment('Is network visible to outsiders?'),
                    nullable=False,
                    default=True,
                    server_default=npbool(True),
                    info={'header_string': _('Public')})
    ipv4_address = Column('ipaddr',
                          IPv4Address(),
                          Comment('Network IPv4 address'),
                          nullable=True,
                          default=None,
                          server_default=text('NULL'),
                          info={'header_string': _('IPv4 Address')})
    ipv6_address = Column('ip6addr',
                          IPv6Address(),
                          Comment('Network IPv6 address'),
                          nullable=True,
                          default=None,
                          server_default=text('NULL'),
                          info={'header_string': _('IPv6 Address')})
    ipv4_cidr = Column('cidr',
                       UInt8(),
                       Comment('Network CIDR number'),
                       nullable=False,
                       default=24,
                       server_default=text('24'),
                       info={'header_string': _('IPv4 Netmask')})
    ipv6_cidr = Column('cidr6',
                       UInt8(),
                       Comment('Network CIDRv6 number'),
                       nullable=False,
                       default=64,
                       server_default=text('64'),
                       info={'header_string': _('IPv6 Netmask')})
    vlan_id = Column('vlanid',
                     UInt16(),
                     Comment('Network VLAN ID'),
                     nullable=False,
                     default=0,
                     server_default=text('0'),
                     info={'header_string': _('VLAN')})
    routing_table_id = Column('rtid',
                              UInt32(),
                              ForeignKey('rt_def.rtid',
                                         name='nets_def_fk_rtid',
                                         ondelete='SET NULL',
                                         onupdate='CASCADE'),
                              Comment('Routing table ID'),
                              nullable=True,
                              default=None,
                              server_default=text('NULL'),
                              info={
                                  'header_string': _('Routing Table'),
                                  'filter_type': 'nplist'
                              })
    ipv4_guest_start = Column(
        'gueststart',
        UInt16(),
        Comment('Start of IPv4 guest allocation area'),
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={'header_string': _('Start of IPv4 Guest Allocation Area')})
    ipv4_guest_end = Column(
        'guestend',
        UInt16(),
        Comment('End of IPv4 guest allocation area'),
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={'header_string': _('End of IPv4 Guest Allocation Area')})
    ipv6_guest_start = Column(
        'gueststart6',
        IPv6Offset(),
        Comment('Start of IPv6 guest allocation area'),
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={'header_string': _('Start of IPv6 Guest Allocation Area')})
    ipv6_guest_end = Column(
        'guestend6',
        IPv6Offset(),
        Comment('End of IPv6 guest allocation area'),
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={'header_string': _('End of IPv6 Guest Allocation Area')})
    description = Column('descr',
                         UnicodeText(),
                         Comment('Network description'),
                         nullable=True,
                         default=None,
                         server_default=text('NULL'),
                         info={'header_string': _('Description')})

    domain = relationship('Domain', innerjoin=True, backref='networks')
    group = relationship('NetworkGroup',
                         backref=backref('networks', passive_deletes=True))
    management_device = relationship('NetworkDevice',
                                     backref=backref('networks',
                                                     passive_deletes=True))
    routing_table = relationship('RoutingTable',
                                 backref=backref('networks',
                                                 passive_deletes=True))
    services = relationship('NetworkService',
                            backref=backref('network', innerjoin=True),
                            cascade='all, delete-orphan',
                            passive_deletes=True)

    @property
    def ipv4_network(self):
        if self.ipv4_address:
            return ipaddr.IPv4Network(
                '%s/%s' % (str(self.ipv4_address), str(self.ipv4_cidr)))

    @property
    def ipv6_network(self):
        if self.ipv6_address:
            return ipaddr.IPv6Network(
                '%s/%s' % (str(self.ipv6_address), str(self.ipv6_cidr)))

    def __str__(self):
        return str(self.name)
Пример #4
0
                                 args=(InArgument('xepid', UInt32()),
                                       InArgument('ts', DateTime())),
                                 comment='Execute paid service handler',
                                 label='psefunc',
                                 is_procedure=True)

PSPollProcedure = SQLFunction('ps_poll',
                              args=(InArgument('ts', DateTime()), ),
                              comment='Poll paid services',
                              is_procedure=True)

AcctPCheckProcedure = SQLFunction(
    'acct_pcheck',
    args=(InArgument('aeid', UInt32()), InArgument('ts', DateTime()),
          InArgument('rate_type',
                     RateType.db_type()), InOutArgument('isok', NPBoolean()),
          InOutArgument('user_stashid',
                        UInt32()), InOutArgument('user_qpend', DateTime()),
          InOutArgument('stash_amount',
                        Money()), InOutArgument('stash_credit', Money()),
          InArgument('xcurrid', UInt32()), InArgument('xrate', Money()),
          InArgument('pay', Money())),
    comment='Run linked paid service checks',
    label='aapfunc',
    is_procedure=True)

PSPollEvent = SQLEvent('ev_ps_poll',
                       sched_unit='minute',
                       sched_interval=15,
                       comment='Poll for independent paid services')
Пример #5
0
class PaidService(Base):
    """
	Paid service mapping object.
	"""
    __tablename__ = 'paid_def'
    __table_args__ = (Comment('Paid service mappings'),
                      Index('paid_def_i_entityid',
                            'entityid'), Index('paid_def_i_aeid', 'aeid'),
                      Index('paid_def_i_hostid',
                            'hostid'), Index('paid_def_i_stashid', 'stashid'),
                      Index('paid_def_i_paidid',
                            'paidid'), Index('paid_def_i_active', 'active'),
                      Index('paid_def_i_qpend', 'qpend'),
                      Trigger('before', 'insert', 't_paid_def_bi'),
                      Trigger('before', 'update', 't_paid_def_bu'),
                      Trigger('after', 'insert', 't_paid_def_ai'),
                      Trigger('after', 'update', 't_paid_def_au'),
                      Trigger('after', 'delete', 't_paid_def_ad'), {
                          'mysql_engine': 'InnoDB',
                          'mysql_charset': 'utf8',
                          'info': {
                              'cap_menu':
                              'BASE_PAIDSERVICES',
                              'cap_read':
                              'PAIDSERVICES_LIST',
                              'cap_create':
                              'PAIDSERVICES_CREATE',
                              'cap_edit':
                              'PAIDSERVICES_EDIT',
                              'cap_delete':
                              'PAIDSERVICES_DELETE',
                              'default_sort': ({
                                  'property': 'qpend',
                                  'direction': 'DESC'
                              }, ),
                              'grid_view': ('epid', 'entity', 'stash', 'type',
                                            'active', 'qpend'),
                              'grid_hidden': ('epid', ),
                              'form_view': (),
                              'detail_pane':
                              ('netprofile_core.views', 'dpane_simple')
                          }
                      })
    id = Column('epid',
                UInt32(),
                Sequence('paid_def_epid_seq'),
                Comment('Paid service mapping ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    entity_id = Column('entityid',
                       UInt32(),
                       Comment('Entity ID'),
                       ForeignKey('entities_def.entityid',
                                  name='paid_def_fk_entityid',
                                  onupdate='CASCADE',
                                  ondelete='CASCADE'),
                       nullable=False,
                       info={
                           'header_string': _('Entity'),
                           'filter_type': 'none',
                           'column_flex': 2
                       })
    access_entity_id = Column('aeid',
                              UInt32(),
                              Comment('Access entity ID'),
                              ForeignKey('entities_access.entityid',
                                         name='paid_def_fk_aeid',
                                         onupdate='CASCADE',
                                         ondelete='CASCADE'),
                              nullable=True,
                              default=None,
                              server_default=text('NULL'),
                              info={
                                  'header_string': _('Access Entity'),
                                  'filter_type': 'none',
                                  'column_flex': 2
                              })
    host_id = Column('hostid',
                     UInt32(),
                     Comment('Host ID'),
                     ForeignKey('hosts_def.hostid',
                                name='paid_def_fk_hostid',
                                onupdate='CASCADE',
                                ondelete='CASCADE'),
                     nullable=True,
                     default=None,
                     server_default=text('NULL'),
                     info={
                         'header_string': _('Host'),
                         'filter_type': 'none',
                         'column_flex': 2
                     })
    stash_id = Column('stashid',
                      UInt32(),
                      ForeignKey('stashes_def.stashid',
                                 name='paid_def_fk_stashid',
                                 onupdate='CASCADE',
                                 ondelete='CASCADE'),
                      Comment('Used stash ID'),
                      nullable=False,
                      info={
                          'header_string': _('Stash'),
                          'column_flex': 3
                      })
    paid_id = Column('paidid',
                     UInt32(),
                     ForeignKey('paid_types.paidid',
                                name='paid_def_fk_paidid',
                                onupdate='CASCADE'),
                     Comment('Type ID'),
                     nullable=False,
                     info={
                         'header_string': _('Stash'),
                         'column_flex': 3
                     })
    active = Column(NPBoolean(),
                    Comment('Is service active'),
                    nullable=False,
                    default=True,
                    server_default=npbool(True),
                    info={'header_string': _('Active')})
    quota_period_end = Column('qpend',
                              TIMESTAMP(),
                              Comment('End of quota period'),
                              nullable=True,
                              default=None,
                              server_default=FetchedValue(),
                              info={'header_string': _('Ends')})
    description = Column('descr',
                         UnicodeText(),
                         Comment('Description'),
                         nullable=True,
                         default=None,
                         server_default=text('NULL'),
                         info={'header_string': _('Description')})

    type = relationship('PaidServiceType',
                        innerjoin=True,
                        lazy='joined',
                        backref='paid_services')
    entity = relationship('Entity',
                          foreign_keys=entity_id,
                          innerjoin=True,
                          backref=backref('paid_services',
                                          cascade='all, delete-orphan',
                                          passive_deletes=True))
    access_entity = relationship('AccessEntity',
                                 foreign_keys=access_entity_id,
                                 backref=backref('paid_services_access',
                                                 cascade='all, delete-orphan',
                                                 passive_deletes=True))
    host = relationship('Host',
                        backref=backref('paid_services',
                                        cascade='all, delete-orphan',
                                        passive_deletes=True))
    stash = relationship('Stash',
                         innerjoin=True,
                         backref=backref('paid_services',
                                         cascade='all, delete-orphan',
                                         passive_deletes=True))

    def __str__(self):
        return '%s: %s' % (str(self.stash), str(self.type))
Пример #6
0
class Currency(Base):
	"""
	Stash currency object.
	"""
	__tablename__ = 'currencies_def'
	__table_args__ = (
		Comment('Currencies'),
		Index('currencies_def_u_name', 'name', unique=True),
		Index('currencies_def_u_code', 'code', unique=True),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_STASHES',
				'cap_read'      : 'STASHES_LIST',
				'cap_create'    : 'STASHES_CURRENCIES_CREATE',
				'cap_edit'      : 'STASHES_CURRENCIES_EDIT',
				'cap_delete'    : 'STASHES_CURRENCIES_DELETE',
				'menu_name'     : _('Currencies'),
				'show_in_menu'  : 'admin',
				'default_sort'  : ({ 'property': 'name', 'direction': 'ASC' },),
				'grid_view'     : ('currid', 'name', 'code'),
				'grid_hidden'   : ('currid',),
				'form_view'     : (
					'name', 'code',
					'prefix', 'suffix',
					'xchange_rate',
					'xchange_from', 'xchange_to',
					'convert_from', 'convert_to',
					'allow_credit', 'allow_accounts', 'allow_services', 'allow_futures',
					'oper_visible', 'user_visible',
					'descr'
				),
				'easy_search'   : ('name', 'code', 'prefix', 'suffix'),
				'detail_pane'   : ('netprofile_core.views', 'dpane_simple'),
				'create_wizard' : SimpleWizard(title=_('Add new currency'))
			}
		}
	)
	id = Column(
		'currid',
		UInt32(),
		Sequence('currencies_def_currid_seq'),
		Comment('Currency ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	name = Column(
		Unicode(255),
		Comment('Currency name'),
		nullable=False,
		info={
			'header_string' : _('Name'),
			'column_flex'   : 3
		}
	)
	code = Column(
		CHAR(3),
		Comment('ISO 4217 currency code'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Code')
		}
	)
	prefix = Column(
		Unicode(16),
		Comment('Currency symbol prefix'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Prefix')
		}
	)
	suffix = Column(
		Unicode(16),
		Comment('Currency symbol suffix'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Suffix')
		}
	)
	exchange_rate = Column(
		'xchange_rate',
		Money(),
		Comment('Fallback exchange rate with default currency'),
		nullable=False,
		default=1,
		server_default=text('1'),
		info={
			'header_string' : _('Exchange Rate')
		}
	)
	can_exchange_from = Column(
		'xchange_from',
		NPBoolean(),
		Comment('Can exchange from this currency'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Exchange From')
		}
	)
	can_exchange_to = Column(
		'xchange_to',
		NPBoolean(),
		Comment('Can exchange to this currency'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Exchange To')
		}
	)
	can_convert_from = Column(
		'convert_from',
		NPBoolean(),
		Comment('Allow converting stashes from this currency'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Convert From')
		}
	)
	can_convert_to = Column(
		'convert_to',
		NPBoolean(),
		Comment('Allow converting stashes to this currency'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Convert To')
		}
	)
	allow_credit = Column(
		NPBoolean(),
		Comment('Allow crediting with this currency'),
		nullable=False,
		default=True,
		server_default=npbool(True),
		info={
			'header_string' : _('Crediting')
		}
	)
	allow_accounts = Column(
		NPBoolean(),
		Comment('Allow linking accounts to stashes with this currency'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Allow Accounts')
		}
	)
	allow_services = Column(
		NPBoolean(),
		Comment('Allow linking paid services to stashes with this currency'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Allow Paid Services')
		}
	)
	allow_futures = Column(
		NPBoolean(),
		Comment('Allow promised payments to stashes with this currency'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Allow Promised Payments')
		}
	)
	visible_to_operator = Column(
		'oper_visible',
		NPBoolean(),
		Comment('Visibility in operator interface'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Visible to Operator')
		}
	)
	visible_to_user = Column(
		'user_visible',
		NPBoolean(),
		Comment('Visibility in user interface'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Visible to User')
		}
	)
	description = Column(
		'descr',
		UnicodeText(),
		Comment('Currency description'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Description')
		}
	)

	def __str__(self):
		return str(self.name)

	def format(self, req, amount):
		return money_format(req, amount, code=self.code, prefix=self.prefix, suffix=self.suffix)

	def format_long(self, req, amount):
		return money_format_long(req, amount, code=self.code)
Пример #7
0
class StashIOType(Base):
	"""
	Stash I/O operation type object.
	"""
	__tablename__ = 'stashes_io_types'
	__table_args__ = (
		Comment('Stashes input/output operation types'),
		Index('stashes_io_types_i_type', 'type'),
		Index('stashes_io_types_u_ftype', 'ftype', unique=True),
		Index('stashes_io_types_i_oper_visible', 'oper_visible'),
		Index('stashes_io_types_i_user_visible', 'user_visible'),
		Index('stashes_io_types_i_oper_cap', 'oper_cap'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_STASHES',
				'cap_read'      : 'STASHES_IO',
				'cap_create'    : 'STASHES_IOTYPES_CREATE',
				'cap_edit'      : 'STASHES_IOTYPES_EDIT',
				'cap_delete'    : 'STASHES_IOTYPES_DELETE',
				'menu_name'     : _('Operation Types'),
				'show_in_menu'  : 'admin',
				'default_sort'  : ({ 'property': 'name', 'direction': 'ASC' },),
				'grid_view'     : ('name', 'class', 'type'),
				'form_view'     : ('name', 'class', 'type', 'ftype', 'user_visible', 'oper_visible', 'oper_capability', 'pays_futures', 'descr'),
				'easy_search'   : ('name',),
				'detail_pane'   : ('netprofile_core.views', 'dpane_simple'),
				'create_wizard' : SimpleWizard(title=_('Add new operation type'))
			}
		}
	)
	id = Column(
		'siotypeid',
		UInt32(),
		Sequence('stashes_io_types_siotypeid_seq', start=101, increment=1),
		Comment('Stash I/O ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	name  = Column(
		Unicode(255),
		Comment('Stash I/O name'),
		nullable=False,
		info={
			'header_string' : _('Name'),
			'column_flex'   : 1
		}
	)
	io_class = Column(
		'class',
		OperationClass.db_type(),
		Comment('Stash I/O class'),
		nullable=False,
		default=OperationClass.system,
		server_default=OperationClass.system,
		info={
			'header_string' : _('Class')
		}
	)
	type = Column(
		IOOperationType.db_type(),
		Comment('Stash I/O type'),
		nullable=False,
		default=IOOperationType.bidirectional,
		server_default=IOOperationType.bidirectional,
		info={
			'header_string' : _('Type')
		}
	)
	function_type = Column(
		'ftype',
		IOFunctionType.db_type(),
		Comment('Special built-in function for this I/O type'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Function')
		}
	)
	visible_to_operator = Column(
		'oper_visible',
		NPBoolean(),
		Comment('Visibility in operator interface'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Visible to Operator')
		}
	)
	visible_to_user = Column(
		'user_visible',
		NPBoolean(),
		Comment('Visibility in user interface'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Visible to User')
		}
	)
	fulfills_futures = Column(
		'pays_futures',
		NPBoolean(),
		Comment('Serves as a fulfillment for promised payments'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Counts for promised payments')
		}
	)
	oper_capability_code = Column(
		'oper_cap',
		ASCIIString(48),
		Comment('Stash I/O required operator capability'),
		ForeignKey('privileges.code', name='stashes_io_types_fk_oper_cap', onupdate='CASCADE', ondelete='SET NULL'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Required Operator Capability')
		}
	)
	description = Column(
		'descr',
		UnicodeText(),
		Comment('Stash I/O description'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Description')
		}
	)

	oper_capability = relationship(
		'Privilege',
		backref=backref(
			'stash_io_types',
			passive_deletes=True
		),
		lazy='joined'
	)

	def __str__(self):
		if self.io_class == OperationClass.system:
			req = getattr(self, '__req__', None)
			if req:
				return req.localizer.translate(_(self.name))
		return str(self.name)
Пример #8
0
class DomainServiceType(Base):
	"""
	Domains-to-hosts linkage type.
	"""
	__tablename__ = 'domains_hltypes'
	__table_args__ = (
		Comment('Domains-hosts linkage types'),
		Index('domains_hltypes_u_name', 'name', unique=True),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_DOMAINS',
				'cap_read'      : 'DOMAINS_LIST',
				'cap_create'    : 'DOMAINS_SERVICETYPES_CREATE',
				'cap_edit'      : 'DOMAINS_SERVICETYPES_EDIT',
				'cap_delete'    : 'DOMAINS_SERVICETYPES_DELETE',

				'show_in_menu'  : 'admin',
				'menu_name'     : _('Domain Service Types'),
				'default_sort'  : ({ 'property': 'name' ,'direction': 'ASC' },),
				'grid_view'     : ('hltypeid', 'name', 'unique'),
				'grid_hidden'   : ('hltypeid',),
				'easy_search'   : ('name',),

				'create_wizard' : SimpleWizard(title=_('Add new type'))
			}
		}
	)
	id = Column(
		'hltypeid',
		UInt32(),
		Sequence('domains_hltypes_hltypeid_seq', start=101, increment=1),
		Comment('Domains-hosts linkage type ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	name = Column(
		Unicode(255),
		Comment('Domains-hosts linkage type name'),
		nullable=False,
		info={
			'header_string' : _('Name'),
			'column_flex'   : 1
		}
	)
	unique = Column(
		NPBoolean(),
		Comment('Is unique per domain?'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Unique')
		}
	)

	def __str__(self):
		req = getattr(self, '__req__', None)
		if req:
			return req.localizer.translate(_(self.name))
		return str(self.name)
Пример #9
0
class UserLocation(Base):
	"""
	Users' addresses.
	"""
	__tablename__ = 'users_locations'
	__table_args__ = (
		Comment('User locations'),
		Index('users_locations_i_uid', 'uid'),
		Index('users_locations_i_houseid', 'houseid'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_read'      : 'USERS_LIST',
				'cap_create'    : 'USERS_EDIT',
				'cap_edit'      : 'USERS_EDIT',
				'cap_delete'    : 'USERS_EDIT',

				'menu_name'     : _('User Addresses'),
				'default_sort'  : ({ 'property': 'atype' ,'direction': 'ASC' },),
				'grid_view'     : (
					'ulocid', 'user', 'primary', 'atype',
					MarkupColumn(
						header_string=_('Address'),
						column_flex=3,
						template='{__str__}'
					)
				),
				'grid_hidden'   : ('ulocid',),
				'form_view'     : (
					'user', 'primary', 'atype', 'house',
					'country', 'stprov', 'city', 'addr',
					'entrance', 'floor', 'flat', 'room',
					'entrycode', 'postindex', 'descr'
				),
				'detail_pane'   : ('netprofile_core.views', 'dpane_simple'),
				'create_wizard' : SimpleWizard(title=_('Add new user address'))
			}
		}
	)
	id = Column(
		'ulocid',
		UInt32(),
		Sequence('users_locations_ulocid_seq'),
		Comment('User location ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	user_id = Column(
		'uid',
		UInt32(),
		ForeignKey('users.uid', name='users_locations_fk_uid', ondelete='CASCADE', onupdate='CASCADE'),
		Comment('User ID'),
		nullable=False,
		info={
			'header_string' : _('User'),
			'filter_type'   : 'none'
		}
	)
	primary = Column(
		NPBoolean(),
		Comment('Primary flag'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Primary')
		}
	)
	type = Column(
		'atype',
		AddressType.db_type(),
		Comment('Address type'),
		nullable=False,
		default=AddressType.work,
		server_default=AddressType.work,
		info={
			'header_string' : _('Type'),
			'column_flex'   : 1
		}
	)
	country = Column(
		CHAR(2),
		Comment('ISO 3166-1 alpha-2 country code'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Country'),
			'choices'       : countries_alpha2
		}
	)
	state_or_province = Column(
		'stprov',
		Unicode(255),
		Comment('State or province name'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('State/province')
		}
	)
	city = Column(
		Unicode(255),
		Comment('City name'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('City')
		}
	)
	address = Column(
		'addr',
		Unicode(255),
		Comment('Freeform address'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Address')
		}
	)
	house_id = Column(
		'houseid',
		UInt32(),
		ForeignKey('addr_houses.houseid', name='users_locations_fk_houseid', ondelete='CASCADE', onupdate='CASCADE'),
		Comment('House ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('House'),
			'filter_type'   : 'none',
			'column_flex'   : 1
		}
	)
	entrance = Column(
		UInt8(),
		Comment('Entrance number'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Entr.')
		}
	)
	floor = Column(
		Int16(),
		Comment('Floor number'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Floor')
		}
	)
	flat = Column(
		UInt16(),
		Comment('Flat/office number'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Flat')
		}
	)
	room = Column(
		Unicode(8),
		Comment('Room identifier'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Room')
		}
	)
	entry_code = Column(
		'entrycode',
		Unicode(8),
		Comment('Entry code'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Entry Code')
		}
	)
	postal_code = Column(
		'postindex',
		Unicode(8),
		Comment('Postal code'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Postal Code')
		}
	)
	description = Column(
		'descr',
		UnicodeText(),
		Comment('Address description'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Description'),
			'column_flex'   : 2
		}
	)

	user = relationship(
		'User',
		innerjoin=True,
		backref=backref(
			'locations',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)

	def __str__(self):
		req = self.__req__ or get_current_request()
		loc = req.localizer
		locale_cur = req.current_locale
		locale_en = req.locales['en']

		ret = []
		bit = self.country
		if bit:
			if bit in locale_cur.territories:
				bit = locale_cur.territories[bit]
			elif bit in locale_en.territories:
				bit = locale_en.territories[bit]
			ret.append(bit + ',')
		bit = self.city_address
		if bit:
			ret.append(bit + ',')
		bit = self.street_address
		if bit:
			ret.append(bit)
		if self.entrance:
			ret.extend((
				loc.translate(_('entr.')),
				str(self.entrance)
			))
		if self.floor:
			ret.extend((
				loc.translate(_('fl.')),
				str(self.floor)
			))
		if self.flat:
			pfx = _('app.')
			if self.type == AddressType.work:
				pfx = _('office')
			ret.extend((
				loc.translate(pfx),
				str(self.flat)
			))

		return ' '.join(ret)

	def add_to_vcard(self, card):
		data = dict()
		if self.country:
			data['country'] = self.country
		if self.state_or_province:
			data['region'] = self.state_or_province
		if self.postal_code:
			data['box'] = self.postal_code
		bit = self.city_address
		if bit:
			data['city'] = bit
		bit = self.street_address
		if bit:
			data['street'] = bit
		if len(data) > 0:
			obj = card.add('adr')
			obj.value = vobject.vcard.Address(**data)
			objtype = list(AddressType.vcard_types(self.type))
			if self.primary:
				objtype.append('pref')
			obj.type_paramlist = objtype

	@property
	def city_address(self):
		if self.house and self.house.street:
			return str(self.house.street.city)
		return self.city

	@property
	def street_address(self):
		if self.house:
			return str(self.house)
		return self.address
Пример #10
0
class IPv4Address(Base):
    """
	IPv4 address object.
	"""
    __tablename__ = 'ipaddr_def'
    __table_args__ = (Comment('IPv4 addresses'),
                      Index('ipaddr_def_u_address',
                            'netid',
                            'offset',
                            unique=True), Index('ipaddr_def_i_hostid',
                                                'hostid'),
                      Index('ipaddr_def_i_poolid',
                            'poolid'), Index('ipaddr_def_i_inuse', 'inuse'),
                      Trigger('before', 'insert', 't_ipaddr_def_bi'),
                      Trigger('before', 'update', 't_ipaddr_def_bu'),
                      Trigger('after', 'insert', 't_ipaddr_def_ai'),
                      Trigger('after', 'update', 't_ipaddr_def_au'),
                      Trigger('after', 'delete', 't_ipaddr_def_ad'), {
                          'mysql_engine': 'InnoDB',
                          'mysql_charset': 'utf8',
                          'info': {
                              'cap_menu':
                              'BASE_IPADDR',
                              'cap_read':
                              'IPADDR_LIST',
                              'cap_create':
                              'IPADDR_CREATE',
                              'cap_edit':
                              'IPADDR_EDIT',
                              'cap_delete':
                              'IPADDR_DELETE',
                              'menu_name':
                              _('IPv4 Addresses'),
                              'show_in_menu':
                              'modules',
                              'grid_view':
                              ('ipaddrid', 'host',
                               MarkupColumn(name='offset',
                                            header_string=_('Address'),
                                            template='{__str__}',
                                            column_flex=1,
                                            sortable=True), 'hwaddr', 'vis',
                               'owned', 'inuse'),
                              'grid_hidden': ('ipaddrid', ),
                              'form_view':
                              ('host', 'network', 'offset', 'hwaddr', 'ttl',
                               'pool', 'vis', 'owned', 'inuse'),
                              'detail_pane':
                              ('netprofile_core.views', 'dpane_simple'),
                              'create_wizard':
                              SimpleWizard(title=_('Add new IPv4 address'))
                          }
                      })
    id = Column('ipaddrid',
                UInt32(),
                Sequence('ipaddr_def_ipaddrid_seq'),
                Comment('IPv4 address ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    host_id = Column('hostid',
                     UInt32(),
                     ForeignKey('hosts_def.hostid',
                                name='ipaddr_def_fk_hostid',
                                onupdate='CASCADE',
                                ondelete='CASCADE'),
                     Comment('Host ID'),
                     nullable=False,
                     info={
                         'header_string': _('Host'),
                         'filter_type': 'none',
                         'column_flex': 1
                     })
    pool_id = Column('poolid',
                     UInt32(),
                     ForeignKey('ippool_def.poolid',
                                name='ipaddr_def_fk_poolid',
                                onupdate='CASCADE',
                                ondelete='SET NULL'),
                     Comment('IP address pool ID'),
                     nullable=True,
                     default=None,
                     server_default=text('NULL'),
                     info={
                         'header_string': _('Pool'),
                         'filter_type': 'nplist'
                     })
    network_id = Column('netid',
                        UInt32(),
                        ForeignKey('nets_def.netid',
                                   name='ipaddr_def_fk_netid',
                                   onupdate='CASCADE',
                                   ondelete='CASCADE'),
                        Comment('Network ID'),
                        nullable=False,
                        info={
                            'header_string': _('Network'),
                            'filter_type': 'nplist'
                        })
    offset = Column(UInt32(),
                    Comment('Offset from network start'),
                    nullable=False,
                    info={'header_string': _('Offset')})
    hardware_address = Column('hwaddr',
                              MACAddress(),
                              Comment('Hardware address'),
                              nullable=False,
                              info={
                                  'header_string': _('Hardware Address'),
                                  'column_flex': 1
                              })
    ttl = Column(UInt32(),
                 Comment('RR time to live'),
                 nullable=True,
                 default=None,
                 server_default=text('NULL'),
                 info={'header_string': _('RR Time To Live')})
    visibility = Column('vis',
                        ObjectVisibility.db_type(),
                        Comment('IPv4 address visibility'),
                        nullable=False,
                        default=ObjectVisibility.both,
                        server_default=ObjectVisibility.both,
                        info={'header_string': _('Visibility')})
    owned = Column(NPBoolean(),
                   Comment('Is statically assigned?'),
                   nullable=False,
                   default=False,
                   server_default=npbool(False),
                   info={'header_string': _('Assigned')})
    in_use = Column('inuse',
                    NPBoolean(),
                    Comment('Is this IPv4 address in use?'),
                    nullable=False,
                    default=False,
                    server_default=npbool(False),
                    info={'header_string': _('In Use')})

    host = relationship('Host',
                        innerjoin=True,
                        lazy='joined',
                        backref=backref('ipv4_addresses',
                                        cascade='all, delete-orphan',
                                        passive_deletes=True))
    pool = relationship('IPPool',
                        backref=backref('ipv4_addresses',
                                        passive_deletes=True))
    network = relationship('Network',
                           innerjoin=True,
                           backref=backref('ipv4_addresses',
                                           cascade='all, delete-orphan',
                                           passive_deletes=True))

    @property
    def address(self):
        if self.network and self.network.ipv4_address:
            return self.network.ipv4_address + self.offset

    @property
    def ptr_name(self):
        addr = self.address
        if addr:
            return int(addr) % 256

    def __str__(self):
        if self.network and self.network.ipv4_address:
            return str(self.network.ipv4_address + self.offset)
Пример #11
0
class Domain(Base):
	"""
	Domain object.
	"""
	__tablename__ = 'domains_def'
	__table_args__ = (
		Comment('Domains'),
		Index('domains_def_u_domain', 'parentid', 'name', unique=True),
		Trigger('after', 'insert', 't_domains_def_ai'),
		Trigger('after', 'update', 't_domains_def_au'),
		Trigger('after', 'delete', 't_domains_def_ad'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_DOMAINS',
				'cap_read'      : 'DOMAINS_LIST',
				'cap_create'    : 'DOMAINS_CREATE',
				'cap_edit'      : 'DOMAINS_EDIT',
				'cap_delete'    : 'DOMAINS_DELETE',

				'show_in_menu'  : 'modules',
				'menu_name'     : _('Domains'),
				'menu_main'     : True,
				'default_sort'  : ({ 'property': 'name' ,'direction': 'ASC' },),
				'grid_view'     : (
					'domainid',
					MarkupColumn(
						name='name',
						header_string=_('Name'),
						template='{__str__}',
						column_flex=1,
						sortable=True
					),
					'parent',
					MarkupColumn(
						name='state',
						header_string=_('State'),
						template=TemplateObject('netprofile_domains:templates/domain_icons.mak'),
						cell_class='np-nopad',
						column_width=60,
						column_resizable=False
					)
				),
				'grid_hidden'   : ('domainid',),
				'form_view'		: (
					'name', 'parent',
					'enabled', 'public', 'signed',
					'soa_refresh', 'soa_retry', 'soa_expire', 'soa_minimum',
					'spf_gen', 'spf_rule', 'spf_errmsg',
					'dkim_name', 'dkim_data', 'dkim_test', 'dkim_subdomains', 'dkim_strict',
					'dmarc_trailer',
					'descr'
				),
				'easy_search'   : ('name', 'descr'),
				'detail_pane'   : ('netprofile_core.views', 'dpane_simple'),

				'create_wizard' : Wizard(
					Step('name', 'parent', 'enabled', 'public', 'signed', 'descr', title=_('Domain info')),
					Step('soa_refresh', 'soa_retry', 'soa_expire', 'soa_minimum', 'dkim_name', 'dkim_data', title=_('DNS options')),
					title=_('Add new domain')
				)
			}
		}
	)
	id = Column(
		'domainid',
		UInt32(),
		Sequence('domains_def_domainid_seq'),
		Comment('Domain ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	parent_id = Column(
		'parentid',
		UInt32(),
		ForeignKey('domains_def.domainid', name='domains_def_fk_parentid', onupdate='CASCADE'),
		Comment('Parent domain ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Parent'),
			'column_flex'   : 1
		}
	)
	name = Column(
		Unicode(255),
		Comment('Domain name'),
		nullable=False,
		info={
			'header_string' : _('Name')
		}
	)
	enabled = Column(
		NPBoolean(),
		Comment('Is domain enabled?'),
		nullable=False,
		default=True,
		server_default=npbool(True),
		info={
			'header_string' : _('Enabled')
		}
	)
	public = Column(
		NPBoolean(),
		Comment('Is domain visible to outsiders?'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Public')
		}
	)
	signed = Column(
		NPBoolean(),
		Comment('Needs DNSSEC signing?'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Signed')
		}
	)
	soa_refresh = Column(
		UInt32(),
		Comment('SOA refresh field'),
		nullable=False,
		default=3600,
		info={
			'header_string' : _('SOA Refresh')
		}
	)
	soa_retry = Column(
		UInt32(),
		Comment('SOA retry field'),
		nullable=False,
		default=300,
		info={
			'header_string' : _('SOA Retry')
		}
	)
	soa_expire = Column(
		UInt32(),
		Comment('SOA expire field'),
		nullable=False,
		default=1814400,
		info={
			'header_string' : _('SOA Expire')
		}
	)
	soa_minimum = Column(
		UInt32(),
		Comment('SOA minimum field'),
		nullable=False,
		default=3600,
		info={
			'header_string' : _('SOA Minimum')
		}
	)
	serial_date = Column(
		Date(),
		Comment('Domain serial date'),
		nullable=False,
		info={
			'header_string' : _('Serial Date'),
			'secret_value'  : True
		}
	)
	serial_revision = Column(
		'serial_rev',
		UInt8(),
		Comment('Domain serial revision'),
		nullable=False,
		default=1,
		info={
			'header_string' : _('Serial Revision'),
			'secret_value'  : True
		}
	)
	dkim_name = Column(
		ASCIIString(255),
		Comment('DKIM public key name'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('DKIM Name')
		}
	)
	dkim_data = Column(
		ASCIIText(),
		Comment('DKIM public key body'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('DKIM Key')
		}
	)
	dkim_test = Column(
		NPBoolean(),
		Comment('Use DKIM in test mode'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('DKIM Test')
		}
	)
	dkim_subdomains = Column(
		NPBoolean(),
		Comment('Propagate DKIM rules to subdomains'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('DKIM in Subdomains')
		}
	)
	dkim_strict = Column(
		NPBoolean(),
		Comment('Use DKIM strict check and discard'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('DKIM Strict')
		}
	)
	spf_generate = Column(
		'spf_gen',
		NPBoolean(),
		Comment('Generate SPF record'),
		nullable=False,
		default=True,
		server_default=npbool(True),
		info={
			'header_string' : _('Use SPF')
		}
	)
	spf_rule = Column(
		ASCIIText(),
		Comment('Custom SPF rule'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Custom SPF Rule')
		}
	)
	spf_error_message = Column(
		'spf_errmsg',
		UnicodeText(),
		Comment('Custom SPF error explanation string'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('SPF Error')
		}
	)
	dmarc_trailer = Column(
		ASCIIString(255),
		Comment('DMARC record trailer'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('DMARC Trailer')
		}
	)
	description = Column(
		'descr',
		UnicodeText(),
		Comment('Domain description'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Description')
		}
	)

	children = relationship(
		'Domain',
		backref=backref('parent', remote_side=[id])
	)

	@property
	def serial(self):
		if not self.serial_date:
			return str(self.serial_revision % 100)
		return '%s%02d' % (
			self.serial_date.strftime('%Y%m%d'),
			(self.serial_revision % 100)
		)

	def __str__(self):
		if self.parent:
			return '%s.%s' % (
				str(self.name),
				str(self.parent)
			)
		return str(self.name)

	@classmethod
	def resolve(cls, name, domain_aliases=True):
		name = name.strip('.')
		sess = DBSession()
		candidates = [(None, domain_candidates(name), None)]

		while len(candidates) > 0:
			old_candidates = candidates
			candidates = []
			domain_cond = []
			da_cond = []
			for domain, names, suffix in old_candidates:
				if domain is None or isinstance(domain, Domain):
					domain_cond.append(and_(
						Domain.parent_id == (domain.id if domain else None),
						Domain.name.in_(names)
					))
				if not domain_aliases:
					continue
				if domain is None or isinstance(domain, DomainAlias):
					da_cond.append(and_(
						DomainAlias.parent_id == (domain.id if domain else None),
						DomainAlias.name.in_(names)
					))
			if len(domain_cond) > 0:
				for domain in sess.query(Domain).filter(or_(*domain_cond)):
					if suffix is None:
						domain_name = str(domain)
					else:
						domain_name = '.'.join((domain.name, suffix))
					if name == domain_name:
						return domain
					offset = name.find('.' + domain_name)
					if offset > 0:
						left_part = name[:offset]
						candidates.append((domain, domain_candidates(left_part), domain_name))
			if domain_aliases and len(da_cond) > 0:
				for da in sess.query(DomainAlias).filter(or_(*da_cond)):
					if suffix is None:
						domain_name = str(da)
					else:
						domain_name = '.'.join((da.name, suffix))
					if name == domain_name:
						return da.domain
					offset = name.find('.' + domain_name)
					if offset > 0:
						left_part = name[:offset]
						dc = domain_candidates(left_part)
						candidates.extend((
							(da, dc, domain_name),
							(da.domain, dc, domain_name)
						))
Пример #12
0
class Document(Base):
    """
	Document object.
	"""
    __tablename__ = 'docs_def'
    __table_args__ = (Comment('Documents'),
                      Index('docs_def_u_code', 'code', unique=True),
                      Index('docs_def_u_name', 'name', unique=True), {
                          'mysql_engine': 'InnoDB',
                          'mysql_charset': 'utf8',
                          'info': {
                              'cap_menu':
                              'BASE_DOCUMENTS',
                              'cap_read':
                              'DOCUMENTS_LIST',
                              'cap_create':
                              'DOCUMENTS_CREATE',
                              'cap_edit':
                              'DOCUMENTS_EDIT',
                              'cap_delete':
                              'DOCUMENTS_DELETE',
                              'menu_name':
                              _('Documents'),
                              'show_in_menu':
                              'admin',
                              'default_sort': ({
                                  'property': 'name',
                                  'direction': 'ASC'
                              }, ),
                              'grid_view': ('docid', 'code', 'name', 'type'),
                              'grid_hidden': ('docid', ),
                              'form_view': ('code', 'name', 'type', 'external',
                                            'body', 'descr'),
                              'easy_search': ('code', 'name'),
                              'detail_pane':
                              ('netprofile_core.views', 'dpane_wide_content'),
                              'create_wizard':
                              SimpleWizard(title=_('Add new document'))
                          }
                      })
    id = Column('docid',
                UInt32(),
                Sequence('docs_def_docid_seq'),
                Comment('Document ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    code = Column(ASCIIString(48),
                  Comment('Document code'),
                  nullable=False,
                  info={'header_string': _('Code')})
    name = Column(Unicode(255),
                  Comment('Document name'),
                  nullable=False,
                  info={
                      'header_string': _('Name'),
                      'column_flex': 1
                  })
    type = Column(DocumentType.db_type(),
                  Comment('Template type'),
                  nullable=False,
                  default=DocumentType.html_ext,
                  server_default=DocumentType.html_ext,
                  info={'header_string': _('Type')})
    external = Column(NPBoolean(),
                      Comment('Is externally stored?'),
                      nullable=False,
                      default=False,
                      server_default=npbool(False),
                      info={'header_string': _('External')})
    body = Column(
        UnicodeText(),
        Comment('Document body'),
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={
            'header_string': _('Body'),
            'editor_xtype': 'tinymce_field',
            'editor_config': {
                'tinyMCEConfig': {
                    'extended_valid_elements':
                    '+tpl[if|elsif|else|for|foreach|switch|case|default]',
                    'custom_elements':
                    '~tpl',
                    'valid_children':
                    '+*[tpl],+tpl[*],+tbody[tpl],+body[tpl],+table[tpl],+tpl[table|tr|tpl|#text]'
                }
            }
        })
    variables = Column('vars',
                       PickleType(),
                       Comment('List of variable templates'),
                       nullable=True,
                       default=None,
                       server_default=text('NULL'),
                       info={'header_string': _('Variables')})
    description = Column('descr',
                         UnicodeText(),
                         Comment('Description'),
                         nullable=True,
                         default=None,
                         server_default=text('NULL'),
                         info={'header_string': _('Description')})

    bundlemap = relationship('DocumentBundleMapping',
                             backref=backref('document', innerjoin=True),
                             cascade='all, delete-orphan',
                             passive_deletes=True)

    bundles = association_proxy(
        'bundlemap',
        'bundle',
        creator=lambda v: DocumentBundleMapping(bundle=v))

    def __str__(self):
        s = self.name
        if not s:
            s = self.code
        return str(s)
Пример #13
0
class AccessEntityChange(Base):
	"""
	Access entity change log object.
	"""
	__tablename__ = 'entities_access_changes'
	__table_args__ = (
		Comment('Changes to access entities'),
		Index('entities_access_changes_i_entityid', 'entityid'),
		Index('entities_access_changes_i_uid', 'uid'),
		Index('entities_access_changes_i_ts', 'ts'),
		Index('entities_access_changes_i_rateid_old', 'rateid_old'),
		Index('entities_access_changes_i_rateid_new', 'rateid_new'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'     : 'BASE_ENTITIES',
				'cap_read'     : 'ENTITIES_LIST',
				'cap_create'   : '__NOPRIV__',
				'cap_edit'     : '__NOPRIV__',
				'cap_delete'   : '__NOPRIV__',

				'menu_name'    : _('Access Entity Changes'),
				'default_sort' : ({ 'property': 'ts' ,'direction': 'DESC' },),
				'grid_view'    : ('aecid', 'entity', 'user', 'ts'),
				'grid_hidden'  : ('aecid',),
				'form_view'    : (
					'entity', 'user', 'ts',
					'pwchanged',
					'state_old', 'state_new',
					'old_rate', 'new_rate',
					'descr'
				),
				'easy_search'  : ('descr',)
			}
		}
	)
	id = Column(
		'aecid',
		UInt64(),
		Sequence('entities_access_changes_aecid_seq'),
		Comment('Access entity change ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	entity_id = Column(
		'entityid',
		UInt32(),
		Comment('Access entity ID'),
		ForeignKey('entities_access.entityid', name='entities_access_changes_fk_entityid', ondelete='CASCADE', onupdate='CASCADE'),
		nullable=False,
		info={
			'header_string' : _('Entity'),
			'column_flex'   : 2
		}
	)
	user_id = Column(
		'uid',
		UInt32(),
		Comment('User ID'),
		ForeignKey('users.uid', name='entities_access_changes_fk_uid', ondelete='SET NULL', onupdate='CASCADE'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('User'),
			'filter_type'   : 'nplist'
		}
	)
	timestamp = Column(
		'ts',
		TIMESTAMP(),
		Comment('Entity change timestamp'),
		CurrentTimestampDefault(),
		nullable=False,
		info={
			'header_string' : _('Time')
		}
	)
	password_changed = Column(
		'pwchanged',
		NPBoolean(),
		Comment('Password was changed'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Changed Password')
		}
	)
	old_access_state = Column(
		'state_old',
		UInt8(),
		Comment('Old access code'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Old Access Code')
		}
	)
	new_access_state = Column(
		'state_new',
		UInt8(),
		Comment('New access code'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('New Access Code')
		}
	)
	old_rate_id = Column(
		'rateid_old',
		UInt32(),
		Comment('Old rate ID'),
		ForeignKey('rates_def.rateid', name='entities_access_changes_fk_rateid_old', ondelete='SET NULL', onupdate='CASCADE'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Old Rate'),
			'filter_type'   : 'nplist',
			'column_flex'   : 1
		}
	)
	new_rate_id = Column(
		'rateid_new',
		UInt32(),
		Comment('New rate ID'),
		ForeignKey('rates_def.rateid', name='entities_access_changes_fk_rateid_new', ondelete='SET NULL', onupdate='CASCADE'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('New Rate'),
			'filter_type'   : 'nplist',
			'column_flex'   : 1
		}
	)
	description = Column(
		'descr',
		UnicodeText(),
		Comment('Access entity change description'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Description')
		}
	)

	entity = relationship(
		'AccessEntity',
		innerjoin=True,
		backref=backref(
			'changes',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)
	user = relationship(
		'User',
		backref=backref(
			'access_entity_changes',
			passive_deletes=True
		)
	)
	old_rate = relationship(
		'Rate',
		lazy='joined',
		foreign_keys=old_rate_id
		# No backref
	)
	new_rate = relationship(
		'Rate',
		lazy='joined',
		foreign_keys=new_rate_id
		# No backref
	)

	def get_entity_history(self, req):
		loc = req.localizer
		eh = EntityHistory(
			self.entity,
			loc.translate(_('Access entity "%s" changed')) % (str(self.entity)),
			self.timestamp,
			None if (self.user is None) else str(self.user)
		)
		if self.password_changed:
			eh.parts.append(EntityHistoryPart('access:password', loc.translate(_('Password was changed'))))
		if self.old_access_state != self.new_access_state:
			recognized = AccessState.values()
			if self.old_access_state in recognized:
				eh.parts.append(EntityHistoryPart('access:state_old', loc.translate(AccessState.from_string(self.old_access_state).description)))
			if self.new_access_state in recognized:
				eh.parts.append(EntityHistoryPart('access:state_new', loc.translate(AccessState.from_string(self.new_access_state).description)))
		if self.old_rate != self.new_rate:
			if self.old_rate:
				eh.parts.append(EntityHistoryPart('access:rate_old', str(self.old_rate)))
			if self.new_rate:
				eh.parts.append(EntityHistoryPart('access:rate_new', str(self.new_rate)))
		if self.description:
			eh.parts.append(EntityHistoryPart('access:comment', self.description))
		return eh
Пример #14
0
class PerUserRateModifier(Base):
	"""
	Per-user rate modifier definition
	"""
	__tablename__ = 'rates_mods_peruser'
	__table_args__ = (
		Comment('Per-user rate modifiers'),
		Index('rates_mods_peruser_u_mapping', 'rmtid', 'entityid', 'rateid', unique=True),
		Index('rates_mods_peruser_i_entityid', 'entityid'),
		Index('rates_mods_peruser_i_rateid', 'rateid'),
		Index('rates_mods_peruser_i_l_ord', 'l_ord'),
		Trigger('before', 'insert', 't_rates_mods_peruser_bi'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_ENTITIES', # FIXME
				'cap_read'      : 'ENTITIES_LIST', # FIXME
				'cap_create'    : 'ENTITIES_EDIT', # FIXME
				'cap_edit'      : 'ENTITIES_EDIT', # FIXME
				'cap_delete'    : 'ENTITIES_EDIT', # FIXME
				'menu_name'     : _('Rate Modifiers'),
				'default_sort'  : ({ 'property': 'l_ord', 'direction': 'ASC' },),
				'grid_view'     : ('rmid', 'entity', 'rate', 'type', 'enabled', 'l_ord'),
				'grid_hidden'   : ('rmid',),
				'create_wizard' : SimpleWizard(title=_('Add new rate modifier'))
			}
		}
	)
	id = Column(
		'rmid',
		UInt32(),
		Sequence('rates_mods_peruser_rmid_seq'),
		Comment('Rate modifier ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	type_id = Column(
		'rmtid',
		UInt32(),
		Comment('Rate modifier type ID'),
		ForeignKey('rates_mods_types.rmtid', name='rates_mods_peruser_fk_rmtid', ondelete='CASCADE', onupdate='CASCADE'),
		nullable=False,
		info={
			'header_string' : _('Type'),
			'filter_type'   : 'nplist',
			'column_flex'   : 1
		}
	)
	entity_id = Column(
		'entityid',
		UInt32(),
		Comment('Access entity ID'),
		ForeignKey('entities_access.entityid', name='rates_mods_peruser_fk_entityid', ondelete='CASCADE', onupdate='CASCADE'),
		nullable=False,
		info={
			'header_string' : _('Account'),
			'filter_type'   : 'none',
			'column_flex'   : 1
		}
	)
	rate_id = Column(
		'rateid',
		UInt32(),
		Comment('Rate ID'),
		ForeignKey('rates_def.rateid', name='rates_mods_peruser_fk_rateid', ondelete='CASCADE', onupdate='CASCADE'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Rate'),
			'filter_type'   : 'nplist',
			'column_flex'   : 1
		}
	)
	creation_time = Column(
		'ctime',
		TIMESTAMP(),
		Comment('Creation timestamp'),
		nullable=True,
		default=None,
		server_default=FetchedValue(),
		info={
			'header_string' : _('Created'),
			'read_only'     : True
		}
	)
	enabled = Column(
		NPBoolean(),
		Comment('Is modifier enabled?'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Enabled')
		}
	)
	lookup_order = Column(
		'l_ord',
		UInt16(),
		Comment('Lookup order'),
		nullable=False,
		default=1000,
		server_default=text('1000'),
		info={
			'header_string' : _('Lookup Order')
		}
	)

	type = relationship(
		'RateModifierType',
		innerjoin=True,
		backref=backref(
			'per_user_modifiers',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)
	entity = relationship(
		'AccessEntity',
		innerjoin=True,
		backref=backref(
			'rate_modifiers',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)
	rate = relationship(
		'Rate',
		backref=backref(
			'per_user_modifiers',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)
Пример #15
0
class AccessEntity(Entity):
	"""
	Access entity object.
	"""
	DN_ATTR = 'uid'
	__tablename__ = 'entities_access'
	__table_args__ = (
		Comment('Access entities'),
		Index('entities_access_i_stashid', 'stashid'),
		Index('entities_access_i_rateid', 'rateid'),
		Index('entities_access_i_aliasid', 'aliasid'),
		Index('entities_access_i_ipaddrid', 'ipaddrid'),
		Index('entities_access_i_ip6addrid', 'ip6addrid'),
		Index('entities_access_i_nextrateid', 'nextrateid'),
		Trigger('before', 'insert', 't_entities_access_bi'),
		Trigger('before', 'update', 't_entities_access_bu'),
		Trigger('after', 'update', 't_entities_access_au'),
		Trigger('after', 'delete', 't_entities_access_ad'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'     : 'BASE_ENTITIES',
				'cap_read'     : 'ENTITIES_LIST',
				'cap_create'   : 'ENTITIES_CREATE',
				'cap_edit'     : 'ENTITIES_EDIT',
				'cap_delete'   : 'ENTITIES_DELETE',

				'show_in_menu' : 'modules',
				'menu_name'    : _('Access Entities'),
				'menu_parent'  : 'entities',
				'default_sort' : ({ 'property': 'nick' ,'direction': 'ASC' },),
				'grid_view'    : (
					MarkupColumn(
						name='icon',
						header_string=' ',
						help_text=_('Entity icon'),
						column_width=22,
						column_name=_('Icon'),
						column_resizable=False,
						cell_class='np-nopad',
						template='<img class="np-block-img" src="{grid_icon}" />'
					),
					'entityid',
					'nick', 'stash', 'rate'
				),
				'grid_hidden'  : ('entityid',),
				'form_view'    : (
					'nick', 'parent', 'state', 'flags',
					'password', 'stash', 'rate', 'next_rate', #'alias_of',
					'ipv4_address', 'ipv6_address',
					'ut_ingress', 'ut_egress', 'u_sec',
					'qpend', 'access_state',
					'pol_ingress', 'pol_egress',
					'bcheck', 'pcheck',
					'descr'
				),
				'easy_search'  : ('nick',),
				'extra_data'    : ('grid_icon',),
				'detail_pane'  : ('netprofile_core.views', 'dpane_simple'),
				'create_wizard' : Wizard(
					Step(
						'nick', 'parent', 'state', 
						'flags', 'descr',
						id='generic', title=_('Generic entity properties'),
					),
					Step(
						'password', 'stash', 'rate',
						id='ent_access1', title=_('Access entity properties'),
					),
					title=_('Add new access entity'), validator='CreateAccessEntity'
				)
			}
		}
	)
	__mapper_args__ = {
		'polymorphic_identity' : 5
	}
	id = Column(
		'entityid',
		UInt32(),
		ForeignKey('entities_def.entityid', name='entities_access_fk_entityid', ondelete='CASCADE', onupdate='CASCADE'),
		Comment('Entity ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	password = Column(
		Unicode(255),
		Comment('Cleartext password'),
		nullable=False,
		info={
			'header_string' : _('Password'),
			'secret_value'  : True,
			'editor_xtype'  : 'passwordfield'
		}
	)
	stash_id = Column(
		'stashid',
		UInt32(),
		ForeignKey('stashes_def.stashid', name='entities_access_fk_stashid', onupdate='CASCADE'),
		Comment('Used stash ID'),
		nullable=False,
		info={
			'header_string' : _('Stash'),
			'column_flex'   : 3
		}
	)
	rate_id = Column(
		'rateid',
		UInt32(),
		ForeignKey('rates_def.rateid', name='entities_access_fk_rateid', onupdate='CASCADE'),
		Comment('Used rate ID'),
		nullable=False,
		info={
			'header_string' : _('Rate'),
			'filter_type'   : 'nplist',
			'column_flex'   : 2
		}
	)
	alias_of_id = Column(
		'aliasid',
		UInt32(),
		ForeignKey('entities_access.entityid', name='entities_access_fk_aliasid', ondelete='CASCADE', onupdate='CASCADE'),
		Comment('Aliased access entity ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Alias Of'),
			'filter_type'   : 'none'
		}
	)
	next_rate_id = Column(
		'nextrateid',
		UInt32(),
		ForeignKey('rates_def.rateid', name='entities_access_fk_nextrateid', ondelete='SET NULL', onupdate='CASCADE'),
		Comment('Next rate ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Next Rate'),
			'filter_type'   : 'nplist'
		}
	)
	ipv4_address_id = Column(
		'ipaddrid',
		UInt32(),
		ForeignKey('ipaddr_def.ipaddrid', name='entities_access_fk_ipaddrid', ondelete='SET NULL', onupdate='CASCADE'),
		Comment('IPv4 address ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('IPv4 Address')
		}
	)
	ipv6_address_id = Column(
		'ip6addrid',
		UInt64(),
		ForeignKey('ip6addr_def.ip6addrid', name='entities_access_fk_ip6addrid', ondelete='SET NULL', onupdate='CASCADE'),
		Comment('IPv6 address ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('IPv6 Address')
		}
	)
	used_traffic_ingress = Column(
		'ut_ingress',
		Traffic(),
		Comment('Used ingress traffic'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Used Ingress'),
			'read_only'     : True
		}
	)
	used_traffic_egress = Column(
		'ut_egress',
		Traffic(),
		Comment('Used egress traffic'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Used Egress'),
			'read_only'     : True
		}
	)
	used_seconds = Column(
		'u_sec',
		UInt32(),
		Comment('Used seconds'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Used Seconds'),
			'read_only'     : True
		}
	)
	quota_period_end = Column(
		'qpend',
		TIMESTAMP(),
		Comment('End of quota period'),
		nullable=True,
		default=None,
		server_default=FetchedValue(),
		info={
			'header_string' : _('Ends'),
			'read_only'     : True
		}
	)
	access_state = Column(
		'state',
		UInt8(),
		Comment('Access code'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Access Code'),
			'choices'       : AccessState,
			'write_cap'     : 'ENTITIES_ACCOUNTSTATE_EDIT'
		}
	)
	policy_ingress = Column(
		'pol_ingress',
		ASCIIString(255),
		Comment('Ingress traffic policy'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Ingress Policy')
		}
	)
	policy_egress = Column(
		'pol_egress',
		ASCIIString(255),
		Comment('Egress traffic policy'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Egress Policy')
		}
	)
	check_block_state = Column(
		'bcheck',
		NPBoolean(),
		Comment('Check block state'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Check Blocks')
		}
	)
	check_paid_services = Column(
		'pcheck',
		NPBoolean(),
		Comment('Check paid services'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Check Services')
		}
	)

	stash = relationship(
		'Stash',
		innerjoin=True,
		backref='access_entities'
	)
	rate = relationship(
		'Rate',
		innerjoin=True,
		foreign_keys=rate_id,
		backref='access_entities'
	)
	next_rate = relationship(
		'Rate',
		foreign_keys=next_rate_id,
		backref=backref(
			'pending_access_entities',
			passive_deletes=True
		)
	)
	alias_of = relationship(
		'AccessEntity',
		foreign_keys=alias_of_id,
		remote_side=[id],
		backref='aliases'
	)
	ipv4_address = relationship(
		'IPv4Address',
		backref=backref(
			'access_entities',
			passive_deletes=True
		)
	)
	ipv6_address = relationship(
		'IPv6Address',
		backref=backref(
			'access_entities',
			passive_deletes=True
		)
	)
	blocks = relationship(
		'AccessBlock',
		backref=backref('entity', innerjoin=True),
		cascade='all, delete-orphan',
		passive_deletes=True
	)

	def data(self, req):
		ret = super(AccessEntity, self).data

		if self.rate:
			ret['rate'] = str(self.rate)
		if self.next_rate:
			ret['nextrate'] = str(self.next_rate)
		if self.quota_period_end:
			ret['qpend'] = format_datetime(self.quota_period_end, locale=req.current_locale)

		ret['accessstate'] = self.access_state_string(req)
		if self.access_state == AccessState.ok.value:
			ret['accessimg'] = 'ok'
		elif self.access_state == AccessState.block_auto.value:
			ret['accessimg'] = 'stop'
		elif self.access_state == AccessState.block_manual.value:
			ret['accessimg'] = 'manual'
		else:
			ret['accessimg'] = 'misc'

		return ret

	def access_state_string(self, req):
		if self.access_state is None:
			return None
		return req.localizer.translate(AccessState.from_string(self.access_state).description)

	def grid_icon(self, req):
		return req.static_url('netprofile_access:static/img/access.png')
Пример #16
0
class ExternalOperationProvider(Base):
    """
	External Operation Providers object
	"""
    __tablename__ = 'xop_providers'
    __table_args__ = (Comment('External operation providers'),
                      Index('xop_providers_u_name', 'name', unique=True),
                      Index('xop_providers_u_uri', 'uri', unique=True),
                      Index('xop_providers_u_sname', 'sname', unique=True),
                      Index('xop_providers_i_siotypeid', 'siotypeid'), {
                          'mysql_engine': 'InnoDB',
                          'mysql_charset': 'utf8',
                          'info': {
                              'cap_menu':
                              'BASE_XOP',
                              'cap_read':
                              'STASHES_IO',
                              'cap_create':
                              'STASHES_IOTYPES_CREATE',
                              'cap_edit':
                              'STASHES_IOTYPES_EDIT',
                              'cap_delete':
                              'STASHES_IOTYPES_DELETE',
                              'menu_name':
                              _('Providers'),
                              'show_in_menu':
                              'admin',
                              'default_sort': ({
                                  'property': 'name',
                                  'direction': 'ASC'
                              }, ),
                              'grid_view': ('xoppid', 'name', 'sname',
                                            'gwclass', 'enabled'),
                              'grid_hidden': ('xoppid', ),
                              'form_view':
                              ('uri', 'name', 'sname', 'gwclass', 'enabled',
                               'accesslist', 'io_type', 'mindiff', 'maxdiff',
                               'authmethod', 'authopts', 'authuser',
                               'authpass', 'descr'),
                              'create_wizard':
                              SimpleWizard(title=_('Add new provider')),
                              'detail_pane':
                              ('netprofile_core.views', 'dpane_simple')
                          }
                      })
    id = Column('xoppid',
                UInt32(),
                Sequence('xop_providers_xoppid_seq'),
                Comment('External operation provider ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    uri = Column(ASCIIString(64),
                 Comment('URI used in XOP interface'),
                 nullable=True,
                 default=None,
                 server_default=text('NULL'),
                 info={
                     'header_string': _('URI'),
                     'column_flex': 1
                 })
    name = Column(Unicode(255),
                  Comment('External operation provider name'),
                  nullable=False,
                  info={
                      'header_string': _('Name'),
                      'column_flex': 2
                  })
    short_name = Column('sname',
                        Unicode(32),
                        Comment('External operation provider short name'),
                        nullable=True,
                        default=None,
                        server_default=text('NULL'),
                        info={
                            'header_string': _('Short Name'),
                            'column_flex': 1
                        })
    enabled = Column(NPBoolean(),
                     Comment('Is provider enabled?'),
                     nullable=False,
                     default=False,
                     server_default=npbool(False),
                     info={'header_string': _('Enabled')})
    access_list = Column('accesslist',
                         ASCIIString(255),
                         Comment('Allowed access rules'),
                         nullable=True,
                         default=None,
                         server_default=text('NULL'),
                         info={'header_string': _('Access List')})
    gateway_class = Column('gwclass',
                           ASCIIString(64),
                           Comment('Provider gateway class name'),
                           nullable=False,
                           info={'header_string': _('Gateway')})
    io_type_id = Column('siotypeid',
                        UInt32(),
                        Comment('Stash I/O type generated in transaction'),
                        ForeignKey('stashes_io_types.siotypeid',
                                   name='xop_providers_fk_soitypeid',
                                   onupdate='CASCADE'),
                        nullable=True,
                        default=None,
                        server_default=text('NULL'),
                        info={
                            'header_string': _('Operation Type'),
                            'filter_type': 'nplist',
                            'column_flex': 2
                        })
    min_difference = Column('mindiff',
                            Money(),
                            Comment('Minimum operation result'),
                            nullable=True,
                            default=None,
                            server_default=text('NULL'),
                            info={'header_string': _('Minimum Amount')})
    max_difference = Column('maxdiff',
                            Money(),
                            Comment('Maxmum operation result'),
                            nullable=True,
                            default=None,
                            server_default=text('NULL'),
                            info={'header_string': _('Maximum Amount')})
    authentication_method = Column(
        'authmethod',
        ExternalOperationProviderAuthMethod.db_type(),
        Comment('Authentication method'),
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={'header_string': _('Auth Type')})
    authentication_options = Column('authopts',
                                    PickleType(),
                                    Comment('Authentication options'),
                                    nullable=True,
                                    default=None,
                                    server_default=text('NULL'),
                                    info={'header_string': _('Auth Options')})
    authentication_username = Column('authuser',
                                     Unicode(255),
                                     Comment('Authentication user'),
                                     nullable=True,
                                     default=None,
                                     server_default=text('NULL'),
                                     info={'header_string': _('Auth User')})
    authentication_password = Column(
        'authpass',
        Unicode(255),
        Comment('Authentication password'),
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={'header_string': _('Auth Password')})
    description = Column('descr',
                         UnicodeText(),
                         Comment('External operation provider description'),
                         nullable=True,
                         default=None,
                         server_default=text('NULL'),
                         info={'header_string': _('Description')})

    io_type = relationship('StashIOType',
                           backref='external_operation_providers')

    @property
    def access_nets(self):
        if not self.access_list:
            return ()
        nets = []
        for ace in self.access_list.split(';'):
            try:
                nets.append(IPNetwork(ace.strip()))
            except ValueError:
                pass
        return nets

    def __str__(self):
        return '%s' % self.name

    def can_access(self, req):
        if not req.remote_addr:
            return False
        try:
            addr = IPAddress(req.remote_addr)
        except ValueError:
            return False
        nets = self.access_nets
        if len(nets) == 0:
            return True
        for net in nets:
            if addr in net:
                return True
        return False

    def get_gateway(self):
        if not self.gateway_class:
            return None
        itp = list(
            pkg_resources.iter_entry_points('netprofile.xop.gateways',
                                            self.gateway_class))
        if len(itp) == 0:
            return None
        cls = itp[0].load()
        return cls(self)

    def check_operation(self, xop):
        is_ok = True
        if (self.min_difference
                is not None) and (xop.difference < self.min_difference):
            is_ok = False
        if (self.max_difference
                is not None) and (xop.difference > self.max_difference):
            is_ok = False
        if not is_ok:
            xop.state = ExternalOperationState.canceled