Example #1
0
    def creator_id(cls):
        """Declare the creator_id field.

        :param (object) cls
        :return db.Column
        """
        return db.Column(db.Integer, db.ForeignKey('user.id'))
Example #2
0
    def last_modified_by_id(cls):
        """Declare the last_modified_by_id field.

        :param (object) cls
        :return db.Column
        """
        return db.Column(db.Integer, db.ForeignKey('user.id'))
Example #3
0
class Grant(db.Model):
    """Grant model definition.

    The Grant databse table definition for handling OAuth authentication

    :param object db.Model: SQLAlchemy declarative base

    See the official Flask SQLAlchemy documentation for more information
    https://pythonhosted.org/Flask-SQLAlchemy/models.html
    """

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

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

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

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

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

    _scopes = db.Column(db.String)

    def delete(self):
        """Remove the Grant from the database table.

        :param object self: Grant class
        """
        db.session.delete(self)
        db.session.commit()
        return self

    @property
    def scopes(self):
        """Define how scopes are displayed."""
        if self._scopes:
            return self._scopes.split()
        return []
Example #4
0
class Client(db.Model):
    """Client model definition.

    Setup the client database table definition for handling OAuth
    authentication

    :param object db.Model: SQLAlchemy base declarative

    See the official Flask SQLAlchemy documetation for more information
    https://pythonhosted.org/Flask-SQLAlchemy/models.html
    """

    application_name = db.Column(db.Text)

    client_id = db.Column(db.String, primary_key=True)
    client_secret = db.Column(db.String, nullable=False)

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

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

    @property
    def client_type(self):
        """Define the default client type."""
        return 'public'

    @property
    def redirect_uris(self):
        """Define how redirect_uris are displayed."""
        if self._redirect_uris:
            return self._redirect_uris.split()
        return []

    @property
    def default_redirect_uri(self):
        """Select default redirect_uri."""
        return self.redirect_uris[0]

    @property
    def default_scopes(self):
        """Define how scopes are displayed."""
        if self._default_scopes:
            return self._default_scopes.split()
        return []
Example #5
0
class Token(db.Model):
    """Token database definition.

    :param object db.Model: SQLAlchemy declarative base

    See the official Flask SQLAlchemy documentation for more information
    https://pythonhosted.org/Flask-SQLAlchemy/models.html
    """

    __tablename__ = 'token'
    __table_args__ = {'extend_existing': True}

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

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

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

    token_type = db.Column(db.String)

    access_token = db.Column(db.String, unique=True)
    refresh_token = db.Column(db.String, unique=True)

    expires = db.Column(db.DateTime)
    _scopes = db.Column(db.String)

    @property
    def scopes(self):
        """Define how scopes should be displayed."""
        if self._scopes:
            return self._scopes.split()
        return []
Example #6
0
class File(BaseMixin):
    """File schema definition.

    The `File` database table definition

    :param object db.Model: SQLAlchemy declarative base

    See the official Flask SQLAlchemy documentation for more information
    https://pythonhosted.org/Flask-SQLAlchemy/models.html
    """

    __tablename__ = 'file'
    __table_args__ = {'extend_existing': True}

    filepath = db.Column(db.String)
    filename = db.Column(db.String)
    filetype = db.Column(db.String)
    filesize = db.Column(db.String)

    caption = db.Column(db.String)
    caption_link = db.Column(db.String)
Example #7
0
class BaseMixin(db.Model):
    """BaseMixin definition.

    The `BaseMixin` definition used throughout the system to extend
    data models with basic fields.

    @param (object) db.Model
    """

    __abstract__ = True

    """Feature Identifier."""
    id = db.Column(db.Integer, primary_key=True)

    """Feature Statuses."""
    has_been_archived = db.Column(db.Boolean)
    has_been_deleted = db.Column(db.Boolean)

    """Feature Timestamps."""
    created_on = db.Column(db.DateTime)
    modified_on = db.Column(db.DateTime)

    """Define attributes that create relationships for us.

    :see: For more documentation on usage of declarative attributes see the
          official SQLAlchemy documentation at:

          http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/
            api.html#sqlalchemy.ext.declarative.declared_attr
    """

    """Feature User Association."""
    @declared_attr
    def creator_id(cls):
        """Declare the creator_id field.

        :param (object) cls
        :return db.Column
        """
        return db.Column(db.Integer, db.ForeignKey('user.id'))

    @declared_attr
    def created_by(cls):
        """Declare the created_by field.

        :param (object) cls
        :return db.relationship
        """
        return db.relationship('User', **{
            'foreign_keys': cls.creator_id,
            'uselist': False
        })

    """Feature Modified by User Association."""
    @declared_attr
    def last_modified_by_id(cls):
        """Declare the last_modified_by_id field.

        :param (object) cls
        :return db.Column
        """
        return db.Column(db.Integer, db.ForeignKey('user.id'))

    @declared_attr
    def last_modified_by(cls):
        """Declare the last_modified_by field.

        :param (object) cls
        :return db.relationship
        """
        return db.relationship('User', **{
            'foreign_keys': cls.last_modified_by_id,
            'uselist': False
        })

    def get_related_data_values(self, objects_, field_):
        """Get all values for specific relationship.

        :param (object) self
        :param (list) objects_
        :param (string) field_

        :return (list) list_
        """
        list_ = []

        if type(objects_) == InstrumentedList or type(objects_) == "list":
            for object_ in objects_:

                name_ = "Unnamed"

                if object_.__dict__[field_]:
                    name_ = object_.__dict__[field_]

                list_.append({
                    "id": object_.__dict__["id"],
                    "name": name_
                })
        else:
            if hasattr(objects_, '__dict__'):

                name_ = "Unnamed"

                if object_.__dict__[field_]:
                    name_ = object_.__dict__[field_]

                list_.append({
                    "id": objects_.__dict__["id"],
                    "name": name_
                })

        return list_

    def related_data(self):
        """Get data relationships for specific data model.

        :param (object) self

        :return (list) list_
        """
        list_ = []

        for relationship_ in self.__def__["relationships"]:

            if hasattr(self, relationship_.get('name')):

                field_ = relationship_.get('label_field_name')
                values_ = self.__dict__[relationship_.get('name')]
                items_ = self.get_related_data_values(values_, field_)

                r_ = {
                    "type": relationship_.get('machine_name'),
                    "label": relationship_.get('class_name'),
                    "count": len(items_),
                    "list": items_
                }

                list_.append(r_)

        return list_
Example #8
0
class Role(db.Model, RoleMixin):
    """Role schema definition.

    The `Role` database table definition used throughout the system to grant
    permissions to specific users

    @param (object) db.Model
    @param (object) RoleMixin
    """

    """Name of the database table that holds `role` data.

    @see http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/
         declarative.html#table-configuration
    """
    __tablename__ = 'role'
    __table_args__ = {
      'extend_existing': True
    }

    __def__ = {
        "access": "private",
        "fields": {
            "name": {
                "field_label": "Role Name",
                "field_help": "",
                "field_order": 1,
                "component": {
                    "name": "textfield",
                    "options": {},
                    "group": "Role Information"
                },
                "is_editable": True,
                "is_required": True,
            },
            "description": {
                "field_label": "Role Description",
                "field_help": "",
                "field_order": 2,
                "component": {
                    "name": "textfield",
                    "options": {},
                    "group": "Role Information"
                },
                "is_editable": True,
                "is_required": True,
            },
        }
    }

    """Fields within the data model."""
    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.Text, unique=True)
    description = db.Column(db.Text)

    def __init__(self, name, description=None):
        """Role schema definition.

        @param (object) self
        @param (string) name
        @param (string) description
        """
        self.name = name
        self.description = description

    def __repr__(self):
        """How the Role schema is representation when inspected."""
        return '<Role %r>' % (self.name)
Example #9
0
class User(db.Model, UserMixin):
    """User schema definition.

    The `User` database table definition used throughout the system to
    identify, authenticate, and manage system users

    @param (object) db.Model
    @param (object) UserMixin
    """
    """Database table details.

    See the official SQLAlchemy documetation for more information
    http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/declarative.html\
        #table-configuration
    """
    __tablename__ = 'user'
    __table_args__ = {'extend_existing': True}

    __def__ = {
        "access": "private",
        "fields": {
            "email": {
                "field_label": "Email Address",
                "field_help": "A valid email address (not public)",
                "field_order": 1,
                "component": {
                    "name": "textfield",
                    "options": {
                        "max-length": 0,
                        "allowed_characters": "ascii"
                    },
                    "group": "User Information"
                },
                "is_editable": True,
                "is_required": True,
            },
            "password": {
                "field_label": "Password",
                "field_help": "",
                "field_order": 2,
                "component": {
                    "name": "password",
                    "options": {},
                    "group": "User Information"
                },
                "is_editable": True,
                "is_required": True,
            },
            "active": {
                "field_label": "Active",
                "field_help": "",
                "field_order": 3,
                "component": {
                    "name": "boolean",
                    "options": {},
                    "group": "User Information"
                },
                "is_editable": True,
                "is_required": True,
            },
            "first_name": {
                "field_label": "First Name",
                "field_help": "",
                "field_order": 1,
                "component": {
                    "name": "textfield",
                    "options": {},
                    "group": "User Profile"
                },
                "is_editable": True,
                "is_required": False,
            },
            "last_name": {
                "field_label": "Last Name",
                "field_help": "",
                "field_order": 2,
                "component": {
                    "name": "textfield",
                    "options": {},
                    "group": "User Profile"
                },
                "is_editable": True,
                "is_required": False,
            },
            "background": {
                "field_label": "Background",
                "field_help": "",
                "field_order": 3,
                "component": {
                    "name": "textarea",
                    "options": {},
                    "group": "User Profile"
                },
                "is_editable": True,
                "is_required": False,
            },
            "picture": {
                "field_label": "Profile Picture",
                "field_help": "",
                "field_order": 4,
                "component": {
                    "name": "image",
                    "options": {
                        "allowed_extensions": [
                            "JPG", "jpg", "JPEG", "jpeg", "GIF", "gif", "PNG",
                            "png"
                        ],
                        "multiple":
                        False
                    },
                    "group": "User Profile"
                },
                "is_editable": True,
                "is_required": False,
            },
            "title": {
                "field_label": "Title",
                "field_help": "",
                "field_order": 1,
                "component": {
                    "name": "textfield",
                    "options": {},
                    "group": "Job Information"
                },
                "is_editable": True,
                "is_required": False,
            },
            "organization_name": {
                "field_label": "Organization Name",
                "field_help": "",
                "field_order": 2,
                "component": {
                    "name": "textfield",
                    "options": {},
                    "group": "Job Information"
                },
                "is_editable": True,
                "is_required": False,
            },
            "roles": {
                "field_label": "Roles",
                "field_help": "",
                "field_order": 1,
                "component": {
                    "name": "relationship",
                    "options": {},
                    "group": "Roles"
                },
                "is_editable": True,
                "is_required": True,
            },
            "confirmed_at": {
                "field_label": "Confirmed At",
                "field_help": "",
                "field_order": 1,
                "component": {
                    "name": "datetime",
                    "options": {},
                    "group": "Account History"
                },
                "is_editable": False,
                "is_required": True,
            },
            "last_login_at": {
                "field_label": "Last Login At",
                "field_help": "",
                "field_order": 2,
                "component": {
                    "name": "datetime",
                    "options": {},
                    "group": "Account History"
                },
                "is_editable": False,
                "is_required": True,
            },
            "current_login_at": {
                "field_label": "Current Login At",
                "field_help": "",
                "field_order": 4,
                "component": {
                    "name": "datetime",
                    "options": {},
                    "group": "Account History"
                },
                "is_editable": False,
                "is_required": True,
            },
            "last_login_ip": {
                "field_label": "Last Login IP",
                "field_help": "",
                "field_order": 3,
                "component": {
                    "name": "textfield",
                    "options": {},
                    "group": "Account History"
                },
                "is_editable": False,
                "is_required": True,
            },
            "current_login_ip": {
                "field_label": "Current Login IP",
                "field_help": "",
                "field_order": 5,
                "component": {
                    "name": "textfield",
                    "options": {},
                    "group": "Account History"
                },
                "is_editable": False,
                "is_required": True,
            },
            "login_count": {
                "field_label": "Login Count",
                "field_help": "",
                "field_order": 6,
                "component": {
                    "name": "number",
                    "options": {},
                    "group": "Account History"
                },
                "is_editable": False,
                "is_required": True,
            }
        }
    }

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.Text, unique=True)
    password = db.Column(db.Text)
    active = db.Column(db.Boolean)

    confirmed_at = db.Column(db.DateTime)
    last_login_at = db.Column(db.DateTime)
    current_login_at = db.Column(db.DateTime)
    last_login_ip = db.Column(db.Text)
    current_login_ip = db.Column(db.Text)
    login_count = db.Column(db.Integer)

    roles = db.relationship(
        'Role', **{
            'secondary': user_roles,
            'backref': db.backref('users')
        })

    def __init__(self,
                 email,
                 password=None,
                 active=False,
                 background=None,
                 picture=None,
                 title=None,
                 organization_name=None,
                 confirmed_at=None,
                 last_login_at=None,
                 current_login_at=None,
                 last_login_ip=None,
                 current_login_ip=None,
                 login_count=0,
                 roles=None,
                 organizations=None):
        """Role schema definition constructor.

        @param (object) self
        @param (string) email
        @param (string) password
        @param (boolean) active
        @param (string) first_name
        @param (string) last_name
        @param (string) bio
        @param (string) picture
        @param (string) title
        @param (string) organization_name
        @param (datetime) confirmed_at
        @param (datetime) last_login_at
        @param (datetime) current_login_at
        @param (string) last_login_ip
        @param (string) current_login_ip
        @param (integer) login_count
        @param (array) roles
        """
        self.email = email
        self.password = password
        self.active = active
        self.background = background
        self.picture = picture
        self.title = title
        self.organization_name = organization_name
        self.confirmed_at = confirmed_at
        self.last_login_at = last_login_at
        self.current_login_at = current_login_at
        self.last_login_ip = last_login_ip
        self.current_login_ip = current_login_ip
        self.login_count = login_count
        self.roles = roles if roles else []
        self.organizations = organizations if organizations else []

    def set_password(self, password):
        """Generate a password hash based on user input.

        Set the user password using the pbkdf2:sha1 method and a
        salt_length of 128

        @param (object) self
        @param (string) password
            The password to set in the database
        """
        self.password = generate_password_hash(password,
                                               method='pbkdf2:sha1',
                                               salt_length=128)

    def check_password(self, password):
        """Verify password is correct by hashing and comparing hashes.

        Check to see if the password entered by the user matches the password
        saved in the database associated with the acting user

        @param (object) self
        @param (string) password
        The password to check against the database
        @return (bool)
            The boolean of whether or not the passwords match
        """
        return check_password_hash(self.password, password)

    def user_get(self):
        """Get the SQLAlchemy User object for the current_user.

        @param (object) self
        @return (object) user_
            The object of the current user, not to be confused with
            current_user
        """
        return {
            'id': self.id,
            # 'first_name': self.first_name,
            # 'last_name': self.last_name,
            # 'picture': self.picture,
        }
Example #10
0
from rith.schema.role import Role
"""User Roles schema definition.

These tables are necessary to perform our many to many relationships

@see https://pythonhosted.org/Flask-SQLAlchemy/models.html\
      #many-to-many-relationships
   This documentation is specific to Flask using sqlalchemy

@see http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html\
      #relationships-many-to-many
   This documentation covers SQLAlchemy
"""
user_roles = db.Table('user_roles',
                      db.Column('user_id', db.Integer,
                                db.ForeignKey('user.id')),
                      db.Column('role_id', db.Integer,
                                db.ForeignKey('role.id')),
                      extend_existing=True)


class User(db.Model, UserMixin):
    """User schema definition.

    The `User` database table definition used throughout the system to
    identify, authenticate, and manage system users

    @param (object) db.Model
    @param (object) UserMixin
    """
    """Database table details.
Example #11
0
class Image(BaseMixin):
    """Image schema definition.

    The `Image` database table definition

    :param object db.Model: SQLAlchemy declarative base

    See the official Flask SQLAlchemy documentation for more information
    https://pythonhosted.org/Flask-SQLAlchemy/models.html
    """

    __tablename__ = 'image'
    __table_args__ = {'extend_existing': True}

    original = db.Column(db.String)

    square_retina = db.Column(db.String)
    square = db.Column(db.String)

    thumbnail_retina = db.Column(db.String)
    thumbnail = db.Column(db.String)

    icon_retina = db.Column(db.String)
    icon = db.Column(db.String)

    filename = db.Column(db.String)
    filetype = db.Column(db.String)
    filesize = db.Column(db.String)

    caption = db.Column(db.String)
    caption_link = db.Column(db.String)