# Path: app/main.py

# 
# Path: app/crud_mixin.py
# class CRUDMixin(object):
#     """ Helper class flask-sqlalchemy entities """
#     __table_args__ = {'extend_existing': True}
# 
#     id = db.Column(db.Integer, primary_key=True)
# 
#     @classmethod
#     def get_by_id(cls, id):
#         if any(
#             (isinstance(id, basestring) and id.isdigit(),
#              isinstance(id, (int, float))),
#         ):
#             return cls.query.get(int(id))
#         return None
# 
# 
#     @classmethod
#     def create(cls, **kwargs):
#         """ Helper for session.add() + session.commit() """
#         instance = cls(**kwargs)
#         return instance.save()
# 
# 
#     def update(self, commit=True, **kwargs):
#         for attr, value in kwargs.iteritems():
#             setattr(self, attr, value)
#         return commit and self.save() or self
# 
# 
#     def save(self, commit=True):
#         db.session.add(self)
#         if commit:
#             db.session.commit()
#         return self
# 
# 
#     def delete(self, commit=True):
#         db.session.delete(self)
#         return commit and db.session.commit()
# 
# Path: app/models/role_entity.py
# class RoleEntity(db.Model, CRUDMixin):  # RoleMixin
# 
#     """ Stores possible user roles """
#     __tablename__ = 'Role'
# 
#     id = db.Column("rolID", db.Integer, primary_key=True)
#     name = db.Column("rolName", db.String(255), nullable=False, unique=True)
#     description = db.Column("rolDescription", db.String(255), nullable=False)
# 
#     def __repr__(self):
#         """ implements friendly representation """
#         return "<RoleEntity (rolID: {0.id}, rolName: {0.name})>" \
#             .format(self)
# 
# Path: app/models/user_role_entity.py
# class UserRoleEntity(db.Model, CRUDMixin):
#     """ Stores the user-role mapping """
#     __tablename__ = 'UserRole'
# 
#     id = db.Column("urID", db.Integer, primary_key=True)
#     user_id = db.Column("usrID", db.Integer, db.ForeignKey('User.usrID',
#                         ondelete='CASCADE'), nullable=False)
#     role_id = db.Column("rolID", db.Integer, db.ForeignKey('Role.rolID',
#                         ondelete='CASCADE'), nullable=False)
#     added_at = db.Column('urAddedAt', db.DateTime(), nullable=False,
#                          server_default='0000-00-00 00:00:00')
# 
#     role = db.relationship('RoleEntity', uselist=False)
#     user = db.relationship('UserEntity', uselist=False)
# 
#     def get_id(self):
#         """ return the unicode of the primary key value """
#         return unicode(self.id)
# 
#     def __repr__(self):
#         return "<UserRoleEntity (\n\t" \
#             "urID: {0.id}, \n\t" \
#             " {0.user!r}, \n\t" \
#             " {0.role!r}, \n" \
#             " {0.added_at}, \n" \
#             ")>".format(self)
# 
# Path: app/utils.py
# FORMAT_US_DATE = "%x"
# FORMAT_US_DATE_TIME = '%x %X'
# FORMAT_US_DATE_TIME_ZONE = '%x %X %Z%z'
# FORMAT_DATABASE_DATE_TIME = "%Y-%m-%d %H:%M:%S"
# ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'tiff',
#                           'zip', 'tar', 'tgz', 'bz2'])
# FLASH_CATEGORY_ERROR = 'error'
# FLASH_CATEGORY_INFO = 'info'
# def _get_remote_addr():
# def _get_user_agent():
# def _create_salt():
# def _generate_sha512_hmac(pepper, salt, data):
# def generate_auth(pepper, password):
# def is_valid_auth(pepper, salt, candidate_password, correct_hash):
# def clean_str(dangerous):
# def clean_int(dangerous):
# def get_safe_int(unsafe, default=1, min_allowed=1, max_allowed=None):
# def flash_error(msg):
# def flash_info(msg):
# def pack(data):
# def pack_error(msg):
# def jsonify_error(data):
# def jsonify_success(data):
# def get_db_friendly_date_time():
# def localize_datetime(value, zone_name='US/Eastern'):
# def localize_est_date(value):
# def localize_est_datetime(value):
# def get_expiration_date(offset_days):
# def compute_text_md5(text):
# def get_email_token(email, salt, secret):
# def get_email_from_token(token, salt, secret, max_age=86400):
# def redcap_api_call(url, token, content, fields, max_time):
# def retrieve_redcap_subjects(url, token, fields, max_time=30):
# def retrieve_redcap_events(url, token, max_time=30):


from datetime import datetime
from flask_login import UserMixin
from app.main import db
from app.crud_mixin import CRUDMixin
from app.models.role_entity import RoleEntity
from app.models.user_role_entity import UserRoleEntity
from app import utils

    def is_authenticated(self):
        """ Returns True if the user is authenticated, i.e. they have provided
        valid credentials.
        (Only authenticated users will fulfill the criteria of login_required.)
        """
        return True

    def get_id(self):
        """ The id encrypted in the session """
        return unicode(self.id)

    def get_roles(self):
        """ Return text representation of user roles """
        return [role.name for role in self.roles]

    def get_name(self):
        """
        :rtype string
        :return concat(first, ' ', last)
        """
        return "{} {}".format(
            self.first.encode('utf-8'),
            self.last.encode('utf-8'))

    def get_email_verification_token(self, salt, secret):
        """
        :rtype string
        :return the email verification token stored in the
        """

# Path: app/main.py

# 
# Path: app/crud_mixin.py
# class CRUDMixin(object):
#     """ Helper class flask-sqlalchemy entities """
#     __table_args__ = {'extend_existing': True}
# 
#     id = db.Column(db.Integer, primary_key=True)
# 
#     @classmethod
#     def get_by_id(cls, id):
#         if any(
#             (isinstance(id, basestring) and id.isdigit(),
#              isinstance(id, (int, float))),
#         ):
#             return cls.query.get(int(id))
#         return None
# 
# 
#     @classmethod
#     def create(cls, **kwargs):
#         """ Helper for session.add() + session.commit() """
#         instance = cls(**kwargs)
#         return instance.save()
# 
# 
#     def update(self, commit=True, **kwargs):
#         for attr, value in kwargs.iteritems():
#             setattr(self, attr, value)
#         return commit and self.save() or self
# 
# 
#     def save(self, commit=True):
#         db.session.add(self)
#         if commit:
#             db.session.commit()
#         return self
# 
# 
#     def delete(self, commit=True):
#         db.session.delete(self)
#         return commit and db.session.commit()
# 
# Path: app/models/role_entity.py
# class RoleEntity(db.Model, CRUDMixin):  # RoleMixin
# 
#     """ Stores possible user roles """
#     __tablename__ = 'Role'
# 
#     id = db.Column("rolID", db.Integer, primary_key=True)
#     name = db.Column("rolName", db.String(255), nullable=False, unique=True)
#     description = db.Column("rolDescription", db.String(255), nullable=False)
# 
#     def __repr__(self):
#         """ implements friendly representation """
#         return "<RoleEntity (rolID: {0.id}, rolName: {0.name})>" \
#             .format(self)
# 
# Path: app/models/user_role_entity.py
# class UserRoleEntity(db.Model, CRUDMixin):
#     """ Stores the user-role mapping """
#     __tablename__ = 'UserRole'
# 
#     id = db.Column("urID", db.Integer, primary_key=True)
#     user_id = db.Column("usrID", db.Integer, db.ForeignKey('User.usrID',
#                         ondelete='CASCADE'), nullable=False)
#     role_id = db.Column("rolID", db.Integer, db.ForeignKey('Role.rolID',
#                         ondelete='CASCADE'), nullable=False)
#     added_at = db.Column('urAddedAt', db.DateTime(), nullable=False,
#                          server_default='0000-00-00 00:00:00')
# 
#     role = db.relationship('RoleEntity', uselist=False)
#     user = db.relationship('UserEntity', uselist=False)
# 
#     def get_id(self):
#         """ return the unicode of the primary key value """
#         return unicode(self.id)
# 
#     def __repr__(self):
#         return "<UserRoleEntity (\n\t" \
#             "urID: {0.id}, \n\t" \
#             " {0.user!r}, \n\t" \
#             " {0.role!r}, \n" \
#             " {0.added_at}, \n" \
#             ")>".format(self)
# 
# Path: app/utils.py
# FORMAT_US_DATE = "%x"
# FORMAT_US_DATE_TIME = '%x %X'
# FORMAT_US_DATE_TIME_ZONE = '%x %X %Z%z'
# FORMAT_DATABASE_DATE_TIME = "%Y-%m-%d %H:%M:%S"
# ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'tiff',
#                           'zip', 'tar', 'tgz', 'bz2'])
# FLASH_CATEGORY_ERROR = 'error'
# FLASH_CATEGORY_INFO = 'info'
# def _get_remote_addr():
# def _get_user_agent():
# def _create_salt():
# def _generate_sha512_hmac(pepper, salt, data):
# def generate_auth(pepper, password):
# def is_valid_auth(pepper, salt, candidate_password, correct_hash):
# def clean_str(dangerous):
# def clean_int(dangerous):
# def get_safe_int(unsafe, default=1, min_allowed=1, max_allowed=None):
# def flash_error(msg):
# def flash_info(msg):
# def pack(data):
# def pack_error(msg):
# def jsonify_error(data):
# def jsonify_success(data):
# def get_db_friendly_date_time():
# def localize_datetime(value, zone_name='US/Eastern'):
# def localize_est_date(value):
# def localize_est_datetime(value):
# def get_expiration_date(offset_days):
# def compute_text_md5(text):
# def get_email_token(email, salt, secret):
# def get_email_from_token(token, salt, secret, max_age=86400):
# def redcap_api_call(url, token, content, fields, max_time):
# def retrieve_redcap_subjects(url, token, fields, max_time=30):
# def retrieve_redcap_events(url, token, max_time=30):


# Path: app/models/user_entity.py
from datetime import datetime
from flask_login import UserMixin
from app.main import db
from app.crud_mixin import CRUDMixin
from app.models.role_entity import RoleEntity
from app.models.user_role_entity import UserRoleEntity
from app import utils


    def is_authenticated(self):
        """ Returns True if the user is authenticated, i.e. they have provided
        valid credentials.
        (Only authenticated users will fulfill the criteria of login_required.)
        """
        return True

    def get_id(self):
        """ The id encrypted in the session """
        return unicode(self.id)

    def get_roles(self):
        """ Return text representation of user roles """
        return [role.name for role in self.roles]

    def get_name(self):
        """
        :rtype string
        :return concat(first, ' ', last)
        """
        return "{} {}".format(
            self.first.encode('utf-8'),
            self.last.encode('utf-8'))

    def get_email_verification_token(self, salt, secret):
        """
        :rtype string
        :return the email verification token stored in the
        """

        return utils.get_email_token(self.email, salt, secret)