示例#1
0
 def _convert_to_python(self, value, state):
     try:
         kajiki.TextTemplate(value)
     except:
         raise formencode.Invalid(_('Template not valid.'), value, state)
     return value
示例#2
0
 def validate_python(self, value, state):
     if not re.match('[a-zA-Z0-9_-]+$', value):
         raise formencode.Invalid(self.message('badFormat', state),
                                  value, state)
示例#3
0
 def validate(self, value, state=None):
     value = super(NeighborhoodAddProjectForm, self).validate(value, state)
     provider = plugin.ProjectRegistrationProvider.get()
     if not provider.phone_verified(c.user, c.project.neighborhood):
         raise formencode.Invalid(u'phone-verification', value, None)
     return value
示例#4
0
 def get_api(self, path):
     try:
         return self._operation_index[path]
     except KeyError:
         raise fe.Invalid('Unknown path: {}'.format(path), self._raw, None)
示例#5
0
 def validate_python(self, value, state):
     if value != authentication_token():
         msg = self.message('invalid_token', state)
         raise formencode.Invalid(msg, value, state)
示例#6
0
 def _to_python(self, value, state):
     session = DBSession()
     if not session.query(User).filter_by(email=value).all():
         raise formencode.Invalid('Username not found.', value, state)
     return value
 def _convert_to_python(self, value, _):
     try:
         return str(value).encode('ascii')
     except UnicodeError:
         raise formencode.Invalid('Invalid ascii string %s' % value, '',
                                  None)
示例#8
0
 def _to_python(self, value, state):
     from adhocracy import i18n
     if value in i18n.LOCALES:
         return value
     else:
         raise formencode.Invalid(_('Invalid locale choice'), value, state)
示例#9
0
 def _to_python(self, value, state):
     value = convertTime(value)
     if not value:
         raise fe.Invalid("Please enter a valid time in the format HH:MM.",
                          value, state)
     return value
 def _to_python(self, value, state):
     try:
         return Decimal(value)
     except DecimalException:
         raise formencode.Invalid('Please enter a number', value, state)
示例#11
0
 def validate_python(self, value, state, config):
     min_chars = config.auth.password_min_chars
     if len(value) < min_chars:
         raise formencode.Invalid(
             self.message('too_short', value, min_chars=min_chars), value,
             state)
示例#12
0
 def _to_python(self, value, state):
    try:
        crack.VeryFascistCheck(value.encode('utf-8'))
    except ValueError, e:
        raise formencode.Invalid("New password " + str(e), value, state)
def actions_duplicate(request):
    dbsession = DBSession()
    experiment = dbsession.query(Experiment).filter(
        Experiment.id == request.matchdict['eid']).first()
    if experiment:
        if request.method == 'POST':
            try:
                params = DuplicateSchema().to_python(request.params,
                                                     State(request=request))
                data = ExperimentIOSchema(include_schemas=[s for s in all_io_schemas if s != ExperimentIOSchema]).\
                    dump(experiment).data
                data = deepcopy(data)
                with transaction.manager:
                    dbsession.add(experiment)
                    new_experiment, errors = ExperimentIOSchema(include_schemas=[s for s in all_io_schemas
                                                                                 if s != ExperimentIOSchema]).\
                        load(data)
                    if errors:
                        raise formencode.Invalid(
                            '. '.join([
                                '%s: %s' %
                                (e['source']['pointer'], e['detail'])
                                for e in errors['errors']
                            ]), None, None)
                    for page in new_experiment.pages:
                        replace_questions(page, dbsession)
                    new_experiment.title = params['title']
                    new_experiment.owner = request.current_user
                    new_experiment.external_id = uuid.uuid1().hex,
                    new_experiment.status = 'develop'
                    dbsession.add(new_experiment)
                    dbsession.flush()
                    for latin_square in new_experiment.latin_squares:
                        fix_latin_square(latin_square,
                                         new_experiment.data_sets)
                    for page in new_experiment.pages:
                        for transition in page.next:
                            fix_transition(transition, new_experiment.pages)
                dbsession.add(new_experiment)
                raise HTTPFound(
                    request.route_url('experiment.view',
                                      eid=new_experiment.id))
            except formencode.Invalid as e:
                return {
                    'experiment':
                    experiment,
                    'crumbs': [{
                        'title': 'Experiments',
                        'url': request.route_url('dashboard')
                    }, {
                        'title':
                        experiment.title,
                        'url':
                        request.route_url('experiment.view', eid=experiment.id)
                    }, {
                        'title':
                        'Actions',
                        'url':
                        request.route_url('experiment.actions',
                                          eid=experiment.id)
                    }, {
                        'title':
                        'Duplicate',
                        'url':
                        request.route_url('experiment.actions.duplicate',
                                          eid=experiment.id)
                    }],
                    'errors':
                    e.error_dict if e.error_dict else {
                        'title': str(e)
                    },
                    'values':
                    request.params
                }
        return {
            'experiment':
            experiment,
            'crumbs': [{
                'title': 'Experiments',
                'url': request.route_url('dashboard')
            }, {
                'title':
                experiment.title,
                'url':
                request.route_url('experiment.view', eid=experiment.id)
            }, {
                'title':
                'Actions',
                'url':
                request.route_url('experiment.actions', eid=experiment.id)
            }, {
                'title':
                'Duplicate',
                'url':
                request.route_url('experiment.actions.duplicate',
                                  eid=experiment.id)
            }]
        }
    else:
        raise HTTPNotFound()
示例#14
0
 def _convert_to_python(self, value, state):
     __, mail_model = model.provider.query(model.MailModel, filters=dict(name=value))
     if mail_model:
         raise formencode.Invalid(_('Model with this name already created.'), value, state)
     return value
示例#15
0
 def _to_python(self, value, state):
     from allura import model as M
     user = M.User.by_username(value)
     if not user:
         raise fe.Invalid('Invalid username', value, state)
     return user
示例#16
0
 def result(value, state, func=func):
     try:
         return func(value)
     except (ValueError, TypeError) as e:
         raise formencode.Invalid(str(e), {}, value, state)
示例#17
0
 def _to_python(self, value, state):
     try:
         json.loads(value)
     except ValueError as e:
         raise fe.Invalid('Invalid JSON: ' + str(e), value, state)
     return value
示例#18
0
 def _to_python(self, value, state):
     if not isinstance(value, six.string_types):
         raise formencode.Invalid('Must be a string type', value, state)
     # this reverse a string or list...yah, I know, it looks funny
     return value[::-1]
示例#19
0
        def to_python(self, value, state):
            if old_data['repo_type'] != value:
                raise formencode.Invalid(_('Fork have to be the same '
                                           'type as original'), value, state)

            return value
示例#20
0
文件: forms.py 项目: lym/allura-git
 def to_python(self, kw, state):
     d = super(AddInactivePeriodForm, self).to_python(kw, state)
     if d['startdate'] > d['enddate']:
         raise formencode.Invalid(
             'Invalid period: start date greater than end date.', kw, state)
     return d
示例#21
0
    def store_project(self, current_user, is_create, selected_id, **data):
        """
        We want to create/update a project entity.
        """
        # Validate Unique Name
        new_name = data["name"]
        if len(new_name) < 1:
            raise ProjectServiceException("Invalid project name!")
        projects_no = dao.count_projects_for_name(new_name, selected_id)
        if projects_no > 0:
            err = {'name': 'Please choose another name, this one is used!'}
            raise formencode.Invalid("Duplicate Name Error", {},
                                     None,
                                     error_dict=err)
        started_operations = dao.get_operation_numbers(selected_id)[1]
        if started_operations > 0:
            raise ProjectServiceException(
                "A project can not be renamed while operations are still running!"
            )
        if is_create:
            current_proj = Project(new_name, current_user.id,
                                   data["description"])
            self.structure_helper.get_project_folder(current_proj)
        else:
            try:
                current_proj = dao.get_project_by_id(selected_id)
            except Exception as excep:
                self.logger.exception("An error has occurred!")
                raise ProjectServiceException(str(excep))
            if current_proj.name != new_name:
                self.structure_helper.rename_project_structure(
                    current_proj.name, new_name)
            current_proj.name = new_name
            current_proj.description = data["description"]
        # Commit to make sure we have a valid ID
        current_proj.refresh_update_date()
        self.structure_helper.write_project_metadata(current_proj)
        current_proj = dao.store_entity(current_proj)

        # Retrieve, to initialize lazy attributes
        current_proj = dao.get_project_by_id(current_proj.id)
        # Update share settings on current Project entity
        visited_pages = []
        prj_admin = current_proj.administrator.username
        if 'visited_pages' in data and data['visited_pages']:
            visited_pages = data['visited_pages'].split(',')
        for page in visited_pages:
            members = UserService.retrieve_users_except([prj_admin], int(page),
                                                        MEMBERS_PAGE_SIZE)[0]
            members = [m.id for m in members]
            dao.delete_members_for_project(current_proj.id, members)

        selected_user_ids = data["users"]
        if is_create and current_user.id not in selected_user_ids:
            # Make the project admin also member of the current project
            selected_user_ids.append(current_user.id)
        dao.add_members_to_project(current_proj.id, selected_user_ids)
        # Finish operation
        self.logger.debug("Edit/Save OK for project:" + str(current_proj.id) +
                          ' by user:' + current_user.username)
        return current_proj
示例#22
0
 def _to_python(self, value, state):
     users_q = model.Session.query(model.User).filter_by(username = value)
     if users_q.count() > 0:
         raise formencode.Invalid('That username already exists', value, state)
     else:
         return value
示例#23
0
 def get_operation(self, path, method):
     try:
         return self._operation_index[path][method.upper()]
     except KeyError:
         raise fe.Invalid('Unknown operation: {} {}'.format(method, path),
                          self._raw, None)
示例#24
0
 def validate_python(self, value, state):
     if value == None:
         raise formencode.Invalid('No such user', value, state)
示例#25
0
        def to_python(self, value, state):
            perms_update = OrderedSet()
            perms_new = OrderedSet()
            # build a list of permission to update and new permission to create

            #CLEAN OUT ORG VALUE FROM NEW MEMBERS, and group them using
            new_perms_group = defaultdict(dict)
            for k, v in value.copy().iteritems():
                if k.startswith('perm_new_member'):
                    del value[k]
                    _type, part = k.split('perm_new_member_')
                    args = part.split('_')
                    if len(args) == 1:
                        new_perms_group[args[0]]['perm'] = v
                    elif len(args) == 2:
                        _key, pos = args
                        new_perms_group[pos][_key] = v

            # fill new permissions in order of how they were added
            for k in sorted(map(int, new_perms_group.keys())):
                perm_dict = new_perms_group[str(k)]
                new_member = perm_dict.get('name')
                new_perm = perm_dict.get('perm')
                new_type = perm_dict.get('type')
                if new_member and new_perm and new_type:
                    perms_new.add((new_member, new_perm, new_type))

            for k, v in value.iteritems():
                if k.startswith('u_perm_') or k.startswith('g_perm_'):
                    member = k[7:]
                    t = {'u': 'user', 'g': 'users_group'}[k[0]]
                    if member == User.DEFAULT_USER:
                        if str2bool(value.get('repo_private')):
                            # set none for default when updating to
                            # private repo protects against form manipulation
                            v = EMPTY_PERM
                    perms_update.add((member, v, t))

            value['perms_updates'] = list(perms_update)
            value['perms_new'] = list(perms_new)

            # update permissions
            for k, v, t in perms_new:
                try:
                    if t is 'user':
                        self.user_db = User.query() \
                            .filter(User.active == True) \
                            .filter(User.username == k).one()
                    if t is 'users_group':
                        self.user_db = UserGroup.query() \
                            .filter(UserGroup.users_group_active == True) \
                            .filter(UserGroup.users_group_name == k).one()

                except Exception:
                    log.exception('Updated permission failed')
                    msg = self.message('perm_new_member_type', state)
                    raise formencode.Invalid(
                        msg,
                        value,
                        state,
                        error_dict=dict(perm_new_member_name=msg))
            return value
示例#26
0
 def validate_python(self, value, state):
     if value == None:
         raise formencode.Invalid('Invalid id', value, state)
示例#27
0
 def validate_python(self, value, state):
     if value != os.path.basename(value):
         raise formencode.Invalid(self.message('badPath', state), value,
                                  state)
示例#28
0
 def _to_python(self, value, state):
     value_bytes = h.really_unicode(value or '').encode('utf-8')
     if len(value_bytes) > self.max:
         raise fe.Invalid("Please enter a value less than %s bytes long." %
                          self.max, value, state)
     return value
示例#29
0
 def to_python(self, value, state):
     d = super(PasswordChangeBase, self).to_python(value, state)
     if d['pw'] != d['pw2']:
         raise formencode.Invalid('Passwords must match', value, state)
     return d
示例#30
0
 def _convert_to_python(self, value, state):
     query = DBSession.query(
         Storage.id).filter(Storage.name == value.strip())
     if query.count() > 0:
         raise formencode.Invalid('That name already exists', value, state)
     return value