Esempio n. 1
0
class User(Document):
    gfname = StringField()
    glname = StringField()
    email = EmailField()
    aeriesid = IntField()
    gid = StringField(unique=True)
    # App Admin, Student
    role = StringField()
    issenior = BooleanField(default=False)
    admin = BooleanField(default=False)
    pronouns = StringField()
    fname = StringField()
    lname = StringField()
    image = FileField()
    birthdate = DateField()
    personalemail = EmailField()
    mobile = StringField()
    address = StringField()
    city = StringField()
    state = StringField()
    zipcode = IntField()
    socmedia = StringField()
    nextyr = StringField()
    invitelist = ListField()
    meta = {'ordering': ['+glname', '+gfname']}
Esempio n. 2
0
class Mensaje(Document):
    origen = EmailField(null=False)
    destino = EmailField(null=False)
    contenido = StringField(null=False)
    fecha = DateTimeField(default=datetime.utcnow)
    foto = StringField(null=True)

    def __str__(self):
        return self.contenido
Esempio n. 3
0
class Store(BaseRecord):
    OPTIONS = (
        ('SUN', 'Sunday'),
        ('MON', 'Monday'),
        ('TUES', 'Tuesday'),
        ('WED', 'Wednesday'),
        ('THURS', 'Thursday'),
        ('FRI', 'Friday'),
        ('SAT', 'Saturday')
    )

    # constructor:
    storeNumber = StringField(max_length=50, required=True)
    fkCustomer = ReferenceField('Customer', required=True, dbref=False)
    address = EmbeddedDocumentField(Address, required=True)
    phoneNumber = StringField(max_length=20, required=True)
    region = StringField(max_length=50, required=True)

    division = StringField(max_length=50, required=True)
    awardedVendor = StringField(max_length=50, required=True, default='PR Skate')

    overnightCrew = StringField(max_length=25)  # choices: Full Time or Part Time

    overnightAccess = ListField(StringField(max_length=5), choices=(
        ('SUN', 'Sunday'),
        ('MON', 'Monday'),
        ('TUES', 'Tuesday'),
        ('WED', 'Wednesday'),
        ('THURS', 'Thursday'),
        ('FRI', 'Friday'),
        ('SAT', 'Saturday')
    ))
    noiseOrdinance = BooleanField(default=False)
    timeCutOff = StringField()

    fkRegionCode = ReferenceField('RegionCode', dbref=False)
    fkMicroRegionCode = ReferenceField('MicroRegionCode', dbref=False)
    coordinates = EmbeddedDocumentField(Coordinates)
    active = BooleanField(default=False)
    installationDueDates = ListField(DateField())  # Uploaded able
    inspectionDueDates = ListField(DateField())  # Uploaded able MAYBE NEW TABLES
    fiscalWeek = IntField(min_value=1, max_value=53)

    storeManagerName = EmbeddedDocumentField(Name)
    storeManagerEmail = EmailField()

    opsManagerName = EmbeddedDocumentField(Name)
    opsManagerEmail = EmailField()
    managerName = EmbeddedDocumentField(Name)
    managerEmail = EmailField()
    overnightManagerName = EmbeddedDocumentField(Name)
    overnightManagerEmail = EmailField()

    meta = {'collection': 'Store'}

    def __str__(self):
        return f'{self.storeNumber} - {self.address.city} - {self.address.state}'
Esempio n. 4
0
class Ticket(Document):
    """
    Represents a ticket
    """
    title = StringField(required=True)
    status = StringField(required=True)
    text = StringField(required=True)
    create_time = DateTimeField(required=True)
    close_time = DateTimeField(required=False)
    delete_time = DateTimeField(required=False)

    creator = EmailField(required=True)
    assignee = EmailField(required=True)

    comments = EmbeddedDocumentListField(Comment)
Esempio n. 5
0
class User(Document, UserMixin):
    user_meta = EmbeddedDocumentField(Meta, default=Meta)
    name = StringField(required=True, max_length=50)
    email = EmailField(required=True, unique=True)
    role = StringField(default="volunteer")
    confirmed = BooleanField(default=False)
    password = StringField(min_length=8, required=True)
    congregation = ReferenceField('Congregation', required=True)
    isActive = BooleanField(default=True)
    shifts = ListField(ReferenceField('Shift'), default=[])

    def get_auth_token(self):
        s = Serializer(current_app.config['SECRET_KEY'])
        return s.dumps({
            'user_id': str(self.id),
            'email': self.email
        }).decode('utf-8')

    @login_manager.user_loader
    def load_user(id):
        return User.objects(id=id).first()

    # User mixin methods
    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)
Esempio n. 6
0
class User(Document):
    # Values copied from the Google Account or input by code. I recommend NOT editing the values in these fields
    # because you can't edit them in their origins. Instead, I created copies of the fields that I want to give
    # the user the ability to edit.
    # First four fields are the user's first name, last name, email and Google ID # that are copied from Google in the User.py routes file.
    gfname = StringField()
    glname = StringField()
    # Mongoengine has several field types like email field that enable you to varify that what the user put in is actually
    # that type of data like EmailField() below.
    email = EmailField()
    # unique is a parameter that is possible on all fields. it is false by default. If you want to make sure that each
    # vlaue in a field is unique that you need to set this to True. In this case gid is the users googleID and no two
    # users can have the same gid.
    gid = StringField(unique=True)
    # The role value is enterred by the code in the user.py routes based on if the user's email as an 's_' at the beginning.
    # The roles are "teacher" or "Student"
    role = StringField()
    # In the users.py file there is a python list of email addresses of people designated to be "admins" of this app.
    # so that user has some special privleges.
    admin = BooleanField()
    # The following values are all set in the users.py file.  these fields can all be edited by the user in the edit profile function.
    pronouns = StringField()
    fname = StringField()
    lname = StringField()
    # URLField() holds a URL or a link to a webpage
    image = URLField()
    # DateField() holds just a date.  There is also a DateTimeField()
    birthdate = DateField()
    # This is how you set the default sorting.  You can also sort records after you retreive them in the route.
    meta = {'ordering': ['+lname', '+fname']}
Esempio n. 7
0
class Donator(Document):
    nickname = StringField(max_length=100)
    email = EmailField(required=True)
    donated = BooleanField(default=False)
    md5 = StringField(required=True)

    meta = {'indexes': ['email', 'donated']}

    @property
    def name(self):
        return self.nickname or self.email

    @property
    def avatar(self):
        # default images for gravatar can be 'wavatar' or 'monsterid'
        return "http://gravatar.com/avatar/{}?s=60&d=wavatar".format(self.md5)
        # return "http://rokh.chehrak.com/{}?{}".format(
        #     self.md5, urlencode({'size': 64,
        #                          'default': url_for('static', filename='image/avatar.png', _external=True),
        #                          'hash': b64encode(self.email)}))

    def save(self, *args, **kwargs):
        self.md5 = md5(self.email).hexdigest()
        super(Donator, self).save(*args, **kwargs)

    @property
    def donates(self):
        return int(Donate.objects(confirm=True, donator=self).sum('amount'))

    def __repr__(self):
        return '<Donator %r>' % self.email
Esempio n. 8
0
class Account(BaseDocument):
    """
    账号表
    """
    account_source = ReferenceField('AccountSource',
                                    required=True,
                                    reverse_delete_rule=CASCADE)  # 所属平台
    user_name = StringField(max_length=64,
                            required=True,
                            unique_with='account_source')  # 账号用户名
    password = StringField(max_length=64, required=True)  # 账号密码
    account_info = ReferenceField('AccountInfo')  # 所属账号信息
    reg_email = EmailField()  # 注册账号使用的邮箱
    phone_number = StringField(max_length=16)  # 注册账号使用的手机号
    reg_time = FloatField()  # 注册时间
    health_status = StringField(default="unknown",
                                choices=("unknown", "healthy", "unhealthy",
                                         "creating", "failure"))  # 健康状态
    activities = ListField(ReferenceField(
        Activity, reverse_delete_rule=PULL))  # 账号在哪些即将或正在进行的活动中使用
    login_cookie = StringField()  # 账号登录的cookie
    last_active_time = FloatField()  # 上次活跃时间
    stats30 = IntField(default=0)  # 近30天活跃天数
    stats7 = IntField(default=0)  # 近7天活跃天数
    stats = ListField(IntField())  # 近30天的活动数组
    status = StringField(choices=('ENABLED', 'DISABLED'),
                         default='ENABLED')  # 账号状态, 0启用, 1禁用
class User(Document):
    firstName = StringField(regex=APIUtils.firstname_regex, required=True)
    lastName = StringField(regex=APIUtils.lastname_regex, required=True)
    companyName = StringField(regex=APIUtils.companyname_regex, required=True)
    username = StringField(regex=APIUtils.username_regex,
                           required=True,
                           unique=True)
    emailAddress = EmailField(required=True, unique=True)
    password = StringField(required=True)
    recoveryCode = IntField(min_value=100000,
                            max_value=999999,
                            required=False,
                            null=True)
    codeFor = StringField(null=True,
                          choices=APIUtils.valid_code_for_choices,
                          required=False)
    publicIP = StringField(regex=APIUtils.ipaddress_regex,
                           required=False,
                           default=None,
                           null=True)
    emailVerified = BooleanField(required=True, default=False)
    verifiedPublicIP = BooleanField(required=True, default=False)
    publicIPVerifier = UUIDField(required=False,
                                 default=None,
                                 null=True,
                                 binary=False)
Esempio n. 10
0
class User(Document):
    username = StringField(unique=True)
    email = EmailField(unique=True)
    password = StringField()  # add encryption.
    created = DateTimeField()
    verified = BooleanField()
    avatar = URLField()
Esempio n. 11
0
class User(EmbeddedDocument):
    name = StringField(max_length=40,min_length=5)
    email = EmailField()
    createdAt = DateField()
    token = DictField()
    password = StringField(max_length=64)
    meta = {'collection': 'users'}
Esempio n. 12
0
class Member(Document):
    email = EmailField(unique=True, required=True, description='계정 아이디 이메일 형식')
    name = StringField(required=True, description='사용자 이름')
    password = StringField(required=True,
                           min_length=6,
                           description='비밀번호 6자리 이상')
    created_time = DateTimeField(
        default=datetime.utcnow().strftime('%B %d %Y - %H:%M:%S'),
        description='가입 일시')
    last_login_time = DateTimeField(description='최근 로그인 일시')
    deleted = BooleanField(default=False, description='탈퇴 여부')
    deleted_time = DateTimeField(null=True, default=None, description='탈퇴 시간')

    # 마지막 로그인시간 업데이트
    def update_last_login_time(self):
        self.last_login_time = datetime.utcnow().strftime(
            '%B %d %Y - %H:%M:%S')
        self.save()

    # 비밀번호 체크
    def check_password(self, req):
        if not bcrypt.checkpw(req.encode('utf-8'),
                              self.password.encode('utf-8')):
            return False
        else:
            return True

    # 회원 탈퇴
    def soft_delete(self):
        self.deleted = True
        self.deleted_time = datetime.utcnow().strftime('%B %d %Y - %H:%M:%S')
        self.save()
Esempio n. 13
0
class UserInfo(EmbeddedDocument):
    nickname = StringField()
    avatar = URLField()
    location = StringField()
    gender = StringField()
    birth = DateTimeField()
    blog = URLField()
    site = URLField()
    intro = StringField()
    pf_intro = StringField()
    verified = BooleanField()
    vip = BooleanField()
    level_score = IntField()  # 经验值
    level = IntField()  # 等级
    email = EmailField()
    qq = StringField()
    msn = StringField()
    register_date = DateTimeField()
    n_follows = IntField()
    n_fans = IntField()
    n_msgs = IntField()
    is_person = BooleanField()

    edu = ListField(EmbeddedDocumentField(EduInfo))
    work = ListField(EmbeddedDocumentField(WorkInfo))
    tags = ListField(StringField())
Esempio n. 14
0
class Users(Document):
    public_id = UUIDField(binary=False, required=True, unique=True)
    username = StringField(max_length=50, unique=True)
    password = StringField(max_length=150)
    admin = BooleanField(default=False)
    email = EmailField(required=True, unique=True)
    email_confirmed = BooleanField(default=False)

    @staticmethod
    def get_specific_user(public_id: str) -> Document:
        (user,) = Users.objects(public_id=public_id)

        return user

    @staticmethod
    def delete_user(public_id: str) -> bool:
        (user,) = Users.objects(public_id=public_id)
        user.delete()

    @staticmethod
    def validate_if_existing_user(**kwargs):
        try:
            (user,) = Users.objects(**kwargs)
        except ValueError as e:
            if (
                len(e.args) > 0
                and e.args[0] == "not enough values to unpack (expected 1, got 0)"
            ):
                return False
        else:
            return True
Esempio n. 15
0
class User(Document, UserMixin):
    username = StringField(max_length=60, required=True, unique=True)
    email = EmailField(required=True, unique=True)
    password = StringField(max_length=70)
    image_file = StringField(default="default.jpg")
    preferences = ListField(default=None)

    def get_reset_token(self, expires_sec=1800):
        #s = Serializer(app.config['SECRET_KEY'], expires_sec)
        return dumps({'user_id': self.id})  #.decode('utf-8')

    @staticmethod  # tell python we don't need self as token
    def verify_reset_token(token):
        #s = Serializer(app.config['SECRET_KEY'])
        try:
            # print("models.py 30", token)
            user_id = loads(token)['user_id']
            # print(user_id)
        except:
            return None
        for query in User.objects(id=user_id):
            return query

    def __str__(self):
        return f"User('{self.username}','{self.email}','{self.password}')"
Esempio n. 16
0
class Phone(Document):
    ID = StringField(primary_key=True)
    confidence = StringField()
    name = StringField()
    gender = EmbeddedDocumentField(Gender)
    email = EmailField()
    facebook = ReferenceField(Facebook)
    addresses = ListField(StringField())
    metadata = EmbeddedDocumentField(Stats, default=Stats())

    def serialize(self, print_time=False):
        ret = OrderedDict([('ID', self.ID)])
        if not empty(self.confidence):
            ret.update({'confidence': self.confidence})
        if not empty(self.name):
            ret.update({'name': self.name})
        if not self.gender.empty():
            ret.update({'gender': self.gender.serialize()})
        if not empty(self.email):
            ret.update({'email': self.email})
        if self.facebook and not self.facebook.empty():
            ret.update({'facebook': self.facebook.serialize()})
        if len(self.addresses):
            ret.update({'addresses': self.addresses})
        if print_time:
            ret.update({'metadata': self.metadata.serialize()})
        return ret

    def expired(self):
        return self.metadata.expired()
Esempio n. 17
0
class AdminUser(Document):
    meta = {'strict': 'False'}
    id = UUIDField(primary_key=True, default=uuid4)
    name = StringField()
    email = EmailField()
    password_hash = StringField()
    permissions = StringField(choices=AdminPermissions)
    login_log = DictField()

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    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.cofirmed = True
        self.save()
        return True
Esempio n. 18
0
class UserInfo(Document):
    meta = {"collection": "user_info", "db_alias": "default"}
    name = StringField(max_length=32, required=True)
    password = StringField(max_length=32, required=True)
    email = EmailField(required=True)
    # 记录激活状态
    is_active = BooleanField(default=False)
Esempio n. 19
0
class School(Document):
    code = IntField(required=True, primary_key=True)
    name = StringField(required=True)
    street = StringField(required=True)
    suburb = StringField(required=True)
    postcode = IntField(required=True)
    phone = StringField(required=True)
    email = EmailField(required=True)
    website = URLField(required=True)
    logo = URLField(required=False)
    fax = StringField(required=True)
    enrolments = IntField(required=True)
    level = StringField(required=True)
    opportunity_classes = BooleanField(requred=True)
    selective = StringField(required=True)
    gender = StringField(required=True)
    location = PointField(required=True)
    preschool = BooleanField(required=True)
    late_opening = BooleanField(required=True)
    intensive_english_centre = BooleanField(required=True)
    healthy_canteen = BooleanField(required=True)
    indigenous_pct = FloatField(required=True)
    lbote_pct = FloatField(required=True)
    icsea = IntField(required=True)
    support_classes = ListField(required=False)
    attendance_rate = FloatField(required=False)
    selective_entry_score = IntField(required=False)
    opportunity_classes_entry_score = IntField(required=False)
    train_station_id = StringField(required=False)
    train_station = StringField(required=False)
    train_distance = IntField(required=False)
    train_duration = IntField(required=False)
    meta = {'collection': 'schools'}

    def __init__(self, code, name, street, suburb, postcode, phone, email, website, fax, enrolments,
                 level, opportunity_classes, selective, gender, location, preschool, late_opening,
                 intensive_english_centre, healthy_canteen, indigenous_pct, lbote_pct, icsea, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.code = code
        self.name = name
        self.street = street
        self.suburb = suburb
        self.postcode = postcode
        self.phone = phone
        self.email = email
        self.website = website
        self.fax = fax
        self.enrolments = enrolments
        self.level = level
        self.opportunity_classes = opportunity_classes
        self.selective = selective
        self.gender = gender
        self.location = location
        self.preschool = preschool
        self.late_opening = late_opening
        self.intensive_english_centre = intensive_english_centre
        self.healthy_canteen = healthy_canteen
        self.indigenous_pct = indigenous_pct
        self.lbote_pct = lbote_pct
        self.icsea = icsea
Esempio n. 20
0
class User(Document):
    DELIVERY_TYPE = "DELIVERY"
    CUSTOMER_TYPE = "CUSTOMER"
    BACK_OFFICE_TYPE = "BACK_OFFICE"

    FLAT_SUBSCRIPTION = "FLAT"
    PREMIUM_SUBSCRIPTION = "PREMIUM"

    name = StringField(required=False)
    last_name = StringField(required=False)
    google_id = StringField(required=False)
    password = StringField(required=False)
    email = EmailField(required=True, unique=True)
    profile_image = StringField(required=False)
    phone = StringField(required=False)
    type = StringField(required=False, regex="CUSTOMER|DELIVERY|BACK_OFFICE")
    subscription = StringField(required=False,
                               regex="FLAT|PREMIUM",
                               default="FLAT")
    recovery_token = StringField(required=False)
    recovery_token_date = DateTimeField(required=False)
    reputation = FloatField(default=1)
    fcmToken = StringField(required=False)
    messages_sent = IntField(default=0)
    created = DateField(default=datetime.now().date())
    balance = FloatField(default=0)
    location = EmbeddedDocumentField(Coordinates)
    available = BooleanField(default=True)
    deliveries_completed = IntField(default=0)
    gratitude_points = IntField(default=0)
Esempio n. 21
0
class Entity(Document):
    """The entity is the main simulation construct in NCS.

    Entities include neurons, synapses, channels, etc.
    """
    id = UUIDField(primary_key=True)
    entity_type = StringField(max_length=64)
    entity_name = StringField(max_length=64)
    description = StringField(max_length=512)
    author = StringField(max_length=128)
    author_email = EmailField(max_length=128)
    tags = ListField(ReferenceField(Tag, reverse_delete_rule=mongoengine.PULL))

    meta = {
        'allow_inheritance':
        True,
        'indexes': [
            'entity_type',
            # This is supposed to be a full-text-search index, but the
            # correct way in mongoengine to add a text-index yeilds an error
            # when performed here:
            # http://docs.mongoengine.org/guide/text-indexes.html
            {
                'fields': [
                    'entity_name',
                    'description',
                    'author',
                    'author_email',
                ],
                'default_language': 'english',
            },
        ]
    }
Esempio n. 22
0
class Resume(BaseModel):
    name = StringField(max_length=5000, null=False)
    accounts = ReferenceField('Account', null=False)
    tel = StringField(max_length=5000, null=False)
    sex = IntField(null=False)
    birthday = StringField(max_length=5000, null=False)

    email = EmailField(null=False)

    education = ListField(null=True)

    experience = ListField(null=True)

    expect_job = StringField(max_length=5000, null=True)
    expect_salary = IntField(null=True)

    postscript = StringField(max_length=5000, null=True)

    description = StringField(max_length=50000, null=True)

    file_key = StringField(max_length=1000, null=True)
    file_name = StringField(max_length=5000, null=True)

    meta = {
        'collection': 'resume',
        # 'indexes': ['title']
    }
class Recruiter(Document):
    first_name = StringField(required=True)
    last_name = StringField(required=True)
    email = EmailField(required=True, unique=True)
    phone = StringField(required=True, unique=True)
    password = StringField(required=True)
    organization = StringField(required=True)
Esempio n. 24
0
class StudentProfileDocument(Document):
    _model = StudentProfileModel

    # TODO: change `student_list` to `students`?
    uuid = UUIDField(required=True)
    email = EmailField(required=True)
    students = ListField(ReferenceField(StudentDocument))
    guardians = ListField(required=True)
    mailing_lists = ListField(required=False)

    meta = {
        "query_class": StudentProfileQuerySet,
        "db_alias": "student-db",
        "indexes": ["email", "uuid"],
    }

    def dict(self):
        students = [s.dict() for s in self.students]
        return {
            "uuid": self.uuid,
            "email": self.email,
            "student_list": students,
            "guardians": self.guardians,
            "mailing_lists": self.mailing_lists,
        }
Esempio n. 25
0
class User(DbModelMixin, AuthDocument):
    meta = {"db_alias": Database.auth, "strict": strict}

    id = StringField(primary_key=True)
    name = StringField()

    created = DateTimeField()
    """ User auth entry creation time """

    validated = DateTimeField()
    """ Last validation (login) time """

    role = StringField(required=True,
                       choices=get_options(Role),
                       default=Role.user)
    """ User role """

    company = StringField(required=True)
    """ Company this user belongs to """

    credentials = EmbeddedDocumentListField(Credentials, default=list)
    """ Credentials generated for this user """

    email = EmailField(unique=True, required=True)
    """ Email uniquely identifying the user """
Esempio n. 26
0
class Users(Document):
    """
    Template for a mongoengine Document, which represents a user.
    Password is automatically hashed before saving.
    """
    email = EmailField(required=True, unique=True)
    password = StringField(required=True, min_length=6)
    access = EmbeddedDocumentField(Access, default=Access(user=True, admin=False))
    fav_meals = ListField(ReferenceField(Meals, reverse_delete_rule=NULLIFY))
    name = StringField(default='')

    def generate_pwd_hash(self):
        # hash the password with BCrypt method
        # if len(self.password) < 20:     # prevent double hashing
        self.password = generate_password_hash(password=self.password).decode('utf-8')

    def check_pwd_hash(self, password: str) -> bool:
        # check the hash against the password with BCrypt method
        return check_password_hash(pw_hash=self.password, password=password)

    def save(self, *args, **kwargs):
        # Overwrite Document.save() method to enable password hashing before saving
        # Should only work once otherwise generates
        # new hashes which do not match anymore
        if self._created:
            self.generate_pwd_hash()
        super(Users, self).save(*args, **kwargs)
Esempio n. 27
0
class Users(Document):
    active = BooleanField(default=True)
    is_admin = BooleanField(default=False)
    name = StringField(unique=True)
    email = EmailField(unique=True, required=True)
    password = StringField(required=True)
    registered_datetime = DateTimeField(default=datetime.utcnow)
    last_logout_time = DateTimeField()

    posts = ListField(ReferenceField('Posts'))
    comments = ListField(ReferenceField('Comments'))

    def to_json(self):
        return {
            'status': 'active' if self.active else 'banned',
            'is_admin': self.is_admin,
            'name': self.name,
            'email': self.email,
            'registered_on':
            str(self.registered_datetime.replace(microsecond=0)),
            'user_post_count': len(self.posts),
            'comment_count': len(self.comments)
        }

    meta = {
        'db_alias': 'core',
        'collection': 'users',
        'indexes': ['name'],
        'ordering': ['-registered_datetime']
    }
Esempio n. 28
0
class User(Document):
    user_id = StringField(primary_key=True)
    full_name = StringField(min_length=2, max_length=50, required=True)
    country = StringField(min_length=2, max_length=50, required=True)
    email = EmailField(required=True)
    passwd = BinaryField(required=True)
    totp_secret = StringField(required=False)
Esempio n. 29
0
class UserModel(Document):
    _id = ObjectIdField(primary_key=True, default=ObjectId)
    first_name = StringField(max_length=20)
    last_name = StringField(max_length=20)
    username = StringField(required=True, unique=True)
    password = StringField(required=True)
    email = EmailField(required=True, unique=True)
    meta = {"collection": "users"}

    @classmethod
    def register_user(cls, **kwargs) -> None:
        UserModel(**kwargs).save()

    @classmethod
    def get_user_by_id(cls, _id: str) -> "UserModel":
        for user in UserModel.objects(_id=_id):
            return user

    @classmethod
    def get_user_by_username(cls, username: str) -> "UserModel":
        for user in UserModel.objects(username=username):
            return user

    @classmethod
    def get_user_by_email(cls, email: str) -> "UserModel":
        for user in UserModel.objects(email=email):
            return user
Esempio n. 30
0
class User(Document):
    username = StringField(required=True)
    email = EmailField(required=True)
    password = StringField(required=True)

    def __repr__(self):
        return '<Usuer(ano={self.username!r}>'.format(self=self)