def test_email_repr(): assert ( repr(validate.Email(error=None)) == '<Email(error={0!r})>' .format('Not a valid email address.') ) assert ( repr(validate.Email(error='foo')) == '<Email(error={0!r})>' .format('foo') )
class UserSchema(ma.Schema): class Meta: model = User id = fields.Integer(dump_only=True) email = fields.Email(required=True, validate=validate.Email()) password = fields.String(load_only=True, validate=lambda x: 8 <= len(x) <= 128) otp_enabled = fields.Bool(dump_only=True) confirmed = fields.Boolean(required=True) name = fields.String(required=True, validate=lambda x: 3 <= len(x) <= 255) location = fields.String(allow_none=True, validate=lambda x: 0 <= len(x) <= 255) about_me = fields.String(allow_none=True, validate=lambda x: 0 <= len(x) <= 2**16) member_since = fields.DateTime(dump_only=True, format="iso8601") last_seen = fields.DateTime(dump_only=True, format="iso8601") created_at = fields.DateTime(dump_only=True, format="iso8601") updated_at = fields.DateTime(dump_only=True, format="iso8601") role = fields.Nested("RoleSchema", exclude=("users", )) role_id = fields.Integer( required=True, validate=lambda x: x > 0 and Role.query.get(x) is not None) links = ma.Hyperlinks({ "self": ma.URLFor("api.user", id="<id>", _external=True), "collection": ma.URLFor("api.users", _external=True), "relationships": { "posts": ma.URLFor("api.user_posts", id="<id>", _external=True) }, })
class CreateUserFuncionarioSchema(Schema): documento = fields.Str(required=True, validate=validate.Length(min=7, max=15), data_key='documento') nombres = fields.Str(required=True, validate=validate.Length(min=3, max=25), data_key='nombres') apellidos = fields.Str(required=True, validate=validate.Length(min=3, max=25), data_key='apellidos') edad = fields.Str(required=True, validate=validate.Length(max=2), data_key='edad') correo = fields.Str(required=True, validate=validate.Email(), data_key='correo') tipouser = fields.Str(required=True, validate=validate.OneOf(['Aprendiz', 'Funcionario']), data_key='tipouser') tipopersona = fields.Str(required=True, validate=validate.OneOf(['admin', 'user']), data_key='tipopersona') telefono = fields.Str(required=True, validate=validate.Length(min=7, max=10), data_key='telefono')
class RegistrerControllers_schema(Schema): name = fields.Str(required=True, validate=validate.Length(min=3, max=20), data_key='name') lastname = fields.Str(required=True, validate=validate.Length(min=3, max=20), data_key='lastname') identificationCard = fields.Str(required=True, validate=validate.Length(min=1, max=11), data_key='identificationCard') phone = fields.Str(required=True, validate=validate.Length(max=11), data_key='phone') address = fields.Str(required=True, validate=validate.Length(max=50), data_key='address') email = fields.Email(required=True, validate=validate.Email(), data_key='email') password = fields.Str(required=True, validate=validate.Length(min=5, max=15), data_key='password') rol = fields.Str(required=True, validate=validate.Length(min=1), data_key='rol')
class UserChangeDetailsSerializer(CamelCaseSchema): """Serializer to Change User Details""" first_name = fields.Str(required=False, validate=[validate.Length(min=1, max=50)]) last_name = fields.Str(required=False, validate=[validate.Length(min=1, max=50)]) email = fields.Email(required=False, validate=[validate.Email()]) password = fields.Str( required=False, validate=[ validate.Length(min=8, max=40), validate.Regexp( r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$", error=""" Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character """) ]) @post_load def hash_password(self, data, *args, **kwargs): """If PUT request has password changes plain text password to hashed password""" if 'password' in data.keys(): data['password'] = generate_password_hash( password=data.pop('password')) return data
class UserSchema(PersonSchema): __model__ = User username = fields.String(required=True, validate=validate.Length(min=1, max=30)) email = fields.String(required=True, validate=validate.Email()) dependents = fields.Nested( DependentSchema, only=['id', '_type', 'first_name', 'last_name', 'dependency_id'], many=True, dump_only=True, ) created_classes = fields.Nested( 'ClassSchema', only=[ 'id', '_type', 'title', 'duration', 'description', 'creator_id', 'num_of_lessons_per_session', 'capacity' ], many=True, dump_only=True, ) created_organizations = fields.Nested( 'OrganizationSchema', only=['id', '_type', 'name', 'creator_id'], many=True, dump_only=True, )
class RegisterUserInputSchema(Schema): email = fields.Str(required=True, validate=[validate.Email(), validate.Length(min=8)]) password = fields.Str(required=True, validate=[validate.Length(min=6)]) tenantId = fields.Str(required=True, validate=[validate.Length(min=4, max=16)])
class FooBodySchema(BaseSchema): username = fields.String(required=True, validate=validate.Length(min=1, max=512)) email = fields.String(required=True, validate=validate.Email()) some_id = fields.String(missing=gen_uuid, validate=validate.Length(min=1, max=256)) some_state = fields.Dict(missing=lambda: {})
def _emails_validate(value): lst = value.split(';') for addr in lst: if addr == '': continue name, email = parseaddr(addr) validate.Email(error='invalid emails')(email)
class UserScheme(BaseModelScheme): user_id = Str() email = Email(required=True, allow_none=False, validate=[ validate.Email(error='Incorrect email address'), lambda value: _valid_unique('User', 'email', value) ]) password = Str(validate=[validate.Length(max=72)]) is_admin = Bool() last_login = DateTime() is_active = Bool() created_on = DateTime() phone = Str(required=True, allow_none=False, validate=[ validate.Regexp(PHONE_REGEXP), lambda value: _valid_unique('User', 'phone', value) ]) logo_file_uuid = FileSchemeField(model.FileModel, 'User', 'logo', required=False) logo = Nested('FileModelScheme', many=False) class Meta: model = model.User fields = ('email', 'passwd', 'is_admin', 'is_active', 'logo_file_uuid')
class UserSchema(Schema): handle = fields.UUID(dump_only=True) email = fields.Str(required=True, validate=validate.Email()) first_name = fields.Str(required=True, data_key="firstName") last_name = fields.Str(required=True, data_key="lastName") password = fields.Str(required=True, load_only=True) is_admin = fields.Bool(dump_only=True, data_key="isAdmin") @validates("password") def validate_password(self, password): error_messages = [] if len(password) < 6 or len(password) > 18: error_messages.append( "Password must be between 7 and 18 characters long") if not any(char.isdigit() for char in password): error_messages.append("Password should have at least one numeral") if not any(char.isupper() for char in password): error_messages.append( "Password should have at least one uppercase letter") if not any(char.islower() for char in password): error_messages.append( "Password should have at least one lowercase letter") if not any(char in ["$", "@", "#", "%"] for char in password): error_messages.append( "Password should have at least one of the symbols $@#%") if len(error_messages) > 0: raise ValidationError(", ".join(error_messages))
class CustomerData(Schema): id = fields.Integer() customername = fields.String() firstname = fields.String() lastname = fields.String() email = fields.String(validate=validate.Email()) phone = fields.String()
class CustomerToUpdate(Schema): customername = fields.String() firstname = fields.String() lastname = fields.String() email = fields.String(validate=validate.Email()) password = fields.String() phone = fields.String()
class VerifySchema(Schema): email = fields.Str( required=True, validate=validate.Email(error='Not a valid email address')) verification_id = fields.Str(required=True, validate=[validate.Length(min=32, max=32)]) code = fields.Str(required=True, validate=[validate.Length(min=4, max=6)])
class CreateLoginSchema(Schema): email = fields.Str(required=True, validate=validate.Email(), data_key='email') password = fields.Str(required=True, validate=validate.Length(min=5, max=15), data_key='pass')
class UserSchema(ModelSchema): """ User schema class. """ email = field_for(User, "email", validate=validate.Email()) password = fields.Method(deserialize="calc_password") papers = Nested("PaperSchema", many=True, model=Paper) collect_papers = Nested("PaperSchema", many=True, model=Paper) collect_notes = Nested("NoteSchema", many=True, model=Note) avatar = FileField() def calc_password(self, raw_password): """ Calculate HMAC-SHA2 password. Args: raw_password: Raw user password. Returns: Byte sequence of HMAC-SHA256 result of user password. """ return pbkdf2_hmac("sha256", raw_password.encode(), USER_PASSWD_HMAC_SALT, N_HASH_ROUNDS) class Meta: """ User schema meta class. """ model = User sqla_session = db.session load_only = ("password", ) dump_only = ("id", "join_date") exclude = ("sessions", )
class UserSchema(Schema): id = fields.Str(dump_only=True) email = fields.Str( required=True, validate=[validate.Email(error="Not a valid email address")]) username = fields.Str( required=True, validate=[ validate.Length( min=4, max=50, error="username must have between {min} and {max} characters." ), validate.Regexp( r"[a-zA-Z0-9_\-]*$", error= "username must not contain special characters (except _ und -)" ), validate.ContainsNoneOf([" "], error="username must not contain spaces") ]) password = fields.Str( required=True, load_only=True, validate=[ validate.Length( min=8, max=30, error="password must have a length between {min} and {max}") ]) mqtt_topics = fields.List(fields.Str, dump_only=True)
class UpdateUserSchema(BaseSchema): username = fields.String(label='用户名') password = fields.String(label='密码') mobile = fields.String(label='手机号或电话') email = fields.String(label='邮箱', validate=validate.Email(error='输入的邮箱格式不正确。')) real_name = fields.String(label='真实姓名', validate=validate.Length( min=1, max=32, error='真实姓名长度必须在1到32个字符。')) nick_name = fields.String(label='昵称', validate=validate.Length( min=3, max=32, error='昵称长度必须在3到32个字符。')) region = fields.String(label='区域') avatar_url = fields.String(label='头像地址') gender = fields.Integer(label='性别') birth_date = fields.Date(label='出生日期', format="%Y-%m-%d") group_id = fields.Integer(label='用户组', error_messages={'invalid': '用户组id必须为整数类型'}) auth_id = fields.Integer(label='权限', error_messages={'invalid': '权限id必须为整数类型'}) @validates('mobile') def validate_mobile(self, data): if len(data) not in [11, 12]: raise ValidationError("手机号或电话格式不正确。") @pre_load def process_input(self, data, **kwargs): '''设置在验证数据之后将邮箱字段的值全部转小写,并去除前后空格。''' if data.get('email'): data['email'] = data.get('email').lower().strip() return data
class RevendedorSchema(Schema): nome = fields.Str( required=True, validate=validate.Length( min=2, max=100, error='Nome deve ter no mínimo {min} e no máximo {max} caracteres.' )) cpf = fields.Str(required=True) senha = fields.Str( required=True, validate=validate.Length( min=8, max=10, error='Senha deve ter no mínimo {min} e no máximo {max} caracteres.' )) email = fields.Str(required=True, validate=validate.Email()) @post_load def make_revendedor(self, data: dict, **kwargs): return Revendedor(**data) # TODO: Conferir algoritmo @validates("cpf") def validate_cpf(self, value): _validate_cpf(value)
class Userdata(ma.Schema): id = fields.Integer() username = fields.String(required=True) firstName = fields.String(required=True) lastName = fields.String(required=True) email = fields.String(required=True, validate=validate.Email()) phone = fields.String(required=True, validate=validate.Length(10))
class UserSchema(Schema): id = fields.Int(dump_only=True) email = fields.Str( required=True, validate=validate.Email(error='Not a valid email address'), ) password = fields.Str( required=True, validate=[validate.Length(min=6, max=36)], load_only=True, ) joined_on = fields.DateTime(dump_only=True) # Clean up data @pre_load def process_input(self, data): data['email'] = data['email'].lower().strip() return data # We add a post_dump hook to add an envelope to responses @post_dump(pass_many=True) def wrap(self, data, many): key = 'users' if many else 'user' return { key: data, }
class UserSchema(Schema): id = fields.Int() email = fields.Str(required=True, validate=validate.Email(error='Invalid email address')) password = fields.Str(required=True, load_only=True) name = fields.Str(required=True) joined_on = fields.Date(required=False)
class UserRegistrationSerializer(CamelCaseSchema): """Validation And De-serialization For User Registration""" first_name = fields.Str(required=True, validate=[validate.Length(min=1, max=50)]) last_name = fields.Str(required=True, validate=[validate.Length(min=1, max=50)]) email = fields.Email(required=True, validate=[validate.Email()]) password = fields.Str( required=True, load_only=True, validate=[ validate.Length(min=8, max=40), validate.Regexp( r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$", error=""" Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character """) ]) role_id = fields.Int(required=True, validate=[ validate.Range(min=1, max=3, max_inclusive=True, min_inclusive=True) ]) @post_load def make_user(self, data, *args, **kwargs): """:returns user instance to be added to database""" data['password'] = generate_password_hash( password=data.pop('password')) return User(**data)
class UserSchema(Schema): id = fields.Int(dump_only=True, validate=email_validator) email = fields.String( required=True, validate=(validate.Email(error="Not a valid address"), email_validator)) username = fields.String(required=True, validate=(validate.Regexp( "^(?=.{4,30}$)(?![_.])(?!.*[_.]{2})[" "a-zA-Z0-9._]+(?<![_.])$", error="Invalid username"), validate_username)) password = fields.String(required=True, load_only=True, validate=validate.Regexp( "^(?=.*\d).{8,20}$", error="Password must have " "atleast and int and " "have 8 characters")) # @post_load() # def set_password(self, data): # self.password = generate_password_hash(data["password"]) def check_password(self, data): return check_password_hash(self.pw_hash, data["password"])
class LoginControllers_schema(Schema): email = fields.Email(required=True, validate=validate.Email(), data_key='email') password = fields.Str(required=True, validate=validate.Length(min=5, max=15), data_key='password')
class UserSchema(ma.Schema): firstName = fields.String(required=True) lastName = fields.String(required=True) username = fields.String(required=True) email = fields.String(required=True, validate=validate.Email()) password = fields.Function( deserialize=lambda obj: generate_password_hash(obj), load_only=True)
class PersonSchema(Schema): """JSON schema for a person or doctor""" firstName = fields.String( attribute="first_name", required=True, error_messages={"required": "Name required"}, validate=validate.Regexp(r'^[-a-zA-Z]+$', error="First name is not valid") ) lastName = fields.String( attribute="last_name", required=True, error_messages={"required": "Last name required"}, validate=validate.Regexp(r'^[-a-zA-Z]+$', error="Last name is not valid") ) address = fields.String(validate=validate.Length(min=1, error="Address required"), required=True) city = fields.String(validate=validate.Regexp(r"^[a-zA-Z]+$", error="Not a valid city"), required=True) state = fields.String(validate=validate.Regexp(r"^[a-zA-Z]{2,}$", error="Not a valid state"), required=True) zipcode = fields.String( validate=validate.Regexp(r"^\d{5}$", error="Not a valid zip code"), required=True, attribute="zip_code" ) email = fields.String(validate=validate.Email(error="Not a valid email address"), required=True) phone = fields.String( validate=validate.Regexp("^\\(?[0-9]{3}\\)?-?\\s?[0-9]{3}-[0-9]{4}$", error="Not a valid phone"), required=True ) salary = fields.String(required=True) @pre_load def process_input(self, data): for key in data.keys(): data[key] = data[key].lower().strip() return data
class UserSchema(ma.ModelSchema): class Meta: model = User username = field_for( User, 'username', required=True, validate=validate.Length(min=3, max=25), ) password = field_for( User, 'password', required=True, validate=validate.Length(min=8, max=50), load_only=True, ) email = field_for( User, 'email', required=False, validate=( validate.Length(min=6, max=50), validate.Email(), ), ) @post_load def encrypt_password(self, data): password = data['password'] data['password'] = guard.encrypt_password(password) return data
class UserSchema(PublicBaseSchema): date_joined = fields.DateTime(dump_only=True) email = fields.Str(validate=validate.Email()) first_name = fields.Str(validate=validate.Length(min=1, max=32)) last_name = fields.Str(validate=validate.Length(min=1, max=32)) password = fields.Str(load_only=True, validate=validate.Length(min=8))
class UserSchema(marshmallow.SQLAlchemySchema): class Meta: model = models.User username = fields.Str(required=True) email = fields.Str( required=True, validate=validate.Email(error="Not a valid email address"))