Ejemplo n.º 1
0
class Group(db.Model):
    """
    docstring
    """
    __tablename__ = 'groups'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    created = db.Column(db.DateTime, default=datetime.utcnow)
    created_by = db.Column(db.Integer, db.ForeignKey('users.id'))

    creator = db.relationship('User', backref='groups')

    def __init__(self, name, creator):
        self.name = name
        self.creator = creator

    # persist object to database
    def persist(self):
        db.session.add(self)
        db.session.commit()

    # delete from database
    def remove(self):
        db.session.delete(self)
        db.session.commit()

    def __repr__(self):
        return '<Group %r>' % self.name
Ejemplo n.º 2
0
class Membership(db.Model):
    """ docstring """

    __tablename__ = 'memberships'

    id = db.Column(db.Integer, primary_key=True)
    uid = db.Column(db.Integer, db.ForeignKey('users.id'))
    gid = db.Column(db.Integer, db.ForeignKey('groups.id'))
    created = db.Column(db.DateTime, default=datetime.utcnow)

    user = db.relationship('User', backref='memberships')
    group = db.relationship('Group', backref='memberships')

    def __init__(self, user, group):
        self.user = user
        self.group = group

    # persist in the database
    def persist(self):
        db.session.add(self)
        db.session.commit()

    # delete from a database
    def remove(self):
        db.session.delete(self)
        db.session.commit()

    def __repr__(self):
        return '<Membership %d>' % self.uid
Ejemplo n.º 3
0
class Token(db.Model):
    """
    The final token to be used by a client
    """

    __tablename__ = 'tokens'

    id = db.Column(db.Integer, primary_key=True)

    client_id = db.Column(db.String(40),
                          db.ForeignKey('clients.id'),
                          nullable=False)
    client = db.relationship('Client')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    user = db.relationship('User')

    token_type = db.Column(db.String(40))

    access_token = db.Column(db.String(255), unique=True)
    refresh_token = db.Column(db.String(255), unique=True)
    expires = db.Column(db.DateTime)
    _scopes = db.Column(db.Text)

    @property
    def scopes(self):
        if self._scopes:
            return self._scopes.split()
        return []
Ejemplo n.º 4
0
class AuthorizedClients(db.Model):
    """
     The clients authorized by users
    """

    __tablename__ = 'authorized_clients'

    id = db.Column(db.Integer, primary_key=True)

    client_id = db.Column(db.String(40),
                          db.ForeignKey('clients.id'),
                          nullable=False)
    client = db.relationship('Client')

    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    user = db.relationship('User')

    def persist(self):
        db.session.add(self)
        db.session.commit()

    @staticmethod
    def revoke(**kwargs):
        user = kwargs.get('user')
        client = kwargs.get('client')
        authorization = AuthorizedClients.query.filter_by(
            user_id=user.id, client_id=client.client_id).first()
        current_app.logger.debug('authorization to be revoked-- %s',
                                 authorization)
        db.session.delete(authorization)
        db.session.commit()

    @staticmethod
    def getByUser(user):
        authorized_clients = [
            row.client for row in AuthorizedClients.query.filter_by(
                user_id=user.id).all()
        ]

        current_app.logger.debug('authorized clients %s', authorized_clients)

        return authorized_clients
Ejemplo n.º 5
0
class Grant(db.Model):
    """
    A grant token is created in the authorization flow, and will be
    destroyed when the authorization finished. In this case, it would be better
    to store the data in a cache, which would benefit a better performance.
    """
    #TODO: this would perform better if its only in the cache. and not in a db.

    __tablename__ = 'grants'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer,
                        db.ForeignKey('users.id', ondelete='CASCADE'))
    user = db.relationship('User')

    client_id = db.Column(db.String(40),
                          db.ForeignKey('clients.id'),
                          nullable=False)
    client = db.relationship('Client')

    code = db.Column(db.String(255), index=True, nullable=False)

    redirect_uri = db.Column(db.String(255))
    expires = db.Column(db.DateTime)

    _scopes = db.Column(db.Text)

    @property
    def scopes(self):
        if self._scopes:
            return self._scopes.split()
        return []

    def delete(self):
        db.session.delete(self)
        db.session.commit()
Ejemplo n.º 6
0
class Client(db.Model):
    """
    The third-party application registering with the platform
    """

    __tablename__ = 'clients'

    id = db.Column(db.String(40), primary_key=True)

    client_secret = db.Column(db.String(55), nullable=False)

    name = db.Column(db.String(60), nullable=False)

    description = db.Column(db.String(400))

    # creator of the client application
    user_id = db.Column(db.ForeignKey('users.id'))
    creator = db.relationship('User')

    _is_private = db.Column(db.Boolean)

    _host_url = db.Column(db.String(255))

    _redirect_uris = db.Column(db.Text)
    _default_scopes = db.Column(db.Text)

    @property
    def client_id(self):
        return self.id

    @property
    def client_type(self):
        if self._is_private:
            return 'private'
        return 'public'

    @property
    def host_url(self):
        return self._host_url

    @property
    def redirect_uris(self):
        if self._redirect_uris:
            return self._redirect_uris.split()
        return []

    @property
    def default_redirect_uri(self):
        return self.redirect_uris[0]

    @property
    def default_scopes(self):
        if self._default_scopes:
            return self._default_scopes.split()
        return []

    def __repr__(self):
        return '<Client: %s :: ID: %s>' % (self.name, self.id)

    def __str__(self):
        return '<Client: %s :: ID: %s>' % (self.name, self.id)

    # create and persist the client to the database
    def persist(self):
        db.session.add(self)
        db.session.commit()

    @staticmethod
    def getClientsByCreator(user_id):
        clients = Client.query.filter_by(user_id=user_id)
        return [each for each in clients]
Ejemplo n.º 7
0
class Sweet(db.Model):
    """ customary docstring """

    __tablename__ = 'sweets'

    id = db.Column(db.Integer, primary_key=True)

    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    who = db.relationship('User')

    context_id = db.Column(db.Integer, db.ForeignKey('contexts.id'))
    what = db.relationship('Context')

    where = db.Column(db.UnicodeText, nullable=False)

    how = db.Column(JSONType)

    created = db.Column(db.DateTime, default=datetime.utcnow)

    def __init__(self, who, what, where, how):
        current_app.logger.info('initing sweet..')
        self.who = who
        self.what = what
        self.where = urlnorm(where)
        self.how = how

    def __repr__(self):
        return u'[Sweet Object: <%s : @%s: #%s : %s>]' % (
            self.id, self.who, self.what, self.where)

    def __str__(self):
        return u'[Sweet Object: <%s : @%s: #%s : %s>]' % (
            self.id, self.who, self.what, self.where)

    # Update the sweet - only 'how' and 'where' fields can be updated
    def update(self, **kwargs):
        if kwargs.get('how'):
            self.how = kwargs.get('how')
            self.persist()
        if kwargs.get('where'):
            self.where = kwargs.get('where')
            self.persist()

        return None

    # create multiple sweets from a list of JSON
    @staticmethod
    def createSweets(who, payload):
        # the payload has to be a list; a list of swts
        for each in payload:
            if 'what' not in each and 'where' not in each and 'how' not in\
                    each:

                raise InvalidPayload('Invalid payload %s \n while creating\
                                     mutiple sweets' % (each))
                return None

        # all ok. create swts from the list now
        swts = []
        for each in payload:

            what = Context.getByName(each['what'])

            if what is None:
                raise ContextDoNotExist('Context %s do not exist!' %
                                        (each['what']))

            current_app.logger.debug(
                'SWEET PAYLOAD\n---\n%s\n%s\n%s\n%s\n----', who, what,
                each['where'], each['how'])

            new_sweet = Sweet(who, what, each['where'], each['how'])

            new_sweet.persist()
            current_app.logger.debug('New Sweet %s', new_sweet)
            swts.append(new_sweet)

        return swts

    # get Sweets for frontend
    @staticmethod
    def getFrontendSwts(page_num):
        # get <SWTS_PER_PAGE> no. of swts, with an offset of <page_num>
        return Sweet.query.order_by(Sweet.created.desc()).paginate(
            page_num, SWTS_PER_PAGE, False)

    # get all sweets authored by a particular user
    @staticmethod
    def getByCreator(user):
        return Sweet.query.filter_by(who=user).\
            order_by(Sweet.created.desc()).all()

    # allow to query all sweets based on "who", "what" and "where" params
    @staticmethod
    def queryByAll(params):
        if params.get('who'):
            params['who'] = User.getByName(params['who'])
        if params.get('what'):
            params['what'] = Context.getByName(params['what'])

        return Sweet.query.filter_by(**params).all()

    # return a dictionary of data members
    def to_dict(self):

        return {
            'id': self.id,
            'who': self.who.username,
            'user_id': self.user_id,
            'what': self.what.name,
            'context_id': self.context_id,
            'where': self.where,
            'how': self.how,
            #'created': self.created.isoformat()
            'created': self.created.strftime('%a, %d %b %Y, %I:%M %p UTC')
        }

    # create and persist the sweet to the database
    def persist(self):

        current_app.logger.debug('Commiting sweet %s to db', self)
        db.session.add(self)
        db.session.commit()
Ejemplo n.º 8
0
class User(db.Model):
    """ docstring """

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80))
    email = db.Column(db.String(120), unique=True)
    created = db.Column(db.DateTime, default=datetime.utcnow)
    last_active = db.Column(db.DateTime, default=datetime.utcnow)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def update(self, **kwargs):
        if kwargs.get('username'):
            self.username = kwargs.get('username')
        if kwargs.get('last_active'):
            current_app.logger.debug('Updated last_active timestamp %s for %s',
                                     kwargs.get('last_active'), self)
            self.last_active = kwargs.get('last_active')

        self.persist()

    # persist current object in the database
    def persist(self):
        db.session.add(self)
        db.session.commit()

    # delete from database
    def remove(self):
        db.session.delete(self)
        db.session.commit()

    @staticmethod
    def getCurrentUser():
        if 'email' in session:
            user = User.query.filter_by(email=session['email']).first()
            user.update(last_active=datetime.utcnow())
            return user
        return None

    @staticmethod
    def getByName(username):
        return User.query.filter_by(username=username).first()

    def to_dict(self):
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            #'created': self.created.isoformat(),
            'created': self.created.strftime('%a, %d %b %Y, %I:%M %p UTC'),
            #'last_active': self.last_active.isoformat()
            'last_active':
            self.last_active.strftime('%a, %d %b %Y, %I:%M %p UTC')
        }

    def __repr__(self):
        return '<User:: %r %r>' % (self.username, self.email)