Ejemplo n.º 1
0
Archivo: view.py Proyecto: zabano/dx
def show_reports():

    form = FlaskForm()
    if form.validate_on_submit():

        vcf_id = request.form['vcfs'].split(',')[0]
        url = urlparse.urlparse(request.form['url'])
        args = MultiDict(urlparse.parse_qsl(url.query))
        response = jsonapi.get_related(db, args, 'vcfs', vcf_id, 'calls')
        title = request.form.get('title')
        if response.status == requests.codes.ok:
            report = Report(title)
            report.vcfs = [VCF.query.get(vcf_id)]
            report.creator = current_user
            report.project = Project.query.get(request.form.get('project'))
            report.panels = Panel.query.filter(Panel.id.in_(request.form.get('panels').split(','))).all()
            report.fisher = request.form.get('fisher')
            report.artifact = request.form.get('artifact')
            report.frequency = request.form.get('frequency')
            report.depth = request.form.get('depth')
            report.content = cPickle.dumps(response.document)
            db.add(report)
            try:
                db.commit()
            except SQLAlchemyError:
                flash("Error saving report: '{0}'. Please try again later.".format(title), category='danger')
            else:
                flash("Report: '{0}' saved successfully.".format(title), category='success')

    admin = current_user.is_authenticated and PERMISSION.MANAGE_REPORT_REQUEST in current_user.permissions
    return render_template('reports/index.html', admin=admin)
Ejemplo n.º 2
0
    def update_datacite(self):
        """."""
        form = UpdateDataciteForm()
        cancel_or_new_task_form = FlaskForm()

        is_task_running = False
        time = 0
        task_details = current_cache.get('update_datacite:task_details')

        if task_details:
            is_task_running = True
            if cancel_or_new_task_form.validate_on_submit():
                current_cache.set('update_datacite:task_details', None)
                return redirect(url_for('updatedataciteview.update_datacite'))
        else:
            if form.validate_on_submit():
                from_date = request.form['from_date']
                until_date = request.form['until_date']

                action = request.form['action']
                if action == 'SubmitDates':
                    if from_date > until_date:
                        flash("Error: the 'From' date should precede the 'Until' date.")
                    else:
                        pids_count = find_registered_doi_pids(from_date,
                                                                until_date,
                                                                current_app.config['ZENODO_LOCAL_DOI_PREFIXES']).count()
                        task_details = dict(
                            total_pids=pids_count
                        )
                        time = pids_count/current_app.config['DATACITE_UPDATING_RATE_PER_HOUR']

                elif action == 'Confirm':
                    pids_count = find_registered_doi_pids(from_date,
                                                          until_date,
                                                          current_app.config['ZENODO_LOCAL_DOI_PREFIXES']).count()
                    task_details = dict(
                        start_date=datetime.utcnow(),
                        job_id=str(uuid.uuid4()),
                        from_date=from_date,
                        until_date=until_date,
                        total_pids=pids_count,
                        left_pids=pids_count,
                        last_update=datetime.utcnow()
                    )
                    current_cache.set('update_datacite:task_details',
                                      task_details, timeout=-1)
                    return redirect(url_for('updatedataciteview.update_datacite'))

                elif action == 'Cancel':
                    return redirect(url_for('updatedataciteview.update_datacite'))

        return self.render('zenodo_records/update_datacite.html',
                           form=form,
                           cancel_or_new_task_form=cancel_or_new_task_form,
                           details=task_details,
                           is_task_running=is_task_running, time=time)
Ejemplo n.º 3
0
def delete(id):
    item = Transcript.query.get_or_404(id)
    form = FlaskForm()

    if form.validate_on_submit():
        db.session.delete(item)
        db.session.commit()
        return redirect_for('transcript.index')

    return render_template('transcript/delete.html', item=item, form=form)
Ejemplo n.º 4
0
def delete(id):
    item = Salad.query.get_or_404(id)
    form = FlaskForm()

    if form.validate_on_submit():
        item.delete()
        db.session.commit()

        return redirect_for('salad.index')

    return render_template('salad/delete.html', item=item, form=form)
Ejemplo n.º 5
0
def email_verification_request():
    """GET|POST /email-verification-request: handle email verification requests
    """
    u = g.user

    form = FlaskForm()
    if form.validate_on_submit():
        send_verification_email(u)
        fn = '/auth/email-verification-request-followup.html'
        return render_template(fn, email=u.email)

    return render_template('/auth/email-verification-request.html', form=form)
Ejemplo n.º 6
0
 def validate(self):
     rv = FlaskForm.validate(self)
     if not rv:
         return False
     if len(str(self.postalcode.data)) is 5 and int(self.postalcode.data):
         return True
     self.postalcode.data = re.sub(r'\s', r'', self.postalcode.data)
     if not len(str(self.postalcode.data)) is 6:
         self.postalcode.errors.append('Invalid postal code (length)')
         return False
     if not ''.join([
         str(self.postalcode.data)[0],
         str(self.postalcode.data)[2],
         str(self.postalcode.data)[4]
     ]).isalpha():
         self.postalcode.errors.append(
             'Invalid postal code (example: A1A1A1)'
         )
         return False
     if not ''.join([
         str(self.postalcode.data)[1],
         str(self.postalcode.data)[3],
         str(self.postalcode.data)[5]
     ]).isdigit():
         self.postalcode.errors.append(
             'Invalid postal code (example: A1A1A1)'
         )
         return False
     return True
Ejemplo n.º 7
0
    def validate(self):

        # Validate all other fields with default validators
        if not FlaskForm.validate(self):
            return False
        result = True

        archive_date = self.archive_date.data
        publish_date = self.publish_date.data
        if archive_date and publish_date > archive_date:
            self.archive_date.errors.append(
                _('Archive date needs to be after the publish date.'))
            result = False

        # Test if either english or dutch is entered
        if not (self.nl_title.data or self.en_title.data):
            self.nl_title.errors.append(
                _('Either Dutch or English title required'))
            result = False
        if not (self.nl_content.data or self.en_content.data):
            self.nl_content.errors.append(
                _('Either Dutch or English content required'))
            result = False

        # XOR the results to test if both of a language was given
        if bool(self.nl_title.data) != bool(self.nl_content.data):
            self.nl_title.errors.append(
                _('Dutch title requires Dutch content and vice versa'))
            result = False
        if bool(self.en_title.data) != bool(self.en_content.data):
            self.en_title.errors.append(
                _('English title requires English content and vice versa'))
            result = False

        return result
Ejemplo n.º 8
0
 def validate(self):
     rv = FlaskForm.validate(self)
     if rv is None:
         return False
     user = authenticate_user(current_user.username, self.password.data)
     if user is None:
         return False
     return True
Ejemplo n.º 9
0
	def validate(self):
		if not Form.validate(self):
			return False
		if self.username.data == self.original_username:
			return True
		user = User.query.filter_by(username = self.username.data).first()
		if user != None:
			return False
		return True
Ejemplo n.º 10
0
 def validate(self):
     if not FlaskForm.validate(self):
         return False
     user = User.query.filter_by(email = self.email.data.lower()).first()
     if user:
         self.email.errors.append("That email is already taken")
         return False
     else:
         return True
Ejemplo n.º 11
0
    def validate(self):
        if not FlaskForm.validate(self):
            return False

        if self.open.data:
            self.desired_state = DoorState.Open
        elif self.present.data:
            self.desired_state = DoorState.Present

        return True
Ejemplo n.º 12
0
    def validate(self):
        if not FlaskForm.validate(self):
            return False

        user = User.query.filter_by(email = self.email.data.lower()).first()
        if user and user.check_password(self.password.data):
            return True
        else:
            self.email.errors.append("Invalid e-mail or password")
            return False
Ejemplo n.º 13
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        user = User.get_user(self.username.data)
        if user and user.username.lower() != g.user.username.lower():
            self.username.errors.append('Username already in use')
            return False

        return True
Ejemplo n.º 14
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if rv is None:
            return False

        user = User.objects(username__iexact=self.username.data).first()
        if user is None:
            return True

        else:
            self.username.errors.append("Username is already taken - try again")
            return False
Ejemplo n.º 15
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if rv is None:
            return False

        user = authenticate_user(self.username.data, self.password.data)
        if user is None:
            self.username.errors.append("Invalid username or password")
            return False
        else:
            self.user = user
            return True
Ejemplo n.º 16
0
 def validate(self):
     rv = FlaskForm.validate(self)
     config = ConfigParser.RawConfigParser()
     config.read('swingflask.conf')
     if (
         self.username.data == config.get('admin', 'username')
         and self.password.data == config.get('admin', 'password')
     ):
         return True
     else:
         self.username.errors.append('Invalid credentials')
         return False
Ejemplo n.º 17
0
    def validate(self):
        rv = Form.validate(self)
        if not rv:
            return False

        captcha = session['captcha']
        captcha_data = self.captcha.data
        if captcha_data.lower() != captcha.lower():
            self.captcha.errors.append(_('The captcha is error'))
            return False

        return True
Ejemplo n.º 18
0
    def validate(self):
        # check default validation
        if not FlaskForm.validate(self):
            return False

        # check nested forms
        for t in self.target_set:
            if not t.form.validate():
                error_fields = ','.join(t.form.errors.keys())
                self.target_set.errors.append({'target': t.name, 'message': 'Invalid target ' + error_fields})
                return False

        return True
Ejemplo n.º 19
0
    def validate(self):
        if not FlaskForm.validate(self):
            print "wrong two"
            return False

        user = User.query.filter_by(username=self.username.data).first()
        if user and user.verify_password(self.password_hash.data):
            return True

        else:
            flash('invalid username or password')
            self.username.errors.append("Invalid username or password")
            return False
Ejemplo n.º 20
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        user = User.query.filter_by(username=self.username.data).first()
        if user and user.verify_password(self.password_hash.data):
            print "login 1 working"
            return True

        else:
            flash("Invalid username or password")
            #self.username.errors.append("Invalid username or password")
            return False
Ejemplo n.º 21
0
    def validate(self):

        # Validate all other fields with default validators
        if not FlaskForm.validate(self):
            return False

        # Test if either english or dutch is entered
        if self.start_time.data >= self.end_time.data:
            self.start_time.errors.append(
                _("Start time must be before end time"))
            # Append empty string to mark the field red.
            self.end_time.errors.append('')
            return False

        return True
Ejemplo n.º 22
0
    def validate(self, *args, **kwargs):
        """
        Validates the form by calling `validate` on each field, passing any
        extra `Form.validate_<fieldname>` validators to the field validator.

        also calls `validate_ldap`
        """

        valid = FlaskForm.validate(self, *args, **kwargs)
        if not valid:
            logging.debug("Form validation failed before we had a change to "
                          "check ldap. Reasons: '{0}'".format(self.errors))
            return valid

        return self.validate_ldap()
Ejemplo n.º 23
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        print "hello worlkd"
        username = User.query.filter(func.lower(User.username) == func.lower(self.username.data)).first()

        if username:
            self.username.errors.append("Invalid username or password")
            flash('username taken')
            return False
        else:
            print "Register Validate success"

            return True
 def validate(self):
     if not FlaskForm.validate(self):
         return False
     if self.country_input_method.data == 'choose':
         if place_exists(self.place.data, self.country.data.country_name):
             flash(
                 f'Место {self.place.data} в {self.country.data.country_name} уже существует'
             )
             return False
     if self.country_input_method.data == 'create':
         if country_exists(self.new_country.data):
             flash(f'Страна {self.new_country.data} уже существует')
             return False
         if self.new_country.data == '':
             flash('Название страны - обязательно поле')
             return False
     return True
Ejemplo n.º 25
0
    def validate(self) -> bool:
        valid = FlaskForm.validate(self)

        # Check date format, if valid put dates into a list called "dates"
        dates = {}
        for prefix in ['begin_', 'end_']:
            for postfix in ['_from', '_to']:
                if getattr(self, prefix + 'year' + postfix).data:
                    date = DateMapper.form_to_datetime64(
                        getattr(self, prefix + 'year' + postfix).data,
                        getattr(self, prefix + 'month' + postfix).data,
                        getattr(self, prefix + 'day' + postfix).data)
                    if not date:
                        getattr(self, prefix + 'day' + postfix).errors.append(
                            _('not a valid date'))
                        valid = False
                    else:
                        dates[prefix + postfix.replace('_', '')] = date

        # Check for valid date combination e.g. begin not after end
        if valid:
            for prefix in ['begin', 'end']:
                if prefix + '_from' in dates and prefix + '_to' in dates:
                    if dates[prefix + '_from'] > dates[prefix + '_to']:
                        field = getattr(self, prefix + '_day_from')
                        field.errors.append(
                            _('First date cannot be after second.'))
                        valid = False
        if valid and 'begin_from' in dates and 'end_from' in dates:
            field = getattr(self, 'begin_day_from')
            if len(dates) == 4:  # All dates are used
                if dates['begin_from'] > dates['end_from'] or dates[
                        'begin_to'] > dates['end_to']:
                    field.errors.append(
                        _('Begin dates cannot start after end dates.'))
                    valid = False
            else:
                first = dates['begin_to'] if 'begin_to' in dates else dates[
                    'begin_from']
                second = dates['end_from'] if 'end_from' in dates else dates[
                    'end_to']
                if first > second:
                    field.errors.append(
                        _('Begin dates cannot start after end dates.'))
                    valid = False
        return valid
Ejemplo n.º 26
0
    def validate (self):
        if self.url.data.startswith("http://") == False and self.url.data.startswith("https://") == False :
            self.url.data = "http://" + self.url.data

        if not FlaskForm.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        #fliter for empty and duplicate tags
        stripped = [t.strip() for t in self.tags.data.split(',')]
        not_empty = [tag for tag in stripped if tag]
        tagset = set(not_empty)
        self.tags.data = ",".join(tagset)

        return True
Ejemplo n.º 27
0
    def validate(self):
        """
        Checks if user exists already (by email)

        :return: If the user exists already, return False, else True
        """
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        user = User.query.filter_by(email=self.email.data).first()

        if user:
            self.email.errors.append("This email is already taken.")
            return False

        return True
Ejemplo n.º 28
0
    def hidden_tag_without(self, *exclude_fields):
        """ Return the hidden fields for this form, excluding the fields listed in
            `exclude_fields`

            We use this to render all the hidden fields in the form except for the
            CSRF token, for reasons which are currently unclear to me.
        """
        fields = [
            getattr(self, f)
            if isinstance(f, string_types) and hasattr(self, f) else f
            for f in exclude_fields
        ]
        keep_fields = [
            f for f in self
            if isinstance(f.widget, HiddenInput) and f not in fields
        ]
        return FlaskForm.hidden_tag(self, *keep_fields)
Ejemplo n.º 29
0
def validate_location(form):
    '''Overrides the default validation for the form
    by running it first, then ensuring that the location
    and participant are not both empty for an incident
    form'''
    result = FlaskForm.validate(form)
    if not result:
        return result

    if not form.participant.data and not form.location.data:
        form.location.errors.append(
            _('Participant and location cannot both be empty'))
        form.participant.errors.append(
            _('Participant and location cannot both be empty'))
        return False

    return True
Ejemplo n.º 30
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        proizvod = Proizvod.query.get(self.proizvod_id.data)
        if proizvod.kolicina < self.promijenjena_kolicina.data:
            self.promijenjena_kolicina.errors.append(
                'Nema dovoljno artikla na stanju')
            return False

        tvrtka = Tvrtka.query.filter_by(name=self.name.data).first()
        if tvrtka is None:
            self.name.errors.append('Tvrtka ne postoji')
            return False
        else:
            return True
Ejemplo n.º 31
0
    def validate(self):
        # validate form submission
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        # try to get valid user
        user = User.query.filter_by(username=self.username.data).first()
        if user is None:
            self.username.errors.append('Unknown username')
            return False
        if not user.check_password(self.password.data):
            self.password.errors.append('Invalid password')
            return False

        self.user = user
        return True
Ejemplo n.º 32
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        user = auth_get_user_by_email(self.email.data)
        if user:
            self.password.errors.append('Email already registered')
            return False

        if len(self.password.data) < 8:
            self.password.errors.append(
                'Password should be at least 8 characters long')
            return False

        self.user = auth_add_user(self.email.data, self.password.data)
        return True
Ejemplo n.º 33
0
    def validate(self):
        if not FlaskForm.validate(self):
            return False
        if self.name.data and self.password.data and self.role.data:
            from peerplaysbase.account import PasswordKey
            pkey = PasswordKey(self.name.data, self.password.data, self.role.data)
            self.privateKey.data = pkey.get_private_key()

        if self.privateKey.data:
            try:
                Node().validateAccount(self.privateKey.data),
                return True
            except Exception:
                self.privateKey.errors.append("No account connected to this private key")
                return False
        else:
            return False
Ejemplo n.º 34
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        account = get_account(self.email.data)

        if account is None:
            self.email.errors.append('This email is not registered.')
            return False

        if not account.check_password(self.password.data):
            self.password.errors.append('Incorrect password.')
            return False

        self.account = account
        return True
Ejemplo n.º 35
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        user = Users.query.filter_by(usersname=self.username.data).first()
        if user:
            self.email.errors.append('Email already taken')
            return False

        email = Users.query.filter_by(email=self.email.data).first()
        if email:
            self.email.errors.append('Account already created with this email')
            return False

        self.user = user
        return True
Ejemplo n.º 36
0
    def validate(self):
        if not self.url.data.startswith("http://") or \
            self.url.data.startswith("https://"):
            self.url.data = "http://" + self.url.data

        if not Form.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        #filter out empty and duplicates tag names
        stripped = [t.strip() for t in self.tags.data.split(',')]
        not_empty = [tag for tag in stripped if tag]
        tagset = set(not_empty)
        self.tags.data = ",".join(tagset)
        return True
Ejemplo n.º 37
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        user = User.query.filter_by(username=self.username.data).first()
        if user:
            self.username.errors.append(gettext('Username already registered'))
            return False

        user = User.query.filter_by(email=self.email.data).first()
        if user:
            self.email.errors.append(gettext('Email already registered'))
            return False

        self.user = user
        return True
Ejemplo n.º 38
0
    def validate(self):
        self.user = None
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        user = User.get_user(self.username.data)
        if user is None:
            self.username.errors.append('Unknown username')
            return False

        if not user.check_password(self.password.data):
            self.password.errors.append('Invalid password')
            return False

        self.user = user
        return True
Ejemplo n.º 39
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        user = Users.query.filter_by(
            email=self.email.data
        ).first()

        if user:
            if not check_password_hash(user.password, self.password.data):
                self.password.errors.append('Incorrect email or password')
                return False
            return True
        else:
            self.password.errors.append('Incorrect email or password')
            return False
Ejemplo n.º 40
0
    def validate(self):
        if not (self.url.data.startswith('http://')
                or self.url.data.startswith('https://')):
            self.url.data = 'http://' + self.url.data

        if not FlaskForm.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        stripped = [t.strip() for t in self.tags.data.split(',')]
        not_empty = [tag for tag in stripped if tag]
        tag_set = set(not_empty)
        self.tags.data = ','.join(tag_set)

        return True
Ejemplo n.º 41
0
    def validate(self):
        # Python 3 use super().validate()
        # Validate with the original validators first
        if not FlaskForm.validate(self):
            return False

        result = True

        # With snmp version 2 community should be set
        if self.snmp_version.data == '2' and self.community.data == '':
            self.community.errors.append('Community cannot be empty!')
            result = False

        if self.snmp_version.data == '3':
            # With snmp version 3 security level and username should be always set
            if self.security_username.data == '' or self.security_level.data == 'Choose...':
                self.security_level.errors.append(
                    'Security Username and/or Security Level cannot be empty!')
                self.security_username.errors.append(
                    'Security Username and/or Security Level cannot be empty!')
                result = False
            # With snmp version 3 and auth without priv auth protocol and auth password should be set
            if self.security_level.data == 'auth_without_privacy':
                if self.auth_protocol.data == 'Choose...' or self.auth_password.data == '':
                    self.auth_password.errors.append(
                        'With Auth without Privacy, Auth Prot and/or Auth Pwd cannot be empty'
                    )
                    self.auth_protocol.errors.append(
                        'With Auth without Privacy, Auth Prot and/or Auth Pwd cannot be empty'
                    )
                    result = False
            # With snmp version 3 and auth with priv everything should be set
            if self.security_level.data == 'auth_with_privacy':
                if self.auth_protocol.data == 'Choose...' or self.auth_password.data == '' or \
                        self.privacy_protocol.data == 'Choose...' or self.privacy_password.data == '':
                    self.auth_password.errors.append(
                        'With Auth with Privacy, No Field can be empty')
                    self.auth_protocol.errors.append(
                        'With Auth with Privacy, No Field can be empty')
                    self.privacy_protocol.errors.append(
                        'With Auth with Privacy, No Field can be empty')
                    self.privacy_password.errors.append(
                        'With Auth with Privacy, No Field can be empty')
                    result = False

        return result
Ejemplo n.º 42
0
 def validate(self):
     rv = FlaskForm.validate(self)
     if not rv:
         return False
     import requests
     req_string = "https://www.instagram.com/%s"
     req = requests.get(req_string % (self.insta_username.data))
     if req.status_code != 200:
         self.insta_username.errors.append('User %s does not exist' %
                                           self.insta_username.data)
         return False
     for page in self.pages.data:
         req = requests.get(req_string % (page))
         if req.status_code != 200:
             self.pages.errors.append('Page %s does not exist' % page)
             return False
     return True
Ejemplo n.º 43
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        if self.start_date.data and self.end_date.data:
            start_date, _ = parseDateAccuracy(self.start_date.data)
            end_date, _ = parseDateAccuracy(self.end_date.data)

            if end_date < start_date:
                self.end_date.errors.append(
                    'End date is before the start date')

        if self.errors:
            return False

        return True
Ejemplo n.º 44
0
 def validate(self):
     rv = FlaskForm.validate(self)
     if not rv:
         return False
     if self.action.data not in ('edit', 'new'):
         return False
     has_error = False
     if self.action.data in ('edit', 'new'):
         if (not isinstance(self.name.data, string_types)) or not re.search(r'[A-Za-z0-9]', self.name.data):
             self.name.errors.append(word("The name must be filled in."))
             has_error = True
         if (not isinstance(self.method.data, string_types)) or self.method.data not in ('referer', 'ip', 'none'):
             self.name.errors.append(word("You must select an option."))
             has_error = True
     if has_error:
         return False
     return True
Ejemplo n.º 45
0
    def validate(self):
        if not FlaskForm.validate(self):
            return False

        # Cannot allow this Organization name, because it would cause issues on backend
        if self.organization_name.data == 'global':
            self.organization_name.errors.append(
                'Cannot allow this Organization name for secret reasons, shush.'
            )
            return False

        # TODO: remove these uniqueness checks after introduction of unique constraint
        # in ETCD storage class on backend
        client = get_service_client()
        # Check if organization exists on backend
        response = client.organization.list()
        if response.status > 200:
            self.organization_name.errors.append(
                'Can not contact backend at this time.')
            return False
        organizations = response.data
        organization_names = [org['name'] for org in organizations]
        organization_namespaces = [o['namespace'] for o in organizations]
        if self.organization_name.data in organization_names or slugify(
                self.organization_name.data) in organization_namespaces:
            self.organization_name.errors.append(
                'Organization {} already exists.'.format(
                    self.organization_name.data))
            return False

        # Check if e-mail and username exists on backend
        response = client.user.list()
        if response.status > 200:
            self.email.errors.append('Can not contact backend at this time.')
            return False
        users = response.data
        user_emails = [u['email'] for u in users if 'email' in u]
        if self.email.data in user_emails:
            self.email.errors.append('This e-mail is already registered.')
            return False
        user_usernames = [u['username'] for u in users]
        if self.email.data in user_usernames:
            self.email.errors.append('This username is already registered.')
            return False

        return True
Ejemplo n.º 46
0
    def validate(self):
        if not BaseForm.validate(self):
            return False

        if self.nickname.data == self.original_nickname:
            return True

        if self.nickname.data != User.make_valid_nickname(self.nickname.data):
            self.nickname.errors.append(
                'This nickname has invalid characters. Please use letters, numbers, dots and underscores only')
            return False

        usr = User.query.filter_by(nickname=self.nickname.data).first()
        if usr:
            self.nickname.errors.append('This nickname is already in use. Please choose another one')
            return False
        return True
Ejemplo n.º 47
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        if not is_safe_url(self.next.data):
            return False

        user = db.session.query(User).filter_by(
            first_name=self.first_name.data,
            last_name=self.last_name.data).one_or_none()
        if user is None:
            flash('''Such user doesn't exist''', 'danger')
            return False

        self.user = user
        return True
Ejemplo n.º 48
0
	def validate(self):
		validInput = FlaskForm.validate(self)
		if not validInput:
			return False

		accName  = self.accName.data
		password = self.password.data

		if self.accType.data == 'FlatAcc':
			accQuery = "SELECT account.acc_name, account.owner_name, account.flat_id, society.society_name, society.society_id FROM account \
						INNER JOIN flat ON account.flat_id=flat.flat_id \
						INNER JOIN wing ON flat.wing_id=wing.wing_id \
						INNER JOIN society ON wing.society_id=society.society_id \
						WHERE acc_name = '%s' && acc_pass = '******'" % (accName, password)

		# ADMIN TABLE HAS A PASSWORD FIELD, BUT WE ARE CHECKING PASSWORD FROM ACCOUNT TABLE
		elif self.accType.data == 'AdminAcc':
			accQuery = 'SELECT acc_name, society_id, resident_id \
			FROM admin \
			WHERE acc_name="%s" && admin_pass = "******"' % (accName, password)

		CURSOR.execute(accQuery)
		if CURSOR.rowcount <= 0:
			flash('INVALID LOGIN DETAILS')
			return False

		currUser = CURSOR.fetchone()

		if self.accType.data == 'FlatAcc':
			session['mainPage'] = '/dashboard'
			session['accName']     = currUser[0]
			session['ownerName']   = currUser[1]
			session['flatId']      = currUser[2]
			session['societyName'] = currUser[3]
			session['societyId']   = currUser[4]
		else:
			session['mainPage'] = '/admin'
			session['accName']     = currUser[0]
			session['societyId']   = currUser[1]

			societyAdminQuery = "SELECT society_name FROM society WHERE society_id=%d" % (session['societyId'])
			CURSOR.execute(societyAdminQuery)
			session['societyName'] = CURSOR.fetchone()[0]
			session['ownerName']   = currUser[0]

		return True
Ejemplo n.º 49
0
 def validate(self):
     rv = FlaskForm.validate(self)
     print(projectID)
     if not rv:
         return False
     if int(projectID)!=0:
         project1 = Project.query.get_or_404(int(projectID))
         project2 = Project.query.filter_by(name=self.name.data,version=self.version.data).first()
         if project2 and (project1.name!=self.name.data or project1.version!=self.version.data):
             self.name.errors.append('Mobile project was existed with %s-%s'%(self.name.data,self.version.data))
             return False
     else:
         project = Project.query.filter_by(name=self.name.data,version=self.version.data).first()
         if project:
             self.name.errors.append('Mobile project was existed with %s-%s'%(self.name.data,self.version.data))
             return False
     return True
Ejemplo n.º 50
0
 def validate(self):
     rv = FlaskForm.validate(self)
     if not rv:
         return False
     if self.action.data not in ('edit', 'new'):
         return False
     has_error = False
     if self.action.data in ('edit', 'new'):
         if type(self.name.data) not in (str, unicode) or not re.search(r'[A-Za-z0-9]', self.name.data):
             self.name.errors.append(word("The name must be filled in."))
             has_error = True
         if type(self.method.data) not in (str, unicode) or self.method.data not in ('referer', 'ip', 'none'):
             self.name.errors.append(word("You must select an option."))
             has_error = True
     if has_error:
         return False
     return True
Ejemplo n.º 51
0
def update_materia(id_materia):
    rm = RepositorioMateria()
    rc = RepositorioCurso()
    if request.method == "GET":
        cursos = rc.get_all()
        materia = rm.get_one(int(id_materia))
        if not materia:
            return "Error: materia no encontrada. id_materia: " + str(
                id_materia)
        form = FlaskForm()
        return render_template("nueva_materia.html",
                               mensaje=None,
                               form=form,
                               materia=materia,
                               cursos=cursos)
    else:
        # Capturar los datos del request
        idm = request.form["id_materia"]
        nombre = request.form["nombre"]
        id_curso = request.form["curso"]
        docente = request.form["docente"]
        mail = request.form["mail"]
        if request.form.get("sticky"):
            sticky = True
        else:
            sticky = False
        if request.form.get("cambiar_logo"):
            logo = request.form["logo"]
        else:
            logo = None
        rc = RepositorioCurso()
        curso = rc.get_one(id_curso)
        materia = Materia(idm, nombre, curso, logo, sticky, docente, mail)

        #HACER EL UPDATE
        if materia.logo:
            resultado = rm.update(materia)
        else:
            resultado = rm.update(materia, cambiar_logo=False)
        if resultado:
            mensaje = "Datos de la materia modificados"
        else:
            mensaje = "Error al modificar los datos de la materia"
        #Redirigir a cursos:
        return redirect(url_for('materias', mensaje=mensaje))
Ejemplo n.º 52
0
    def validate(self):
        """
        custom validation method
        :return: boolean
        """
        result = True

        if not FlaskForm.validate(self):
            result = False

        if not self.comm.data and not self.extcomm.data and not self.larcomm.data:
            err_message = "At last one of those values could not be empty"
            self.comm.errors.append(err_message)
            self.larcomm.errors.append(err_message)
            self.extcomm.errors.append(err_message)
            result = False

        return result
Ejemplo n.º 53
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        try:
            participant = Participant.get(
                Participant.Email == self.Email.data.lower().strip())
            print(participant.Name, self.Name.data)
            if participant.Name != self.Name.data.strip():
                self.Name.errors.append(
                    'This name / email combination has already been used, contact [email protected] for help'
                )
                return False
            else:
                return True
        except peewee.DoesNotExist:
            return True
Ejemplo n.º 54
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        user = User.query.filter_by(email=self.email.data).first()

        if user is not None:
            error = 'Email already in use'
            self.email.errors.append(error)
            print("ERROR: %s" % error)
            return False

        user = User(username=self.username.data, email=self.email.data)
        user.password = self.password.data

        self.user = user
        return True
Ejemplo n.º 55
0
    def validate(self):
        # check default validation
        if not FlaskForm.validate(self):
            return False

        # check nested forms
        for t in self.target_set:
            if not t.form.validate():
                error_fields = ','.join(t.form.errors.keys())
                self.target_set.errors.append({
                    'target':
                    t.name,
                    'message':
                    'Invalid target ' + error_fields
                })
                return False

        return True
Ejemplo n.º 56
0
    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        user = User.get_user(self.username.data)
        if user and user.username.lower() != g.user.username.lower():
            self.username.errors.append('Username already in use')
            return False

        if self.password.data:
            if self.old_password.data == '':
                self.old_password.errors.append('Please enter your old password')
                return False
            elif not user.check_password(self.old_password.data):
                self.old_password.errors.append('Incorrect password')
                return False

        return True
Ejemplo n.º 57
0
 def hidden_tag(self, *args, **kwargs):
     self.form_name.data = self._form_name
     return FlaskForm.hidden_tag(self, *args, **kwargs)
Ejemplo n.º 58
0
 def is_submitted(self):
     return FlaskForm.is_submitted(self) and request.form.get("form_name") == self._form_name
Ejemplo n.º 59
0
 def __init__(self, *args, **kwargs):
     self._form_name = type(self).__name__
     FlaskForm.__init__(self, *args, **kwargs)
Ejemplo n.º 60
0
 def __init__(self, default_license_id='CC BY-SA 3.0', default_language='en', **kwargs):
     kwargs.setdefault('license_choice', default_license_id)
     kwargs.setdefault('language', default_language)
     FlaskForm.__init__(self, **kwargs)