Esempio n. 1
0
class NewBookingConfirmForm(NewBookingPeriodForm):
    booked_for_user = PrincipalField(_(u'User'), [DataRequired()],
                                     allow_external=True)
    contact_email = StringField(
        _(u'Email'),
        [InputRequired(), IndicoEmail(multi=True)])
    contact_phone = StringField(_(u'Telephone'))
    booking_reason = TextAreaField(_(u'Reason'), [DataRequired()])
    uses_vc = BooleanField(_(u'I will use videoconference equipment'))
    used_equipment = IndicoQuerySelectMultipleCheckboxField(
        _(u'VC equipment'), get_label=lambda x: x.name)
    needs_vc_assistance = BooleanField(
        _(u'Request assistance for the startup of the videoconference session. '
          u'This support is usually performed remotely.'))
    needs_assistance = BooleanField(
        _(u'Request personal assistance for meeting startup'))
    submit_book = SubmitField(_(u'Create booking'))
    submit_prebook = SubmitField(_(u'Create pre-booking'))

    def validate_used_equipment(self, field):
        if field.data and not self.uses_vc.data:
            raise ValidationError(_(u'Videoconference equipment is not used.'))
        elif not field.data and self.uses_vc.data:
            raise ValidationError(
                _(u'You need to select some Videoconference equipment'))

    def validate_needs_vc_assistance(self, field):
        if field.data and not self.uses_vc.data:
            raise ValidationError(_(u'Videoconference equipment is not used.'))
Esempio n. 2
0
class NewBookingConfirmForm(NewBookingPeriodForm):
    room_usage = RadioField(
        [DataRequired()],
        choices=[('current_user', _("I'll be using the room myself")),
                 ('other_user', _("I'm booking the room for someone else"))])
    booked_for_user = PrincipalField(
        _('User'), [HiddenUnless('room_usage', 'other_user'),
                    DataRequired()],
        allow_external=True)
    booking_reason = TextAreaField(_('Reason'), [DataRequired()])
    uses_vc = BooleanField(_('I will use videoconference equipment'))
    used_equipment = IndicoQuerySelectMultipleCheckboxField(
        _('VC equipment'), get_label=lambda x: x.name)
    needs_vc_assistance = BooleanField(
        _('Request assistance for the startup of the videoconference session. '
          'This support is usually performed remotely.'))
    needs_assistance = BooleanField(
        _('Request personal assistance for meeting startup'))
    submit_book = SubmitField(_('Create booking'))
    submit_prebook = SubmitField(_('Create pre-booking'))

    def validate_used_equipment(self, field):
        if field.data and not self.uses_vc.data:
            raise ValidationError(_('Videoconference equipment is not used.'))
        elif not field.data and self.uses_vc.data:
            raise ValidationError(
                _('Please select the type of videoconference that you will use.'
                  ))

    def validate_needs_vc_assistance(self, field):
        if field.data and not self.uses_vc.data:
            raise ValidationError(_('Videoconference equipment is not used.'))
Esempio n. 3
0
class BillForm(FlaskForm):
    date = DateField(_("Date"), validators=[Required()], default=datetime.now)
    what = StringField(_("What?"), validators=[Required()])
    payer = SelectField(_("Payer"), validators=[Required()], coerce=int)
    amount = CommaDecimalField(_("Amount paid"), validators=[Required()])
    payed_for = SelectMultipleField(_("For whom?"),
                                    validators=[Required()],
                                    coerce=int)
    submit = SubmitField(_("Submit"))
    submit2 = SubmitField(_("Submit and add a new one"))

    def save(self, bill, project):
        bill.payer_id = self.payer.data
        bill.amount = self.amount.data
        bill.what = self.what.data
        bill.date = self.date.data
        bill.owers = [
            Person.query.get(ower, project) for ower in self.payed_for.data
        ]

        return bill

    def fill(self, bill):
        self.payer.data = bill.payer_id
        self.amount.data = bill.amount
        self.what.data = bill.what
        self.date.data = bill.date
        self.payed_for.data = [int(ower.id) for ower in bill.owers]

    def set_default(self):
        self.payed_for.data = self.payed_for.default

    def validate_amount(self, field):
        if field.data == 0:
            raise ValidationError(_("Bills can't be null"))
Esempio n. 4
0
class StoreForm(AddressAccountForm):
    name = StringField("Name",
                       validators=[
                           InputRequired(),
                           Length(2, 25, "Name does not respect our rules.")
                       ])
    picture = FileField("Select a picture...")
    edit_button = SubmitField("Edit")
    add_button = SubmitField("Add")
Esempio n. 5
0
class BillForm(FlaskForm):
    date = DateField(_("Date"),
                     validators=[DataRequired()],
                     default=datetime.now)
    what = StringField(_("What?"), validators=[DataRequired()])
    payer = SelectField(_("Payer"), validators=[DataRequired()], coerce=int)
    amount = CalculatorStringField(_("Amount paid"),
                                   validators=[DataRequired()])
    external_link = URLField(
        _("External link"),
        validators=[Optional()],
        description=_("A link to an external document, related to this bill"),
    )
    payed_for = SelectMultipleField(_("For whom?"),
                                    validators=[DataRequired()],
                                    coerce=int)
    submit = SubmitField(_("Submit"))
    submit2 = SubmitField(_("Submit and add a new one"))

    def save(self, bill, project):
        bill.payer_id = self.payer.data
        bill.amount = self.amount.data
        bill.what = self.what.data
        bill.external_link = self.external_link.data
        bill.date = self.date.data
        bill.owers = [
            Person.query.get(ower, project) for ower in self.payed_for.data
        ]
        return bill

    def fake_form(self, bill, project):
        bill.payer_id = self.payer
        bill.amount = self.amount
        bill.what = self.what
        bill.external_link = ""
        bill.date = self.date
        bill.owers = [
            Person.query.get(ower, project) for ower in self.payed_for
        ]

        return bill

    def fill(self, bill):
        self.payer.data = bill.payer_id
        self.amount.data = bill.amount
        self.what.data = bill.what
        self.external_link.data = bill.external_link
        self.date.data = bill.date
        self.payed_for.data = [int(ower.id) for ower in bill.owers]

    def set_default(self):
        self.payed_for.data = self.payed_for.default

    def validate_amount(self, field):
        if field.data == 0:
            raise ValidationError(_("Bills can't be null"))
Esempio n. 6
0
class Filtrar(FlaskForm):
    desde = DateField("Desde",
                      validators=[fecha_en_pasado],
                      default=date(1, 1, 1))
    hasta = DateField("Hasta",
                      validators=[fecha_en_pasado],
                      default=date.today())
    texto = StringField("Contenido")
    submit = SubmitField("Aceptar")
    reset = SubmitField("Reset")
Esempio n. 7
0
class LoginForm(FlaskForm):
    username = StringField('Username',
                           validators=[DataRequired(),
                                       Length(min=5, max=30)])
    password = PasswordField('Password', validators=[DataRequired()])
    remember = BooleanField('Remember me')
    submit = SubmitField('Login')
Esempio n. 8
0
class MemberForm(FlaskForm):

    name = TextField(_("Name"), validators=[Required()])
    weight = CommaDecimalField(_("Weight"), default=1)
    submit = SubmitField(_("Add"))

    def __init__(self, project, edit=False, *args, **kwargs):
        super(MemberForm, self).__init__(*args, **kwargs)
        self.project = project
        self.edit = edit

    def validate_name(form, field):
        if field.data == form.name.default:
            raise ValidationError(_("User name incorrect"))
        if (not form.edit and Person.query.filter(
                Person.name == field.data, Person.project == form.project,
                Person.activated == True).all()):
            raise ValidationError(_("This project already have this member"))

    def save(self, project, person):
        # if the user is already bound to the project, just reactivate him
        person.name = self.name.data
        person.project = project
        person.weight = self.weight.data

        return person

    def fill(self, member):
        self.name.data = member.name
        self.weight.data = member.weight
Esempio n. 9
0
class UploadForm(FlaskForm):
    upload = FileField(
        'Choose an image...',
        validators=[FileRequired(),
                    FileAllowed(images, 'Images only!')])
    clusters = IntegerField('clusters', )
    submit = SubmitField('Analyse image')
Esempio n. 10
0
class RegistrationForm(FlaskForm):
    """	This is the form used to register new users. See routes.register."""

    username = StringField('Username',
                           validators=[DataRequired(),
                                       Length(min=5, max=20)])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password',
                             validators=[DataRequired(),
                                         Length(min=8)])
    confirm_password = PasswordField(
        'Confirm Password', validators=[DataRequired(),
                                        EqualTo('password')])
    submit = SubmitField('Sign me up.')

    def validate_username(self, username):
        """Check whether another user with the same USERNAME already exists in the database."""

        user = User.query.filter_by(username=username.data).first()
        if user:
            raise ValidationError('Username already exists.')

    def validate_email(self, email):
        """Check whether another user with the same EMAIL ADDRESS already exists in the database."""

        user = User.query.filter_by(email=email.data).first()
        if user:
            raise ValidationError('Email is already in use.')
Esempio n. 11
0
class LoginForm(FlaskForm):
    #定义表单中的各个项
    username=StringField(label='用户名',validators=[DataRequired()])#文本框 要求必须输入内容
    #求必须输入内容
    password=PasswordField(label='密码',validators=[DataRequired()])#密码框要求必须输入内容
    #要求必须输入内容
    submit=SubmitField()    #提交按钮
Esempio n. 12
0
class PasswordReminder(FlaskForm):
    id = StringField(_("Project identifier"), validators=[DataRequired()])
    submit = SubmitField(_("Send me the code by email"))

    def validate_id(form, field):
        if not Project.query.get(field.data):
            raise ValidationError(_("This project does not exists"))
Esempio n. 13
0
class Register(FlaskForm):
    email = EmailField('Email', [
        DataRequired('Por favor, informe seu email.'),
        Email('Por favor, use um email válido.'),
        Length(max=255, message='Email muito longo, por favor tente outro.')
    ])
    username = StringField('Nome de Usuário', [
        DataRequired('Por favor, informe seu nome de usuário.'),
        Length(
            4, 25,
            'O nome de usuário deve ter entre %(min)d a %(max)d caracteres.'),
        Regexp(
            '[a-zA-Z0-9_\-\.]+', re.IGNORECASE,
            'O nome de usuário pode conter letras, números, "_", "-" e ".".')
    ])
    password = PasswordField('Senha', [
        DataRequired('Por favor, informe sua senha.'),
        Length(4, 16, 'A senha deve ter entre %(min)d a %(max)d caracteres.'),
        EqualTo('confirm', 'As senhas não conferem.')
    ])
    confirm = PasswordField('Confirme a Senha', [
        DataRequired('Por favor, confirme sua senha.'),
        EqualTo('password', 'As senhas não conferem.'),
        Length(4, 16, 'A senha deve ter entre %(min)d a %(max)d caracteres.')
    ])
    submit = SubmitField('Cadastrar')

    def validate_email(form, field):
        if UserModel.query.filter_by(email=field.data).first():
            raise ValidationError('Este e-mail já está cadastrado.')

    def validate_username(form, field):
        if UserModel.query.filter_by(username=field.data).first():
            raise ValidationError('Este nome de usuário já está cadastrado.')
Esempio n. 14
0
class UpdateDPForm(FlaskForm):
    dp_image = FileField(
        "Change",
        validators=[FileAllowed(["jpeg", "jpg", "png"])],
        render_kw={"accept": ".png,.jpg,.jpeg"},
    )
    submitDp = SubmitField("Upload")
Esempio n. 15
0
class UpdateAccountInfoForm(FlaskForm):
    username = StringField(
        "Name",
        validators=[
            DataRequired(),
            Length(min=3,
                   max=50,
                   message="Name must be 3 to 50 characters long"),
        ],
    )
    email = StringField("E-mail", validators=[DataRequired(), Email()])
    contact = IntegerField(
        "Contact",
        validators=[
            DataRequired(),
            NumberRange(
                min=1000000000,
                max=9999999999,
                message="Contact number should have 10 digits (no spaces)",
            ),
        ],
        render_kw={
            "inputmode": "numeric",
            "minlength": "10",
            "maxlength": "10"
        },
    )
    password = PasswordField("Password *", validators=[DataRequired()])
    submitInfo = SubmitField("Save Changes")

    def validate_password(self, password):
        if not encryptor.check_password_hash(current_user.password,
                                             password.data):
            raise ValidationError("Incorrect Password")
Esempio n. 16
0
class RegisterForm(FlaskForm):
    username = StringField('Username',
                           validators=[DataRequired(),
                                       Length(min=5, max=30)])
    user_email = EmailField(
        'Email', validators=[DataRequired(),
                             Length(min=5, max=30),
                             Email()])
    password = PasswordField('Password',
                             validators=[DataRequired(),
                                         Length(max=30)])
    confirm_password = PasswordField(
        'Confirm Password', validators=[DataRequired(),
                                        EqualTo('password')])
    accept = BooleanField('Accept conditions')
    submit = SubmitField('Register')

    def validate_username(self, username):
        user = User.objects(name=username.data).first()
        if user:
            raise ValidationError(
                message=
                'Account with given username already exists. Try a different one.'
            )

    def validate_user_email(self, user_email):
        user = User.objects(email=user_email.data).first()
        if user:
            raise ValidationError(
                message=
                'Account with given email already exists. Try a different one.'
            )
Esempio n. 17
0
class ChangeProfilePictureForm(FlaskForm):
    # Form Fileds
    profilePicture = FileField(
        'Update Profile Picture',
        validators=[FileAllowed(['jpg'
                                 'png'], 'File Not Allowed')])
    submit = SubmitField("Update Profile Picture")
Esempio n. 18
0
class LoginForm(FlaskForm):
    email = StringField('Email',
                        validators=[DataRequired(), Email()])
    password = PasswordField('Password',
                             validators=[DataRequired()])
    remember = BooleanField('Remember Me')
    submit = SubmitField('Login')
Esempio n. 19
0
class Recover(FlaskForm):
    email = EmailField('Email', [
        DataRequired('Por favor, informe seu email.'),
        Email('Por favor, use um email válido.'),
        Length(max=255, message='Email muito longo, por favor tente outro.')
    ])
    submit = SubmitField('Recuperar')
Esempio n. 20
0
class LoginForm(FlaskForm):
    email               = StringField("Email",
                            validators=[DataRequired(), Email()])
    password            = PasswordField("Password",
                            validators=[DataRequired()])
    remember            = BooleanField("Remember")  # Jodi cookies hishebe egulo save korte chai
    submit              = SubmitField("Login")
Esempio n. 21
0
class PasswordResetRequestForm(FlaskForm):
    email=StringField('Email',validators=[DataRequired(),Length(1,64),Email()])
    captcha = CaptchaField('验证码')
    captcha_input = StringField('', validators=[DataRequired(), Length(4, 4),
                                                Captcha_equalTo('hidden_right_captcha', '验证码错误')])
    hidden_right_captcha = HiddenField()
    submit=SubmitField('发送重置密码邮件')
Esempio n. 22
0
class ChangePasswordForm(FlaskForm):
    # Form Fileds
    currentPassword = PasswordField(
        "Current Password", validators=[Optional(),
                                        Length(min=6, max=20)])
    password = PasswordField(
        "Password", validators=[DataRequired(),
                                Length(min=6, max=20)])
    confirmPass = PasswordField("Repeat Password",
                                validators=[
                                    DataRequired(),
                                    Length(min=6, max=20),
                                    EqualTo('password')
                                ])
    submit = SubmitField("Change Password")

    # Constructor that gets the user, so we can check the credentials and raise ValidationErrors
    def __init__(self, foundUser, *args, **kwargs):
        self.foundUser = foundUser
        super(ChangePasswordForm, self).__init__(*args, **kwargs)

    # Validates the current password
    def validate_currentPassword(self, currentPassword):
        if bcrypt.check_password_hash(
                self.foundUser.password, currentPassword.data
        ) == False and current_user.isAdmin == False:
            raise ValidationError(
                'Wrong Password. Please contact the admin for assistance.')

    # Validates if the password is correct and if not -> raises an error that can be seen in the front-end
    def validate_password(self, password):
        if bcrypt.check_password_hash(self.foundUser.password, password.data):
            raise ValidationError('No change in password!')
Esempio n. 23
0
class ModifyBookingForm(NewBookingSimpleForm):
    submit_update = SubmitField(_(u'Update booking'))

    def __init__(self, *args, **kwargs):
        self._old_start_dt = kwargs.pop('old_start_dt')
        self._old_end_dt = kwargs.pop('old_end_dt')
        super(ModifyBookingForm, self).__init__(*args, **kwargs)
        del self.room_id
        del self.submit_book
        del self.submit_prebook

    def validate_start_dt(self, field):
        super(NewBookingSimpleForm, self).validate_start_dt(field)
        new_start_dt = field.data
        now = datetime.now()

        if self._old_start_dt < now and new_start_dt != self._old_start_dt and not session.user.is_admin:
            raise ValidationError(
                _(u"The start time is in the past and cannot be modified."))
        if self._old_start_dt >= now and new_start_dt < now and not session.user.is_admin:
            raise ValidationError(
                _(u'The start time cannot be moved into the past.'))

    def validate_end_dt(self, field):
        super(NewBookingSimpleForm, self).validate_end_dt(field)
        new_end_dt = field.data
        now = datetime.now()

        if self._old_end_dt < now and new_end_dt != self._old_end_dt and not session.user.is_admin:
            raise ValidationError(
                _(u"The end time is in the past and cannot be modified."))
        if self._old_end_dt >= now and new_end_dt < now and not session.user.is_admin:
            raise ValidationError(
                _(u'The end time cannot be moved into the past.'))
Esempio n. 24
0
class LoginForm(FlaskForm):
    """ Login Form """
    email = EmailField(validators=[InputRequired('Please enter your email.')])
    password = PasswordField(
        validators=[InputRequired('Please enter your password.')])
    remember_me = BooleanField()
    submit = SubmitField('Login')
Esempio n. 25
0
class BookForm(FlaskForm):
    name = StringField(label="Book Name", validators=[DataRequired()])
    author = StringField(label="Book Author", validators=[DataRequired()])
    rating = SelectField(label="Rating",
                         validators=[DataRequired()],
                         choices=[1, 2, 3, 4, 5])
    submit = SubmitField("submit")
Esempio n. 26
0
class RegistrationForm(FlaskForm):
    username = StringField(
        'username_label',
        validators=[
            InputRequired(message="Username required"),
            Length(min=4,
                   max=25,
                   message="Username must be between 4 and 25 characters")
        ])
    email = StringField('email_label', validators=[DataRequired(), Email()])
    password = PasswordField(
        'password_label',
        validators=[
            InputRequired(message="Password required"),
            Length(min=8, message="Password must be at least 8 characters")
        ])
    confirm_pswd = PasswordField(
        'confirm_pswd_label',
        validators=[
            InputRequired(message="Password required"),
            EqualTo("password", message="Passwords must match")
        ])
    submit_button = SubmitField("Register")

    def validate_username(self, username):
        user_object = User.query.filter_by(username=username.data).first()
        if user_object:
            raise ValidationError("Username already exists.")

    def validate_email(self, email):
        user_object = User.query.filter_by(email=email.data).first()
        if user_object:
            raise ValidationError("Account with this email already exists.")
Esempio n. 27
0
class profileForm(FlaskForm):

    fullname = StringField('Полное имя',
                           validators=[InputRequired('Полное имя требуется.')])
    username = StringField(
        'Имя пользователя',
        validators=[InputRequired('Имя пользователя требуется для.')])
    email = StringField('Эл. адрес',
                        validators=[
                            InputRequired(),
                            Email(message='Эл. адрес требуется для.')
                        ])
    picture = FileField('Update Profile Picture',
                        validators=[FileAllowed(['jpg', 'png'])])
    submit = SubmitField('Update Profile')

    def validate_username(self, username):
        if username.data != current_user.username:
            user = UserInfo.query.filter_by(username=username.data).first()
            if user:
                raise ValidationError(
                    'A user is already exists with this username!!!')

    def validate_email(self, email):
        if email.data != current_user.email:
            email = UserInfo.query.filter_by(email=email.data).first()
            if email:
                raise ValidationError(
                    'A user is already exists with this Email!!!')
Esempio n. 28
0
class MessageForm(Form):
    digest = TextField(
        "Pyzor digest*",
        validators=[length(40, 40, "Invalid Digest"),
                    required()])
    message = FileField('Raw message*')
    name = TextField('Name')
    email = EmailField('Email')
    comment = TextAreaField('Other details')
    recaptcha = RecaptchaField()
    submit = SubmitField()

    def __init___(self, *args, **kwargs):
        super(MessageForm, self).__init__(*args, **kwargs)
        self.msg = None
        self.raw_message = None
        self.logger = app.logger

    def validate(self):
        if not Form.validate(self):
            return False
        self.raw_message = flask.request.files["message"].stream.read()
        try:
            digest = pyzor.digest.DataDigester(
                email.message_from_string(self.raw_message)).value
            if digest != self.digest.data:
                self.add_error("digest", "Digest does not match message.")
                return False
            client = pyzor.client.Client(timeout=20)
            try:
                response = client.check(digest)
            except pyzor.TimeoutError as e:
                self.add_error("message", "Temporary error please try again.")
                self.logger.warn("Timeout: %s", e)
                return False
            except pyzor.CommError as e:
                self.add_error("message", "Temporary error please try again.")
                self.logger.warn("Error: %s", e)
                return False
            if not response.is_ok():
                self.add_error("message", "Temporary error please try again.")
                self.logger.warn("Invalid response from server: %s", response)
                return False
            if int(response["Count"]) == 0:
                self.add_error("message", "Message not reported as spam.")
                return False
            if int(response["WL-Count"]) != 0:
                self.add_error("message", "Message is already whitelisted.")
                return False
        except AssertionError:
            self.add_error("message", "Invalid message.")
            return False
        return True

    def add_error(self, field, message):
        try:
            self.errors[field].append(message)
        except (KeyError, TypeError):
            self.errors[field] = [message]
Esempio n. 29
0
class PasswordReset(FlaskForm):
    password = PasswordField('Password',
                             validators=[DataRequired(),
                                         Length(min=8)])
    confirm_password = PasswordField(
        'Confirm Password', validators=[DataRequired(),
                                        EqualTo('password')])
    submit = SubmitField('Change my password.')
Esempio n. 30
0
class LoginForm(FlaskForm
                ):  #esto sirve para crear formularios, en este caso, de login.
    user_name = StringField('Nombre de usuario',
                            validators=[DataRequired()])  #importado de fields
    password = PasswordField('Password',
                             validators=[DataRequired()
                                         ])  #con validación de datos
    submit = SubmitField('Enviar')  #botón para enviar los datos