class Users(UserMixin, db.Document): username = db.StringField(db_field='un', required=True, unique=True, verbose_name='Nume utilizator') avatar = db.ImageField(db_field='ig', verbose_name='Avatar', size=(640, 480, True)) pswd = db.StringField(db_field='ps', required=True) joindate = db.DateTimeField(db_field='jd', verbose_name='Data inregistrare', default=datetime.datetime.now) email = db.StringField(db_field='em', required=True, unique=True, verbose_name='Email utilizator') status = db.BooleanField(db_field='st', verbose_name='Status', default=True) permissions = db.StringField(db_field='pm', required=True, verbose_name='Drepturi', default='user') specialties = db.ListField(field=db.StringField(), db_field='sp', verbose_name='Specializari') interests = db.ListField(field=db.StringField(), db_field='in', verbose_name='Interese') projects = db.ListField(field=db.ObjectIdField(), db_field='pj', verbose_name='Proiecte') mail_confirmed = db.BooleanField(db_field='mc', default=False) @property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, passwd): self.pswd = generate_password_hash(passwd) def verify_password(self, passwd): return check_password_hash(self.pswd, passwd) def is_admin(self): return self.permissions == 'full' def is_active(self): return self.status def generate_confirmation_token(self, expiration=7200): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': unicode(self.id)}) def confirm(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('confirm') != unicode(self.id): return False self.mail_confirmed = True self.save() return True def generate_reset_token(self, expiration=7200): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': unicode(self.id)}) def resetpass(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return None if data.get('reset') != unicode(self.id): return None return self.id
class Image(db.Document): """ :ivar date_created: :class:`mongoengine.fields.DateTimeField` - The date when the document was created, localized to the server. :ivar date_modified: :class:`mongoengine.fields.DateTimeField` - The date when the document was last modified, localized to the server. :ivar filename: :class:`mongoengine.fields.StringField` - The filename with extension of the image. :ivar creator: :class:`mongoengine.fields.ReferenceField` - Reference to the User that uploaded the photo. :ivar caption: :class:`mongoengine.fields.StringField` - A caption for the photo. :ivar source: :class:`mongoengine.fields.StringField` - A source credit for the picture, if one is needed. :ivar default_path: :class:`mongoengine.fields.StringField` - The path the the version of the image that should be used by default. :ivar versions: :class:`mongoengine.fields.DictField` - A dictionary of sizes to file paths. """ # MongoEngine ORM metadata meta = { 'allow_inheritance': True, 'indexes': ['creator'], 'ordering': ['-date_created'] } date_created = db.DateTimeField(default=now, required=True) date_modified = db.DateTimeField(default=now, required=True) filename = db.StringField(unique=True, max_length=255, required=True, regex=FULL_FILENAME_REGEX) creator = db.ReferenceField('User', required=True) caption = db.StringField() source = db.StringField() default_path = db.StringField(required=True) versions = db.DictField(required=True) def url(self): """Returns the URL path that points to the image. :returns: The URL path like ``"/static/img/cat.jpg"``. :rtype: str """ return url_for('media.file', filename=self.filename) def clean(self): """Called by Mongoengine on every ``.save()`` to the object. Update date_modified and populate the versions dict. :raises: :class:`wtforms.validators.ValidationError` """ VALID_PATHS = re.compile("^(" + BASEDIR + "|http://|https://).*$") self.date_modified = now() if not VALID_PATHS.match(self.default_path): self.default_path = os.path.join(BASEDIR, self.default_path) if self.default_path and self.default_path not in self.versions.values( ): try: width, height = PIL.Image.open(self.default_path).size self.versions['{width}x{height}'.format( width=width, height=height)] = self.default_path except IOError: raise ValidationError('File {} does not exist.'.format( self.default_path)) def pre_validate(form): """Called by Mongoengine before the validation occurs. Ensure that the versions dictionary contains keys of the form ``"<width>x<height>"``, where ``width`` and ``height`` are the size of the image at the path. :raises: :class:`wtforms.validators.ValidationError` """ for size, path in form.versions: try: width, height = PIL.Image.open(path).size if size != '{width}x{height}'.format(width=width, height=height): error = 'Key {size} improperly describes image {path}'.format( size=size, path=path) raise ValidationError(error) except IOError: error = 'File {} does not exist.'.format(form.default_path) raise ValidationError(error) @classmethod def post_delete(klass, sender, document, **kwargs): """Called by Mongoengine after the object has been delted. Moves the deleted image's assocaited files to the DELETED_FOLDER. """ for size, old_path in document.versions.iteritems(): _, filename = os.path.split(old_path) delete_folder = RELATIVE_DELETE_FOLDER if not os.path.isdir(delete_folder): os.mkdir(delete_folder) new_path = os.path.join(delete_folder, filename) try: os.rename(old_path, new_path) except IOError: pass def __unicode__(self): """This image, as a unicode string. :returns: The filename of the image. :rtype: str """ return self.filename def __repr__(self): """The representation of this image. :returns: The image's details. :rtype: str """ rep = 'Photo(filename=%r, default_path=%r, caption=%r)' % \ (self.filename, self.default_path, self.caption) return rep
class Comments(db.Document): author = db.GenericReferenceField(db_field='au', verbose_name='Autor') content = db.StringField(db_field='ct', verbose_name='Continut', required=True) timestamp = db.DateTimeField(db_field='ts', verbose_name='Data') reference = db.GenericReferenceField(db_field='rf', verbose_name='Referinta')
class Todo(db.Document): content = db.StringField(required=True, max_length=20) time = db.DateTimeField(default=datetime.datetime.now()) status = db.IntField(default=0)
class User(UserMixin, db.DynamicDocument): meta = {'collection': 'users'} username = db.StringField(max_length=64) email = db.StringField(max_length=64) password = db.StringField() date_registered = db.DateTimeField(default=datetime.datetime.utcnow()) real_name = db.StringField() city = db.StringField() avatar_url = db.StringField( default= 'https://irac.me/wp-content/uploads/2017/08/irac-user-gravatar-blue-e1503260290469.png' ) collections = db.DictField() saved_games = db.DictField() is_private = db.BooleanField(default=False) @classmethod def register(cls, email, password, username): hashed_pwd = bcrypt.generate_password_hash(password).decode('UTF-8') user = cls(email=email, password=hashed_pwd, username=username).save() return user @classmethod def authenticate(cls, email, password): user = cls.objects(email=email).first() if user: check = bcrypt.check_password_hash(user.password, password) if check: return user return False def save_game(self, game_id, status): self.saved_games[game_id] = status self.save() return self def set_game_status(self, game_id, status): self.saved_game[game_id] = status self.save() return self def create_collection(self, collection_name, collection_description, collection_image, date_created): if not collection_image: collection_image = 'https://avatars.mds.yandex.net/get-pdb/1935444/fab3d347-96a8-4538-94f9-138ba41df623/s1200?webp=false' self.collections[slugify(collection_name)] = { 'name': collection_name, 'games': [], 'description': collection_description, 'imageURL': collection_image, 'date_created': date_created, 'is_private': False } self.save() return self def delete_collection(self, collection_name): del self.collections[collection_name] self.save() return self def add_game_to_collection(self, game_id, collection_name): if game_id not in self.collections[collection_name]['games']: self.collections[collection_name]['games'].append(game_id) self.save() return self def remove_game_from_collection(self, game_id, collection_name): self.collection[collection_name]['games'].remove(game_id) self.save() return self def update_profile(self, name, city, avatar): self.name = name self.city = city if not avatar: self.avatar_url = 'https://irac.me/wp-content/uploads/2017/08/irac-user-gravatar-blue-e1503260290469.png' else: self.avatar_url = avatar self.save() return self def toggle_private(self, collection_name): self.collections[collection_name][ 'is_private'] = True if self.collections[collection_name][ 'is_private'] == False else False self.save() return self
class Loan(tdb.Document): from datetime import datetime loanId = tdb.StringField(required=False) userNo = tdb.IntField(required=False) cellPhone = tdb.StringField(required=False) password = tdb.StringField(required=False) type = tdb.StringField(required=False) address1 = tdb.StringField(required=False) address2 = tdb.StringField(required=False) zipCode = tdb.StringField(required=False) numberHouseholds = tdb.StringField(required=False) schedule = tdb.StringField(required=False) progressRate = tdb.IntField(required=False) supplyArea = tdb.FloatField(required=False) owner = tdb.StringField(required=False) guest = tdb.StringField(required=False) sellType = tdb.StringField(required=False) sellAmount = tdb.FloatField(required=False) bank = tdb.StringField(required=False) bankingAmount = tdb.FloatField(required=False) bankingStatus = tdb.StringField(required=False) job = tdb.StringField(required=False) proofIncome = tdb.FloatField(required=False) unProofIncome = tdb.FloatField(required=False) totalIncome = tdb.FloatField(required=False) exclusiveArea = tdb.FloatField(required=False) expectedSlaes = tdb.FloatField(required=False) businessExpenses = tdb.FloatField(required=False) profixsBusiness = tdb.FloatField(required=False) ownAmount = tdb.FloatField(required=False) loanAmount = tdb.FloatField(required=False) channel = tdb.StringField(required=False) comment = tdb.StringField(required=False) createDate = tdb.DateTimeField(default=datetime.now()) updateDate = tdb.DateTimeField(default=datetime.now()) def __repr__(self): return "<Loan('%s', '%s'>" % (self.userNo, self.cellPhone) def __init__(self, *args, **kwargs): import uuid super(Loan, self).__init__(*args, **kwargs) self.loanId = str(uuid.uuid4()).replace('-', '') if kwargs.get('userNo') is None: self.cellPhone = kwargs['cellPhone'] self.password = kwargs['password'] else: self.userNo = kwargs['userNo'] def __getitem__(self, key): return getattr(self, key) def fromdict(self, v): for key, value in v.items(): if value.isdigit() is True: setattr(self, key, int(value)) elif isfloat(value=value) is True: setattr(self, key, float(value)) else: setattr(self, key, value) return self
class UsersModel(db.Document): username = db.StringField(required=True, unique=True) email = db.StringField(required=True, unique=True) password = db.StringField(required=True) created_at = db.DateTimeField(default=datetime.utcnow()) updated_at = db.DateTimeField() deleted_at = db.DateTimeField() @db.queryset_manager def list_users(doc_cls, queryset): return queryset.filter(deleted_at=None) @staticmethod def get_user(user_id): model = UsersModel.objects.get(pk=user_id) return User.from_model(model) @staticmethod def get_model(user_id): return UsersModel.objects.get(pk=user_id) @staticmethod def filter_users(**kwargs): query = UsersModel.objects(**kwargs, deleted_at=None) return query @staticmethod def search_users(username): query = UsersModel.objects(username__icontains=username, deleted_at=None) return query @staticmethod def sorted_by(field, query): return query.order_by(field) @staticmethod # todo transform into utility method def paginate(query, page, elements_per_page=10): start = (page - 1) * elements_per_page end = start + elements_per_page return query[start:end] @staticmethod def persist(user): user_model = UsersModel.from_user(user) user_model.save() return user_model @staticmethod def from_user(user): if user.user_id == 0: user_model = UsersModel(username=user.username, email=user.email, password=user.password) else: user_model = UsersModel.get_model(user.user_id) user_model.username = user.username user_model.email = user.email user_model.updated_at = datetime.utcnow() return user_model def remove(self): self.deleted_at = datetime.utcnow() self.save() def to_json(self): return { 'id': str(self.id), 'username': self.username, 'email': self.email, 'created_at': self.created_at, 'updated_at': self.updated_at, 'deleted_at': self.deleted_at }
class Review(db.EmbeddedDocument): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) body = db.StringField(verbose_name="Review", required=True) username = db.StringField(verbose_name="Username", max_length=255, required=True)
class Post(db.Document): """A generic post object. :ivar date_created: :class:`mongoengine.fields.DateTimeField` - The date the post was created. :ivar date_modified: :class:`mongoengine.fields.DateTimeField` - The date the post was last modified. :ivar title: :class:`mongoengine.fields.StringField` - The title of the post. :ivar author: :class:`mongoengine.fields.ReferenceField` - The author of the post. :ivar html_content: :class:`mongoengine.fields.StringField` - The HTML body of the post. :ivar markdown_content: :class:`mongoengine.fields.StringField` - The markdown body of the post, which will be rendered to HTML. :ivar images: :class:`mongoengine.fields.ListField` of :class:`mongoengine.fields.ReferenceField` - The images for this blog post. :ivar featured_image: :class:`mongoengine.fields.ReferenceField` - The featured image on this post. :ivar slug: :class:`mongoengine.fields.StringField` - The URL slug associated with this post. :ivar categories: :class:`mongoengine.fields.ListField` of :class:`mongoengine.fields.StringField` - A list of categories for this post. :ivar tags: :class:`mongoengine.fields.ListField` of :class:`mongoengine.fields.StringField` - A list of tags for this post. :ivar published: :class:`mongoengine.fields.BooleanField` - True if the event is published. :ivar date_published: :class:`mongoengine.fields.DateTimeField` - The date when this post was published. :ivar posted_by: :class:`mongoengine.fields.ReferenceField` - The user that posted this event. This may be different than the post's author, if the author was a guest writer or someone not registered with Eventum. """ # MongoEngine ORM metadata meta = { 'allow_inheritance': True, 'indexes': ['title', 'date_created'], 'ordering': ['-date_created'] } date_created = db.DateTimeField(required=True, default=now) date_modified = db.DateTimeField(required=True, default=now) title = db.StringField(required=True, max_length=255) author = db.ReferenceField(User, required=True) html_content = db.StringField() markdown_content = db.StringField(required=True) images = db.ListField(db.ReferenceField('Image')) featured_image = db.ReferenceField('Image') slug = db.StringField(required=True, regex=SLUG_REGEX) categories = db.ListField(db.StringField(db_field='category', max_length=255), default=list) tags = db.ListField(db.StringField(db_field='tag', max_length=255), default=list) published = db.BooleanField(required=True, default=False) date_published = db.DateTimeField() posted_by = db.ReferenceField(User, required=True) def id_str(self): """The id of this object, as a string. :returns: The id :rtype: str """ return str(self.id) def clean(self): """Called by Mongoengine on every ``.save()`` to the object. Update date_modified, and fill in posted_by and html_content if invalid. :raises: :class:`wtforms.validators.ValidationError` """ self.date_modified = now() self.html_content = markdown.markdown(self.markdown_content, ['extra', 'smarty']) if self.images: for image in self.images: self.html_content = self.html_content.replace( 'src="' + image.filename + '"', 'src="' + image.url() + '"') if not self.posted_by: self.posted_by = self.author if self.published and not self.date_published: self.date_published = now() def __unicode__(self): """This post, as a unicode string. :returns: The title of the post :rtype: str """ return self.title def __repr__(self): """The representation of this post. :returns: The post's details. :rtype: str """ rep = '%r(title=%r, author=%r, categories=%r, tags=%r, published=%r' %\ (self.__class__.__name__, self.title, self.author, self.categories, self.tags, self.published) # excluded if None rep += ', date_published=%r' % (self.date_published) \ if self.date_published else "" rep += ', posted_by=%r' % (self.posted_by) if self.posted_by else "" # cut down to 100 characters if len(self.html_content) > 100: rep += ', html_content=%r' % (self.html_content[:97] + "...") else: rep += ', html_content=%r' % (self.html_content) return rep
class User(db.Document): id = db.SequenceField(primary_key=True) email = db.StringField(required=True, unique=True, index=True) username = db.StringField(max_length=50, required=True, index=True) p_hash = db.StringField(max_length=128, required=True) confirmed = db.BooleanField(default=False) role = db.ReferenceField(Role) last_seen = db.DateTimeField(default=datetime.datetime.now) def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config['FY_ADMIN']: self.role = Role.objects(name='Admin').first() else: self.role = Role.objects(default=True).first() @property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.p_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.p_hash, password) # Flask-Login integration def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return str(self.id) def generate_confirmToken(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}) def confirm(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('confirm') != self.id: return False self.confirmed = True # db.session.add(self) self.save() return True def is_permitted(self, permission): return self.role is not None and self.role.is_permitted(permission) def is_admin(self): return self.is_permitted(Permission.ADMIN) def ping(self): self.last_seen = datetime.datetime.now self.save()
class AssignJob(db.Document): worker = db.ReferenceField(Worker) job = db.ReferenceField(Jobs) assign_from = db.DateTimeField() assign_till = db.DateTimeField() status = db.BooleanField()