Ejemplo n.º 1
0
def create_user_email_validator(node, kw):
    email_validator = kw.get('email_validator')
    validator = All(
        Email(),
        UserEmail(**email_validator),
    )
    return validator
Ejemplo n.º 2
0
def deferred_validate_follows(node: SchemaNode, kw: dict) -> callable:
    """Validate lineare history for the `follows` field."""
    # TODO add validation for ForkableVersionables
    return All(
        validate_linear_history_no_merge,
        deferred_validate_linear_history_no_fork(node, kw),
    )
Ejemplo n.º 3
0
def create_domain_validator(node, kw):
    domain_validator = kw.get('domain_validator')
    validator = All(
        FQDN(),
        DomainName(**domain_validator),
    )
    return validator
Ejemplo n.º 4
0
class Schema(MappingSchema):
    email = SchemaNode(String(),
                       title=u'Email',
                       validator=All(Email(), signup.email_not_registered))
    password = SchemaNode(String(),
                          title=u'Current password',
                          validator=change_password.validate_current_password)
Ejemplo n.º 5
0
class Schema(MappingSchema):
    """ Signup schema for new users. """
    firstname = SchemaNode(String(), missing=null)
    lastname = SchemaNode(String(), missing=null)
    email = SchemaNode(String(),
                       title=u'Email',
                       validator=All(Email(), email_not_registered))
    password = SchemaNode(String())
Ejemplo n.º 6
0
 def validator(node: SchemaNode, kw: dict) -> All:
     request = kw['request']
     context = kw['context']
     registry = kw['registry']
     return All(
         create_validate_login(context, request, registry, 'email'),
         create_validate_login_password(request, registry),
         create_validate_account_active(request, 'email'),
     )
Ejemplo n.º 7
0
class MailCreateSchema(MappingSchema):
    subject = SchemaNode(String(), validator=Length(0, 255), missing=drop)
    content = SchemaNode(String())
    name = SchemaNode(String(), validator=Length(0, 255), missing=drop)
    address = SchemaNode(
        String(),
        validator=All(Email(), Length(0, 255)),
        missing=drop,
    )
Ejemplo n.º 8
0
class ImageReferenceSchema(MappingSchema):
    """Data structure for the image reference sheet."""

    picture = Reference(reftype=ImageReference,
                        choices_getter=get_asset_choices)
    picture_description = SingleLine()
    external_picture_url = URL(validator=All(
        URL.validator,
        picture_url_validator,
    ))
Ejemplo n.º 9
0
def deferred_verif_email_unico(node, kw):
    """
	Verifica se o email inserido para cadastro já existe no banco
	"""
    request = kw.get('request')
    emails = request.db["usrTree"].keys()
    return All(
        Email('E-mail inválido'),
        Function(lambda x: not (x in emails), u"Email já cadastrado")
    )
Ejemplo n.º 10
0
def create_named_node(stub, name):
    """ Create an ad-hoc node to represent a mapping item with
    the given name. """
    clone = stub.clone()
    clone.name = name
    valid = lambda n, v: field_name(n, name)
    if clone.validator is not None:
        valid = All(clone.validator, valid)
    clone.validator = valid
    return clone
Ejemplo n.º 11
0
 def validator(self, kw: dict) -> callable:
     """Validate the rate."""
     # TODO add post_pool validator
     context = kw['context']
     request = kw['request']
     registry = kw['registry']
     return All(
         create_validate_rate_value(registry),
         create_validate_subject(request),
         create_validate_is_unique(context, request),
     )
Ejemplo n.º 12
0
class Identifier(SchemaNode):
    """Like :class:`Name`, but doesn't check uniqueness..

    Example value: blu.ABC_12-3
    """

    schema_type = StringType
    default = ''
    missing = drop
    relative_regex = '[a-zA-Z0-9\_\-\.]+'
    validator = All(Regex('^' + relative_regex + '$'),
                    Length(min=1, max=100))
Ejemplo n.º 13
0
def deferred_validate_activation_path(node: SchemaNode, kw: dict) -> All:
    """Validate activation path and add user."""
    context = kw['context']
    request = kw['request']
    registry = kw['registry']
    return All(
        Regex('^/activate/'),
        create_validate_activation_path(
            context,
            request,
            registry,
        ),
    )
Ejemplo n.º 14
0
def create_username_validator(node, kw):
    username_validator = kw.get('username_validator')
    request = kw.get('request')
    if hasattr(request.registry, 'username_validator_class') and \
       request.registry.username_validator_class:
        custom_validator = request.registry.username_validator_class
        validator = All(
            UserName(**username_validator),
            custom_validator(**username_validator),
        )
    else:
        validator = UserName(**username_validator)
    return validator
Ejemplo n.º 15
0
def deferred_validate_badge(node, kw):
    """Check `assign_badge` permission and ISheet interface of `badge` node."""
    request = kw['request']

    def check_assign_badge_permisson(node, value):
        if not request.has_permission('assign_badge', value):
            badge_path = resource_path(value)
            raise Invalid(
                node, 'Your are missing the `assign_badge` '
                ' permission for: ' + badge_path)

    return All(
        validate_reftype,
        check_assign_badge_permisson,
    )
Ejemplo n.º 16
0
class BatchRequestPath(SingleLine):
    """A path in a batch request.

    Either a resource url or a preliminary resource path (a relative path
    preceded by '@') or an absolute path.

    Example values: '@item/v1', 'http://a.org/adhocracy/item/v1', '/item/v1/'
    """

    default = ''
    missing = required
    absolutpath = AbsolutePath.relative_regex
    preliminarypath = '[a-zA-Z0-9\_\-\.\/]+'
    validator = All(
        Regex('^(' + URL_REGEX + '|' + absolutpath + '|@' + preliminarypath +
              ')$'), Length(min=1, max=8192))
Ejemplo n.º 17
0
class ColanderSchemaTestModel(Base, ColanderAlchemyMixin):
    __tablename__ = 'colander_schema_test'

    id = sa.Column(BigInteger, autoincrement=True, primary_key=True)
    foreign_key_field = sa.Column(None, sa.ForeignKey(RelatedClassA.id))
    foreign_key_field2 = sa.Column(None, sa.ForeignKey(RelatedClassB.id))
    foreign_key_field3 = sa.Column(None, sa.ForeignKey(RelatedClassC.id))
    big_integer_field = sa.Column(BigInteger)
    integer_field = sa.Column(sa.Integer, nullable=False)
    numeric_field = sa.Column(sa.Numeric)
    float_field = sa.Column(sa.Float)
    datetime_field = sa.Column(sa.DateTime, index=True)
    date_field = sa.Column(sa.Date)
    time_field = sa.Column(sa.Time)
    text_field = sa.Column(sa.Text)
    unicode_field = sa.Column(sa.Unicode(255))
    unicode_field2 = sa.Column(sa.Unicode(20))
    unicode_field3 = sa.Column(sa.Unicode(20))
    unicode_field4 = sa.Column(sa.Unicode(20))
    unicode_text_field = sa.Column(sa.UnicodeText)
    field_with_range = sa.Column(sa.Integer)
    nullable_field = sa.Column(sa.Boolean, nullable=True)
    not_nullable_field = sa.Column(sa.Boolean, nullable=False, default=False)
    read_only_field = sa.Column(sa.Integer)

    whitelisted_relation = orm.relationship(RelatedClassA)
    read_only_relation = orm.relationship(RelatedClassB)
    not_nullable_relation = orm.relationship(RelatedClassC)

    __schema__ = {
        'read_only_field': {
            'readonly': True
        },
        'field_with_range': {
            'validator': Range(min=1, max=99)
        },
        'whitelisted_relation': {},
        'not_nullable_relation': {
            'nullable': False
        },
        'unicode_field3': {
            'validator': OneOf(['choice'])
        },
        'unicode_field4': {
            'validator': All(OneOf(['choice']), Email())
        }
    }
Ejemplo n.º 18
0
    def validator(node, kw):
        """Validator."""
        registry = kw['registry']

        def validate_permission_name(node, value):
            permission_name = value[0]
            if permission_name not in registry.content.permissions():
                msg = 'No such permission: {0}'.format(permission_name)
                raise Invalid(node, msg, value=permission_name)

        def validate_actions_names(node, value):
            for action in value[1:]:
                if action not in [security.Allow, security.Deny, None]:
                    msg = 'Invalid action: {0}'.format(action)
                    raise Invalid(node, msg, value=action)

        return All(validate_permission_name,
                   validate_actions_names)
Ejemplo n.º 19
0
def deferred_validate_user_email(node: SchemaNode, kw: dict) -> callable:
    """Return validator to check that the `email` is unique and valid or None.

    :param kw: dictionary with 'request' key and
               :class:`pyramid.request.Request` object
               If this is not available the validator is None.
    :raise: Invalid: if name is not unique or not an email address.
    """
    request = kw['request']
    registry = kw['registry']
    context = kw['context']
    locator = registry.getMultiAdapter((context, request), IUserLocator)

    def validate_user_email_is_unique(node, value):
        if locator.get_user_by_email(value):
            raise Invalid(node, 'The user login email is not unique',
                          value=value)
    validate_email = Email.validator
    return All(validate_email, validate_user_email_is_unique)
Ejemplo n.º 20
0
class References(Resources):
    """Schema Node to reference resources that implements a specific sheet.

    The constructor accepts these additional keyword arguments:

        - ``reftype``: :class:`adhocracy_core.interfaces.SheetReference`.
                       The `target_isheet` attribute of the `reftype` specifies
                       the sheet that accepted resources must implement.
                       Storing another kind of resource will trigger a
                       validation error.
        - ``backref``: marks this Reference as a back reference.
                       :class:`adhocracy_core.sheet.ResourceSheet` can use this
                       information to autogenerate the appstruct/cstruct.
                       Default: False.
    """

    reftype = SheetReference
    backref = False
    validator = All(_validate_reftypes)
    multiple = True
    widget = deferred_select_widget
Ejemplo n.º 21
0
class FormCadastrar(CSRFSchema):
    """ 
    Formulário para cadastro de novo usuário
    falta acesso para termos e condições de uso
    """
    nome = SchemaNode(
        String(),
        validator=All(
            Length(max=32),
            #Function(verif_nome_unico, u"Nome já cadastrado"),
            Regex("^(\w)*$", "Usar apenas letras, números ou _"),
        ),
        description='Digite seu nome de usuário'
    )
    email = SchemaNode(
        String(),
        validator=deferred_verif_email_unico,
        description='Digite seu e-mail',
        widget=widget.CheckedInputWidget(
            subject='Email',
            confirm_subject='Confirmar e-mail',
            size=40)
	)
    senha = SchemaNode(
        String(),
        validator=Length(min=5, max=32),
        widget=widget.CheckedPasswordWidget(size=20),
        description='Digite sua senha (no mínimo 5 caracteres) e a confirme'
    )
    confirmar = SchemaNode(
        Boolean(),	
        #description='Aceitar termos e condições',
        label='Aceitar termos e condições',
        widget=widget.CheckboxWidget(),
        title='Confirmar',
        validator=Function(lambda x: x, u'É necessário aceitar as condições'),
    )			
Ejemplo n.º 22
0
class FormContato(CSRFSchema):
    """ 
    Formulário para contato com equipe do site
    """
    assunto = SchemaNode(
        String(),
        validator=All(
            Length(max=32),
            #Function(verif_nome_unico, u"Nome já cadastrado"),
        )
    )	
    email = SchemaNode(
        String(),
		validator=Email('E-mail inválido'),
        description='Digite seu e-mail'
	)	
    mensagem = SchemaNode(
        String(),
        missing=unicode(''),		
        description='Digite sua mensagem',
        title='Mensagem',
        validator=Length(max=100),
        widget=widget.TextAreaWidget(rows=10, cols=60)
    )								
Ejemplo n.º 23
0
class RecipientCreateSchema(MappingSchema):
    name = SchemaNode(String(), validator=Length(0, 255), missing=drop)
    address = SchemaNode(String(), validator=All(Email(), Length(0, 255)))
Ejemplo n.º 24
0

def _dataset_name(name):
    """ These are names that have a special meaning in URLs and
    cannot be used for dataset names. """
    if name is not None and name.lower() in RESERVED_TERMS:
        return "'%s' is a reserved word and cannot be used here" % name
    if not re.match(r"^\w[\w\_\-]+$", name):
        return ("Name must include only "
                "letters, numbers, dashes and underscores")
    if '__' in name:
        return "Double underscores are not allowed in dataset names."
    return True


dataset_name = All(Length(min=2, max=30), Function(_dataset_name))


def _field_name(name):
    """ These are names that have a special meaning in URLs and
    cannot be used for dataset names. """
    if not re.match(r"^\w[\w\_]+$", name):
        return ("Name must include only letters, numbers and underscores")
    if '__' in name:
        return "Double underscores are not allowed in field names."
    return True


field_name = All(Length(min=2, max=60), Function(_field_name))

Ejemplo n.º 25
0
class FormConfigurar(CSRFSchema):
    """
    Formulário para configuração de perfil do usuário
    """
    
    nome = SchemaNode(
        String(),
        validator=All(
            Length(max=32),
            #Function(verif_email_unico, u"Nome já cadastrado"),
            Regex("^(\w)*$", "Usar apenas letras, números ou _"),
        ),
        missing=unicode(''),		
        description='Digite seu nome de usuário'
    )
    sobrenome = SchemaNode(
        String(),
        validator=All(
            Length(max=32),
            #Function(verif_nome_unico, u"Nome já cadastrado"),
        ),
        missing=unicode(''),		
        description='Digite seu sobrenome'
    )	
    genero = SchemaNode(
        String(),
        missing=unicode(''),
        widget=widget.SelectWidget(values=generos),
        title = "Gênero",		
    )	
    nascimento = SchemaNode(
        String(),	
        #máscara não funciona....
		#Date(),
        missing=unicode(''),
        description='Digite a data de nascimento',
		#DateInputWidget não dá erro pelo menos..
        widget= widget.TextInputWidget(mask='99/99/9999')
    )        
    """
    erro	
    foto = SchemaNode(
        deform.FileData(),
        widget=widget.FileUploadWidget(tmpstore),
        missing=unicode(''),		
        description='Carregar foto'
    ) 
    """		
    rua = SchemaNode(
        String(),
        missing=unicode(''),		
        description='Digite sua rua')
    bairro = SchemaNode(
        String(),
        missing=unicode(''),		
        description='Digite seu bairro')
    cidade = SchemaNode(
        String(),
        missing=unicode(''),		
        description='Digite sua cidade')
    estado = SchemaNode(
        String(),
        missing=unicode(''),
        widget=widget.SelectWidget(values=estados))		
    informacoes = SchemaNode(
        String(),
        missing=unicode(''),		
        description='Digite informações sobre você',
        title='Informações',
        validator=Length(max=100),
        widget=widget.TextAreaWidget(rows=10, cols=60)
    )		
    senha = SchemaNode(
        String(),
        missing=unicode(''),		
        validator=Length(min=5, max=32),
        widget=widget.CheckedPasswordWidget(size=20),
        description='Alterar sua senha (no mínimo 5 caracteres) e a confirme'
    )

    notificacoes_site = SchemaNode(
        Boolean(),	
        label='Receber notificações pelo site',
        widget=widget.CheckboxWidget(),
        title='Notificações',
        missing=unicode(''),		
    )	
    notificacoes_email = SchemaNode(
        Boolean(),	
        label='Receber notificações pelo email',
        widget=widget.CheckboxWidget(),
        title='Notificações',
        missing=unicode(''),		
    )	
    atualizacoes_pontos = SchemaNode(
        Boolean(),	
        label='Atualizações de pontos próximos ao endereço cadastrado',
        widget=widget.CheckboxWidget(),
        title='Atualização',
        missing=unicode(''),		
    )	
    atualizacoes_eventos = SchemaNode(
        Boolean(),	
        label='Eventos próximos ao endereço cadastrado',
        widget=widget.CheckboxWidget(),
        title='Atualização',
        missing=unicode(''),		
    )	
Ejemplo n.º 26
0
def deferred_validate_name(node: SchemaNode, kw: dict) -> callable:
    """Check that the node value is a valid child name."""
    return All(deferred_validate_name_is_unique(node, kw),
               *Identifier.validator.validators)
Ejemplo n.º 27
0
 def validator(self, kw: dict) -> callable:
     """Validate the :term:`post_pool` for the object reference."""
     object_validator = create_post_pool_validator(self['object'], kw)
     badge_assignment_validator = create_unique_badge_assignment_validator(
         self['badge'], self['object'], kw)
     return All(object_validator, badge_assignment_validator)
Ejemplo n.º 28
0
 def validator(node: SchemaNode, kw: dict) -> All:
     request = kw['request']
     context = kw['context']
     registry = kw['registry']
     return All(
         create_validate_service_konto_auth(context, request, registry), )
Ejemplo n.º 29
0
 def validator(node: MappingSchema, kw: dict):
     return All(
         deferred_workflow_validator(node, kw),
         create_deferred_permission_validator('edit_workflow')(node, kw),
     )