예제 #1
0
class Loan(db.Document):
    user = db.ReferenceField(User)
    movie = db.ReferenceField(Movie, unique_with=['user'])
    lent_date = db.DateTimeField(default=datetime.datetime.now, required=True)
    expected_return_date = db.DateTimeField(default=datetime.datetime.now,
                                            required=True)
    borrower_email = db.StringField()

    @staticmethod
    def create(user, movie, email, expected_return_date=None):
        info = Loan(user=user, movie=movie, borrower_email=email)
        if expected_return_date:
            info.expected_return_date = expected_return_date
        else:
            info.expected_return_date = info.expected_return_date + datetime.timedelta(
                days=7)
        info.save()
        return info

    def __str__(self):
        return "%s due %s" % (self.movie.title,
                              self.expected_return_date.isoformat())

    def __repr__(self):
        return self.__str__()
예제 #2
0
class MiddlewareDB(db.Document):
    meta = {'collection': 'middleware'}
    temperature = db.FloatField(required=False)
    noise = db.BooleanField(required=False)
    light = db.BooleanField(required=False)
    motion = db.BooleanField(required=False)
    data_from = db.StringField(max_length=50, required=False)
    environment = db.StringField(max_length=50, required=False)
    created_at = db.DateTimeField(default=datetime.utcnow(), required=False)
예제 #3
0
파일: models.py 프로젝트: pyxze/PyxzeHowler
class Howl(db.Document):
    created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
    howl = db.StringField(max_length=140, required=True)
    user = ReferenceField(User)

    def __unicode__(self):
        return self.howl

    meta = {'indexes': ['-created_at'], 'ordering': ['-created_at']}
예제 #4
0
파일: models.py 프로젝트: pyxze/PyxzeHowler
class User(db.Document, UserMixin):
    email = db.StringField(max_length=255)
    password = db.StringField(max_length=255)
    active = db.BooleanField(default=True)
    confirmed_at = db.DateTimeField()
    roles = db.ListField(db.ReferenceField(Role), default=[])

    name = db.StringField(max_length=255)
    username = db.StringField(max_length=255)
    howls = ListField(ReferenceField('Howl'))

    def __unicode__(self):
        return self.username
예제 #5
0
class TaskModel(db.Document):
    name = db.StringField(required=True)
    description = db.StringField()
    duration = db.IntField()
    startdate = db.DateTimeField()
    status = db.BooleanField(default=True)  #convert to enum

    # shouldnt need this on task model
    def encode_auth_token(self, user_id):
        try:
            payload = {
                'exp':
                datetime.datetime.utcnow() + datetime.timedelta(
                    days=current_app.config.get('TOKEN_EXPIRATION_DAYS'),
                    seconds=current_app.config.get(
                        'TOKEN_EXPIRATION_SECONDS')),
                'iat':
                datetime.datetime.utcnow(),
                'sub': {
                    'id': str(user_id)
                }
            }
            return jwt.encode(payload,
                              current_app.config.get('SECRET_KEY'),
                              algorithm='HS256')
        except Exception as e:
            return e

    @staticmethod
    def decode_auth_token(auth_token):
        try:
            payload = jwt.decode(auth_token,
                                 current_app.config.get('SECRET_KEY'))
            return payload['sub']
        except jwt.ExpiredSignatureError:
            return 'Signature expired. Please log in again.'
        except jwt.InvalidTokenError:
            return 'Invalid token. Please log in again.'
예제 #6
0
class User(db.Document):
    created = db.DateTimeField(default=datetime.datetime.now(), required=True)
    email = db.StringField(max_length=255, required=True, unique=True)
    salt = db.StringField(max_length=255, required=True)
    password = db.StringField(max_length=255, required=True)
    roles = db.ListField(db.StringField(max_length=50))

    def hasRole(self, role):
        return role in self.roles

    def addRole(self, role):
        if role not in self.roles:
            self.roles.append(role)
        return self

    def removeRole(self, role):
        if role in self.roles:
            self.roles.remove(role)
        return self

    def changePassword(self, password):
        self.password = hashlib.sha224(self.salt.join(password)).hexdigest()
        self.save()
        return self

    def toJSON(self):
        import json
        return json.dumps({
            'created': self.created.isoformat(),
            'email': self.email,
            'roles': self.roles,
            'id': str(self.id)
        })

    @staticmethod
    def createUser(email, password):
        user = User(email=email)
        user.salt = str(random.getrandbits(128))
        user.password = hashlib.sha224(user.salt.join(password)).hexdigest()
        user.save()
        return user

    @staticmethod
    def validateUser(email, password):
        user = User.objects(email=email).first()
        if user == None:
            return None
        password = hashlib.sha224(user.salt.join(password)).hexdigest()
        if user.password == password:
            return user
        else:
            return None

    def __str__(self):
        return self.email

    def __repr__(self):
        return str(self.toJSON())

    meta = {
        'allow_inheritance': True,
        'indexes': ['-created', 'email'],
        'ordering': ['-created']
    }
예제 #7
0
class MiddlewareStrategyDB(db.Document):
    meta = {'collection': 'strategy'}
    event = db.StringField(max_length=150, required=False)
    command = db.StringField(max_length=150, required=False)
    created_at = db.DateTimeField(default=datetime.utcnow(), required=False)
예제 #8
0
class MiddlewareDisconnectedDevicesDB(db.Document):
    meta = {'collection': 'disconnected devices'}
    name = db.StringField(max_length=50, required=False)
    environment = db.StringField(max_length=50, required=False)
    created_at = db.DateTimeField(default=datetime.utcnow(), required=False)
예제 #9
0
from project import db
from datetime import datetime


class {{device_class}}Status(db.EmbeddedDocument):
    name = db.StringField(max_length=50, unique=True, required=False)
    connect = db.BooleanField(required=False)
    created_at = db.DateTimeField(default=datetime.utcnow(), required=False)


class {{device_class}}Environment(db.EmbeddedDocument):
    {% for sensor in device["device"]["sensors"] %}
    {% if sensor == 'temperature' %}
    {{sensor}} = db.FloatField(required=False)
    {% endif %}
    {% if sensor == 'noise' %}
    {{sensor}} = db.BooleanField(required=False)
    {% endif %}
    {% if sensor == 'light' %}
    {{sensor}} = db.BooleanField(required=False)
    {% endif %}
    {% if sensor == 'motion' %}
    {{sensor}} = db.BooleanField(required=False)
    {% endif %}
    {% endfor %}
    data_from = db.StringField(max_length=50, required=False)
    created_at = db.DateTimeField(default=datetime.utcnow(), required=False)


class {{device_class}}DB(db.Document):
    meta = {'collection': '{{device_name}}'}
예제 #10
0
class Movie(db.Document):
    created = db.DateTimeField(default=datetime.datetime.now, required=True)
    title = db.StringField(max_length=255, required=True)
    summary = db.StringField(max_length=10000, required=True)
    tags = db.ListField(db.StringField(max_length=50))
    cast = db.ListField(db.StringField())
    director = db.StringField()
    tmdb_id = db.IntField()
    runtime = db.IntField()
    poster = db.StringField()
    popularity = db.FloatField()

    def addTag(self, tag):
        if tag not in self.tags:
            self.tags.append(tag)
        return self

    def removeTag(self, tag):
        if tag in self.tags:
            self.tags.remove(tag)
        return self

    def getLoan(self, user):
        from Loan import Loan
        loan = Loan.objects(movie=self, user=user).first()
        return loan

    def __str__(self):
        return self.title

    def __repr__(self):
        return self.__str__()

    def toJSON(self):
        import json
        return json.dumps({
            'created': self.created.isoformat(),
            'title': self.title,
            'summary': self.summary,
            'tags': str(self.tags),
            'id': str(self.id)
        })

    @staticmethod
    def convertMovie(movie):
        result = Movie()
        result.tmdb_id = int(movie.id)
        result.title = str(movie.title)
        result.summary = str(movie.overview.encode('utf-8'))
        if movie.poster:
            sizes = movie.poster.sizes()
            if len(sizes) > 0:
                medium = int(len(sizes) / 2)
                result.poster = str(movie.poster.geturl(sizes[medium]))
        result.popularity = float(movie.userrating)
        result.runtime = int(movie.runtime)
        tags = movie.keywords
        for tag in tags:
            result.addTag(str(tag.name.encode('utf-8')))
        genres = movie.genres
        for genre in genres:
            result.addTag(str(genre.name.encode('utf-8')))
        cast = movie.cast
        for actor in cast:
            result.cast.append("%s:%s" % (actor.name, actor.character))
        crew = movie.crew
        for person in crew:
            job = person.job.encode('utf-8')
            if 'director' == job.lower():
                result.director = person.name.encode('utf-8')
        result.save()
        return result
예제 #11
0
class PersonModel(db.Document):
    meta = {
        'indexes': [{
            'fields': [
                '$username', '$firstname', '$lastname', '$job_title',
                '$department'
            ],
            'default_language':
            'english'
        }]
    }

    username = db.StringField(required=True, unique=True)
    title = db.StringField()
    firstname = db.StringField(required=True)
    lastname = db.StringField(required=True)
    email = db.EmailField()
    gender = db.StringField()
    job_title = db.StringField()
    department = db.StringField()
    avatar = db.URLField()
    employeenumber = db.IntField()
    address = db.EmbeddedDocumentField(Address)
    startdate = db.DateTimeField()
    active = db.BooleanField(default=True)
    password = db.StringField()
    admin = db.BooleanField(default=False, required=True)
    skills = db.ListField(db.ReferenceField(SkillModel), default=[])

    def clean(self):
        self.password = bcrypt.generate_password_hash(
            self.password,
            current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()

    def encode_auth_token(self, user_id):
        try:
            payload = {
                'exp':
                datetime.datetime.utcnow() + datetime.timedelta(
                    days=current_app.config.get('TOKEN_EXPIRATION_DAYS'),
                    seconds=current_app.config.get(
                        'TOKEN_EXPIRATION_SECONDS')),
                'iat':
                datetime.datetime.utcnow(),
                'sub': {
                    'id': str(user_id),
                    'admin': self.admin,
                    'active': self.active
                }
            }
            return jwt.encode(payload,
                              current_app.config.get('SECRET_KEY'),
                              algorithm='HS256')
        except Exception as e:
            return e

    @staticmethod
    def decode_auth_token(auth_token):
        try:
            payload = jwt.decode(auth_token,
                                 current_app.config.get('SECRET_KEY'))
            return payload['sub']
        except jwt.ExpiredSignatureError:
            return 'Signature expired. Please log in again.'
        except jwt.InvalidTokenError:
            return 'Invalid token. Please log in again.'

    @classmethod
    def pre_save(cls, sender, document, **kwargs):
        print(document)