示例#1
0
def upgrade():
    # it possible that this script is being called on new database
    # in this case we should not do anything
    insp = reflection.Inspector.from_engine(ptah.get_base().metadata.bind)

    if 'annotations' in [r['name'] for r in insp.get_columns('ptah_nodes')]:
        return

    # ptah_nodes
    op.add_column('ptah_nodes',
                  sa.Column('annotations', ptah.JsonDictType(), default={}))

    # ptah_content
    op.add_column('ptah_content', sa.Column('lang',
                                            sa.String(12),
                                            default='en'))

    op.create_index('ix_ptah_content_path', 'ptah_content', ('path', ))

    # sqlite doesnt support column drop
    impl = context.get_impl()

    if impl.__dialect__ != 'sqlite':
        op.drop_column('ptah_content', 'view')
        op.drop_column('ptah_content', 'creators')
        op.drop_column('ptah_content', 'subjects')
        op.drop_column('ptah_content', 'publisher')
        op.drop_column('ptah_content', 'contributors')

    op.drop_table('test_sqla_table')
示例#2
0
class Storage(ptah.get_base()):

    __tablename__ = 'ptahcrowd_auth_storage'

    access_token = sqla.Column(sqla.String(255), primary_key=True)
    domain = sqla.Column(sqla.String(255), default='')

    uri = sqla.Column(sqla.String(255), index=True)

    uid = sqla.Column(sqla.String(128), default='', unique=True)
    name = sqla.Column(sqla.String(255), default='')
    email = sqla.Column(sqla.String(128), default='')
    verified = sqla.Column(sqla.Boolean(), default=False)

    profile = sqla.Column(ptah.JsonDictType())
    expires = sqla.Column(sqla.DateTime())

    @classmethod
    def get_by_token(cls, access_token):
        return ptah.get_session().query(cls).filter(
            sqla.and_(cls.access_token == access_token)).first()

    @classmethod
    def create(cls, access_token, domain,
               uid='', name='', email='',
               verified=False, profile=None, expires=None):

        params = {'access_token': access_token,
                  'domain': domain,
                  'uid': uid,
                  'name': name,
                  'email': email.lower(),
                  'verified': verified,
                  'profile': profile}

        session = ptah.get_session()

        # reuse old authorization
        q = session.query(cls).filter(cls.uid == uid)
        old = q.first()
        if old is not None:
            params['uri'] = old.uri
            q.delete()

        entry = cls(**params)
        session.add(entry)
        return entry

    @classmethod
    def delete(cls, key):
        ptah.get_session().query(cls).filter(cls.key == key).delete()
        return True

    @classmethod
    def purge_expired(cls):
        ptah.get_session().query(cls)\
            .filter(cls.expires < datetime.utcnow()).delete()
        return True
示例#3
0
class User(ptah.get_base()):
    """Default user
    
    ``name``: User name.

    ``email``: User email.

    ``properties``: User properties.
    """

    __tablename__ = 'users'

    id = sqla.Column(sqla.Integer, primary_key=True)
    token = sqla.Column(sqla.String(255), index=True)
    source = sqla.Column(sqla.String(18))
    name = sqla.Column(sqla.Unicode(255))
    email = sqla.Column(sqla.Unicode(255), unique=True)
    joined = sqla.Column(sqla.DateTime())
    properties = sqla.Column(ptah.JsonDictType(), default={})

    def __init__(self, **kw):
        self.joined = datetime.utcnow()
        self.properties = {}

        super(User, self).__init__(**kw)

    def __str__(self):
        return self.name

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

    def __repr__(self):
        return '%s<%s:%s>' % (self.__class__.__name__, self.name, self.__uri__)

    _sql_get_id = ptah.QueryFreezer(
        lambda: ptah.get_session().query(User)\
            .filter(User.id==sqla.sql.bindparam('id')))

    @classmethod
    def get_byid(cls, id):
        return cls._sql_get_id.first(id=id)

    _sql_get_token = ptah.QueryFreezer(
        lambda: ptah.get_session().query(User)\
            .filter(User.token==sqla.sql.bindparam('token')))

    @classmethod
    def get_bytoken(cls, token):
        return cls._sql_get_token.first(token=token)
示例#4
0
        class Test(ptah.get_base()):
            __tablename__ = 'test14'

            id = sqla.Column('id', sqla.Integer, primary_key=True)
            data = sqla.Column(ptah.JsonDictType())
示例#5
0
class Node(Base):
    """ Base class for persistent objects.

    .. attribute:: __uri__

       Unique object id. **Required**

    .. attribute:: __type__

       Type information object :py:class:`ptah.cms.TypeInformation`

    .. attribute:: __parent__

       Parent of node. Ptah doesn't load `__parent__` automatically.
       To load node parents use :py:func:`ptah.cms.load_parents` function.

    .. attribute:: __owner__

       URI of owner principal. It possible to load principal object
       by using :py:func:`ptah.resolve` function.

    .. attribute:: __local_roles__

       :py:class:`ptah.JsonDictType` which contains a principal uri as a
       key and a sequence of role's granted to principal for Node.

    .. attribute:: __acls__

       a :py:class:`ptah.JsonListType` of :py:class:`ptah.ACL` strings
       registered with security machinery.

    .. attribute:: __uri_factory__

       function which will return value for __uri__.  the uri must be
       resolvable by using :py:func:`ptah.resolve` function.

    """

    __tablename__ = 'ptah_nodes'

    __id__ = sqla.Column('id', sqla.Integer, primary_key=True)
    __type_id__ = sqla.Column('type', sqla.String, info={'uri': True})
    __type__ = None

    __uri__ = sqla.Column('uri',
                          sqla.String,
                          unique=True,
                          nullable=False,
                          info={'uri': True})
    __parent_uri__ = sqla.Column('parent',
                                 sqla.String,
                                 sqla.ForeignKey(__uri__),
                                 info={'uri': True})

    __owner__ = sqla.Column('owner',
                            sqla.String,
                            default=text_type(''),
                            info={'uri': True})
    __local_roles__ = sqla.Column('roles', ptah.JsonDictType(), default={})
    __acls__ = sqla.Column('acls', ptah.JsonListType(), default=[])

    __children__ = sqla.orm.relationship('Node',
                                         backref=sqla.orm.backref(
                                             '__parent_ref__',
                                             remote_side=[__uri__]))

    __mapper_args__ = {'polymorphic_on': __type_id__}

    __parent__ = None
    __uri_factory__ = None

    __acl__ = ptah.ACLsProperty()

    def __init__(self, **kw):
        self.__owners__ = []
        self.__local_roles__ = {}
        self.__permissions__ = []

        for attr, value in kw.items():
            setattr(self, attr, value)

        if '__parent__' in kw and kw['__parent__'] is not None:
            self.__parent_uri__ = kw['__parent__'].__uri__

        try:
            self.__uri__ = self.__uri_factory__()
        except TypeError:
            raise TypeError('Subclass of Node has to override __uri_factory__')

    @action(permission=View)
    def info(self):
        info = OrderedDict((
            ('__type__', self.__type_id__),
            ('__content__', False),
            ('__uri__', self.__uri__),
            ('__parents__', [p.__uri__ for p in load_parents(self)]),
        ))

        return info
示例#6
0
class CrowdUser(ptah.get_base()):
    """Default crowd user

    ``fullname``: User full name.

    ``username``: User name.

    ``email``: User email.

    ``password``: User password.

    ``properties``: User properties.

    """

    __tablename__ = 'ptahcrowd_users'

    id = sqla.Column(sqla.Integer, primary_key=True)
    fullname = sqla.Column(sqla.Unicode(255), info={
        'title': const.FULLNAME_TITLE,
        'description': const.FULLNAME_DESCR,
        'required': False
    })
    username = sqla.Column(sqla.Unicode(255), unique=True, info={
        'title': const.USERNAME_TITLE,
        'description': const.USERNAME_DESCR,
        'preparer': lower,
        'validator': checkUsernameValidator,
    })
    email = sqla.Column(sqla.Unicode(255), unique=True, info={
        'title': const.EMAIL_TITLE,
        'description': const.EMAIL_DESCR,
        'preparer': lower,
        'validator': ptah.form.All(ptah.form.Email(), checkEmailValidator),
    })
    joined = sqla.Column(sqla.DateTime(), info={'skip': True})
    password = sqla.Column(sqla.Unicode(255), info={
        'title': const.PASSWORD_TITLE,
        'description': const.PASSWORD_DESCR,
        'validator': passwordValidator,
        'field_type': 'password'
    })
    validated = sqla.Column(sqla.Boolean(), default=False, info={
        'title': _('Validated'),
        'default': False,
    })
    suspended = sqla.Column(sqla.Boolean(), default=False, info={
        'title': _('Suspended'),
        'default': False,
    })
    properties = sqla.Column(ptah.JsonDictType(), default={})

    def __init__(self, **kw):
        self.joined = datetime.utcnow()
        self.properties = {}

        super(CrowdUser, self).__init__(**kw)

    def __str__(self):
        return self.name

    @property
    def __name__(self):
        return str(self.id)

    @property
    def name(self):
        return self.fullname or self.username

    def __repr__(self):
        return '%s<%s:%s:%s>'%(self.__class__.__name__, self.name,
            self.__type__.name, self.id)

    _sql_get_id = ptah.QueryFreezer(
        lambda: ptah.get_session().query(CrowdUser)\
            .filter(CrowdUser.id==sqla.sql.bindparam('id')))

    @classmethod
    def get_byid(cls, id):
        return cls._sql_get_id.first(id=id)