def mass_delete(self): items_list = self.request.POST.getall('selected_item') primary_keys = [pk_list_to_dict(json.loads(item)) for item in items_list] objects = self.crud.read(*primary_keys) try: if hasattr(objects, 'delete'): object_names = [escape(x.__repr__() or '') for x in objects] objects.delete() else: object_names = [escape(objects.__repr__() or ''), ] self.request.dbsession.delete(objects) except (NoResultFound, KeyError): raise HTTPNotFound except SacrudMessagedException as e: self.flash_message(e.message, status=e.status) except Exception as e: transaction.abort() logging.exception("Something awful happened!") raise e transaction.commit() self.flash_message(_ps("You delete the following objects:")) self.flash_message("<br/>".join(object_names)) return HTTPFound( location=self.request.route_url(PYRAMID_SACRUD_LIST, table=self.tname))
def mass_delete_view(self): items_list = self.request.POST.getall('selected_item') primary_keys = [ pk_list_to_dict(json.loads(item)) for item in items_list ] objects = self.context.crud.read(*primary_keys) try: if hasattr(objects, 'delete'): object_names = [escape(x.__repr__() or '') for x in objects] objects.delete() else: object_names = [ escape(objects.__repr__() or ''), ] self.request.dbsession.delete(objects) except (NoResultFound, KeyError): raise HTTPNotFound except SacrudException as e: self.flash_message(e.message, status=e.status) except Exception as e: transaction.abort() logging.exception("Something awful happened!") raise e transaction.commit() self.flash_message(_ps("You delete the following objects:")) [self.flash_message(obj) for obj in object_names] return self.list_view_response()
def game_add(context, request): team_a = [escape(s) for s in request.params['team_a'].split(',')] team_b = [escape(s) for s in request.params['team_b'].split(',')] try: score_a = int(request.params['score_a']) score_b = int(request.params['score_b']) except ValueError: return Response(body='Invalid score value!', status='406 Not Acceptable') if score_a < 0 or score_b < 0: return Response(body='Score may not be negative!', status='406 Not Acceptable') for p in (team_a + team_b): if p == "": return Response(body='Player name may not be empty!', status='406 Not Acceptable') # Check if players on each team are unique for player_a in team_a: if player_a in team_b: return Response( body='Player {} appears in both teams!'.format(player_a), status='406 Not Acceptable') game = get_game(context, request.matchdict['game']) game.add_match([team_a, team_b], [score_a, score_b]) log.info("Added match %s", str(game.matches[-1])) return Response(status='200 OK')
def add_link(match): word = match.group(1) exists = request.dbsession.query(models.Page).filter_by(name=word).all() if exists: view_url = request.route_url('view_page', pagename=word) return '<a href="%s">%s</a>' % (view_url, escape(word)) else: add_url = request.route_url('add_page', pagename=word) return '<a href="%s">%s</a>' % (add_url, escape(word))
def login_failure(self, message=None): if message: msg = '<strong>Error:</strong> Sorry, login failed: {0}'.format(escape(message)) else: msg = '<strong>Error:</strong> Sorry, login failed.' self.session.flash(msg, queue='danger') return HTTPFound(location=self.request.route_path('sign_in'))
def login_success(self, login_id, email=None, name=None, openid=None, local=False): self.session.invalidate() # clear session user = self.collection.find_one(dict(login_id=login_id)) if user is None: LOGGER.warn("new user: %s", login_id) user = self.add_user(login_id=login_id, email=email) subject = 'Phoenix: New user {} logged in on {}'.format(user['name'], self.request.server_name) message = 'Please check the activation of the user {} on the Phoenix host {}.'.format( user['name'], self.request.server_name) self.send_notification(email, subject, message) if local: user['group'] = Admin user['last_login'] = datetime.now() user['openid'] = openid or '' user['name'] = name or 'Guest' self.collection.update({'login_id': login_id}, user) self.session.flash("Hello <strong>{0}</strong>. Welcome to Phoenix.".format(escape(name)), queue='info') if user.get('group') == Guest: msg = """ <strong>Warning:</strong> You are a member of the <strong>Guest</strong> group. You are only allowed to submit processes <strong>without access restrictions</strong>. """ self.session.flash(msg, queue='warning') else: generate_access_token(self.request.registry, userid=user['identifier']) headers = remember(self.request, user['identifier']) return HTTPFound(location=self.request.route_path('home'), headers=headers)
def make_selected_action(self): selected_action = self.request.POST.get('selected_action') items_list = None try: items_list = self.request.POST.getall('selected_item') except AttributeError: items_list = self.request.POST.get('selected_item') if selected_action == 'delete': obj_list = [] for item in items_list: pk_list = json.loads(item) pk = pk_list_to_dict(pk_list) try: obj = self.crud.delete(pk) obj_list.append(obj['name']) except (NoResultFound, KeyError): raise HTTPNotFound except SacrudMessagedException as e: self.flash_message(e.message, status=e.status) except Exception as e: transaction.abort() logging.exception("Something awful happened!") raise e transaction.commit() self.flash_message(_ps("You delete the following objects:")) self.flash_message("<br/>".join( [escape(x or '') for x in obj_list])) return HTTPFound( location=self.request.route_url('sa_list', table=self.tname))
def sa_add(self): action = self.request.matched_route.name bc = breadcrumbs(self.tname, get_table_verbose_name(self.table), action, self.pk) dbsession = self.request.dbsession try: obj = get_obj(dbsession, self.table, self.pk) except (NoResultFound, KeyError): raise HTTPNotFound form = SacrudForm(obj=obj, dbsession=dbsession, request=self.request, table=self.table)() def options_for_response(form): return dict( form=form.render(), pk=self.pk, obj=obj, breadcrumbs=bc ) if 'form.submitted' in self.request.params: controls = self.request.POST.items() pstruct = peppercorn.parse(controls) if '__formid__' in pstruct: try: deserialized = form.validate_pstruct(pstruct).values() except deform.ValidationFailure as e: return options_for_response(e) data = {k: preprocessing_value(v) for d in deserialized for k, v in d.items()} else: # if not peppercon format data = pstruct try: if action == PYRAMID_SACRUD_UPDATE: obj = self.crud.update(self.pk, data) flash_action = 'updated' else: obj = self.crud.create(data) flash_action = 'created' name = obj.__repr__() dbsession.flush() except SacrudMessagedException as e: self.flash_message(e.message, status=e.status) return self.get_response(options_for_response(form), SACRUD_EDIT_TEMPLATE) except Exception as e: transaction.abort() logging.exception("Something awful happened!") raise e transaction.commit() self.flash_message(_ps( u"You ${action} object of ${name}", mapping={'action': flash_action, 'name': escape(name or '')} )) return HTTPFound( location=self.request.route_url(PYRAMID_SACRUD_LIST, table=self.tname)) return self.get_response(options_for_response(form), SACRUD_EDIT_TEMPLATE)
def filter_escaped(x, y): """ """ return escape(x)
def make_simple_pkg_info(name, text="", pkgver=None, hash_type=None, pypiserial=None, requires_python=None): class ret: hash_spec = "" if requires_python: requires_python = ' data-requires-python="%s"' % escape( requires_python) else: requires_python = '' if pkgver is not None: assert not text if hash_type and "#" not in pkgver: hv = (pkgver + str(pypiserial)).encode("ascii") hash_value = getattr(hashlib, hash_type)(hv).hexdigest() ret.hash_spec = "%s=%s" % (hash_type, hash_value) pkgver += "#" + ret.hash_spec text = '<a href="../../{name}/{pkgver}"{requires_python}>{pkgver}</a>'.format( name=name, pkgver=pkgver, requires_python=requires_python) elif text and "{md5}" in text: text = text.format(md5=getmd5(text)) elif text and "{sha256}" in text: text = text.format(sha256=getsha256(text)) return ret, text
def escape_output(output): if output: if isinstance(output, list): return list(map(escape, output)) else: return escape(output) else: return output
def escape_output(output): if output: if isinstance(output, list): return map(escape, output) else: return escape(output) else: return output
def generate_twitcher_token(self): try: generate_access_token(self.request.registry, userid=self.userid) except Exception as err: self.session.flash('Could not refresh token: {}'.format(escape(err.message)), queue="danger") else: self.session.flash('Twitcher token was updated.', queue="success") return HTTPFound(location=self.request.route_path('profile', userid=self.userid, tab='twitcher'))
def delete_view(self): if not hasattr(self.context, 'obj'): raise HTTPNotFound self.context.dbsession.delete(self.context.obj) self.commit() self.flash_message( _ps("You have removed object of ${name}", mapping={'name': escape(text_type(self.context.obj) or '')})) return self.list_view_response()
def format_data(data, request=None, relative_to=None, max_array_length=3): if hasattr(data, '__len__'): return format_array(data, max_array_length) elif np.issubdtype(type(data), np.number): return format_number(data) elif isinstance(data, core.Halo): return format_halo(data, request, relative_to) else: return escape(repr(data))
def index_service(self): service_id = self.request.matchdict.get('service_id') service = self.request.catalog.get_record_by_id(service_id) settings = self.request.registry.settings index_thredds.delay(url=service.source, maxrecords=settings.get('solr.maxrecords'), depth=settings.get('solr.depth')) msg = 'Start Indexing of Service {0}. Reload page to see status ...'.format(escape(service.title)) self.session.flash(msg, queue="info") return HTTPFound(location=self.request.route_path(self.name, tab="index"))
def sa_delete(self): try: obj = self.crud.delete(self.pk) transaction.commit() except (NoResultFound, KeyError): raise HTTPNotFound self.flash_message(_ps("You have removed object of ${name}", mapping={'name': escape(obj['name'] or '')})) return HTTPFound( location=self.request.route_url(PYRAMID_SACRUD_LIST, table=self.tname))
def sa_delete(self): try: obj = self.crud.delete(self.pk) transaction.commit() except (NoResultFound, KeyError): raise HTTPNotFound self.flash_message( _ps("You have removed object of ${name}", mapping={'name': escape(obj['name'] or '')})) return HTTPFound( location=self.request.route_url('sa_list', table=self.tname))
def edit_form_post_view(self): form = self.context.form(self.request) params = {'form': form.render()} def get_reponse(form=None): if form: params['form'] = form return render_to_response(self.context.renderer, params, request=self.request) if 'form.submitted' in self.request.params: controls = self.request.POST.items() pstruct = peppercorn.parse(controls) # Validate form try: deserialized = form.validate_pstruct(pstruct).values() except deform.ValidationFailure as e: return get_reponse(e.render()) data = { k: preprocessing_value(k, v, form) # TODO: optimize it for d in deserialized for k, v in d.items() } # Update object try: if self.context.obj: obj = self.context.crud._add(self.context.obj, data) flash_action = 'updated' else: obj = self.context.crud.create(data) flash_action = 'created' name = obj.__repr__() self.context.dbsession.flush() except SacrudException as e: self.flash_message(e.message, status=e.status) return get_reponse() except Exception as e: self.abort() logging.exception("Something awful happened!") raise e self.commit() # Make response self.flash_message( _ps(u"You ${action} object of ${name}", mapping={ 'action': flash_action, 'name': escape(name or '') })) return self.list_view_response() return get_reponse()
def error_message(context, request): """ Error message filter """ if not isinstance(context, (set, list, tuple)): context = (context, ) errors = [] for err in context: if isinstance(err, Exception): err = '%s: %s' % (err.__class__.__name__, escape(str(err), True)) errors.append(err) return {'errors': errors}
def generate_esgf_slcs_token(self): """ Update ESGF slcs token. """ client = ESGFSLCSClient(self.request) if client.get_token(): try: client.refresh_token() except Exception as err: self.session.flash('Could not refresh token: {}'.format(escape(err.message)), queue="danger") else: self.session.flash('ESGF token was updated.', queue="success") return HTTPFound(location=self.request.route_path('profile', userid=self.userid, tab='esgf_slcs')) else: try: auth_url = client.authorize() except Exception as err: self.session.flash('Could not retrieve token: {}'.format(escape(err.message)), queue="danger") return HTTPFound(location=self.request.route_path('profile', userid=self.userid, tab='esgf_slcs')) else: return HTTPFound(location=auth_url)
def error_message(context, request): """ Error message filter """ if not isinstance(context, (set, list, tuple)): context = (context,) errors = [] for err in context: if isinstance(err, Exception): err = '%s: %s'%( err.__class__.__name__, escape(str(err), True)) errors.append(err) return {'errors': errors}
def loading(self): result = task_result(self.session.get('task_id')) if result.ready(): if result.get().get('status') == 'Success': self.session.flash('ESGF logon was successful.', queue='success') return self.callback() else: msg = '<strong>Error:</strong> ESGF logon failed: {0}.'.format( escape(result.get().get('message'))) self.session.flash(msg, queue='danger') return HTTPFound(location=self.request.route_path('esgflogon')) return {}
def edit_form_post_view(self): form = self.context.form(self.request) params = {'form': form.render()} def get_reponse(form=None): if form: params['form'] = form return render_to_response( self.context.renderer, params, request=self.request ) if 'form.submitted' in self.request.params: controls = self.request.POST.items() pstruct = peppercorn.parse(controls) # Validate form try: deserialized = form.validate_pstruct(pstruct).values() except deform.ValidationFailure as e: return get_reponse(e.render()) data = {k: preprocessing_value(k, v, form) # TODO: optimize it for d in deserialized for k, v in d.items()} # Update object try: if self.context.obj: obj = self.context.sacrud._add(self.context.obj, data) flash_action = 'updated' else: obj = self.context.sacrud.create(data) flash_action = 'created' name = obj.__repr__() self.context.dbsession.flush() except SacrudException as e: self.flash_message(e.message, status=e.status) return get_reponse() except Exception as e: self.abort() logging.exception("Something awful happened!") raise e self.commit() # Make response self.flash_message(_ps( u"You ${action} object of ${name}", mapping={'action': flash_action, 'name': escape(name or '')} )) return self.list_view_response() return get_reponse()
def matchmaking_view(context, request): game = get_game(context, request.matchdict['game']) all_games = [g.name for g in context.games.values()] pairings = [] players = [] if 'players' in request.params: player_names = [ escape(s) for s in request.params['players'].split(',') ] players = [game.players[p] for p in player_names if p in game.players] def make_pairing(t1): t2 = [p for p in players if p not in t1] quality = game.draw_probability(t1, t2) return {'team1': t1, 'team2': t2, 'quality': quality} # Calculate match quality for all team compositions for split in range(1, int(len(players) / 2)): for t1 in combinations(players, split): pairings.append(make_pairing(t1)) # Half-Half point with even players needs special handling, because otherwise we will generate # The same teams multiple times (e.g. AB vs CD and CD vs AB) halfside = list(combinations(players, int(len(players) / 2))) if len(players) % 2 == 0: halfside = halfside[:int(len(halfside) / 2)] for t1 in halfside: pairings.append(make_pairing(t1)) pairings.sort(key=lambda p: p['quality'], reverse=True) # Group painings by thresholds for display pairings_good = [p for p in pairings if p['quality'] > 0.4] pairings_ok = [ p for p in pairings if p['quality'] >= 0.1 and not p in pairings_good ] pairings_bad = [ p for p in pairings if not p in pairings_good and not p in pairings_ok ] return { 'game': game, 'all_games': all_games, 'players': players, 'pairings_good': pairings_good, 'pairings_ok': pairings_ok, 'pairings_bad': pairings_bad }
def mass_delete_view(self): items_list = self.request.POST.getall('selected_item') primary_keys = [pk_list_to_dict(json.loads(item)) for item in items_list] objects = self.context.sacrud.read(*primary_keys) try: if hasattr(objects, 'delete'): object_names = [escape(x.__repr__() or '') for x in objects] objects.delete() else: object_names = [escape(objects.__repr__() or ''), ] self.request.dbsession.delete(objects) except (NoResultFound, KeyError): raise HTTPNotFound except SacrudException as e: self.flash_message(e.message, status=e.status) except Exception as e: transaction.abort() logging.exception("Something awful happened!") raise e transaction.commit() self.flash_message(_ps("You delete the following objects:")) [self.flash_message(obj) for obj in object_names] return self.list_view_response()
def update_esgf_certs(self): client = ESGFSLCSClient(self.request) if client.get_token(): try: client.get_certificate() except Exception as err: self.session.flash('Could not update certificate: {}'.format(escape(err.message)), queue="danger") else: self.session.flash('ESGF certificate was updated.', queue="success") return HTTPFound(location=self.request.route_path('profile', userid=self.userid, tab='esgf_certs')) elif False: # TODO: update slcs token ... slcs does not work yet auth_url = client.authorize() return HTTPFound(location=auth_url) else: callback = self.request.route_path('profile', userid=self.userid, tab='esgf_certs') return HTTPFound(location=self.request.route_path('esgflogon', _query=[('callback', callback)]))
def render_control(self, name, **attrs): schema = self.schema field = schema.fields[name] if hasattr(field, 'options'): options = field.options else: options_attr = name + '_options' if hasattr(schema, options_attr): options = getattr(schema, options_attr) assert options # v2l = {v:l for (v,l) in options} v2l = {} for (v,l) in options: v2l[v] = l n2v = variabledecode.variable_encode(v2l.keys(), list_char=self.form.list_char, prepend=name, add_repetitions=False) checkboxes = [] class_ = 'checkbox-inline' if self.inline else 'checkbox' id = self.form_renderer.populate_input_id(name, **attrs) i = 0 checked_values = self._get_checked_values(name) for name, value in n2v.items(): label = v2l[value] check = u' checked="checked"' if value in checked_values else '' checkboxes.append(u""" <div class="%(class)s"> <label> <input type="checkbox" name="%(name)s" value="%(value)s" id="%(id)s"%(check)s> %(label)s </label> </div> """ % { 'id': '%s_%d' % (id, i), 'class': class_, 'name': name, 'value': escape(value), 'label': label, 'check': check, }) i += 1 return u"\n".join(checkboxes)
def login_success(self, login_id, provider=None, token=None): self.session.invalidate() # clear session user = self.collection.find_one(dict(login_id=login_id)) if user is None: LOGGER.warn("new user: {}".format(login_id)) user = self.add_user(login_id=login_id) if provider == 'local': user['group'] = Admin if provider == 'keycloak': user['token'] = token user['provider'] = provider user['last_login'] = datetime.now() self.collection.update({'login_id': login_id}, user) self.session.flash("Hello <strong>{0}</strong>. Welcome to Phoenix.".format(escape(login_id)), queue='info') if provider != 'keycloak': # generate_access_token(self.request.registry, userid=user['identifier']) pass headers = remember(self.request, user['identifier']) return HTTPFound(location=self.request.route_path('home'), headers=headers)
def process_form(self, form): try: controls = list(self.request.POST.items()) appstruct = form.validate(controls) result = esgf_logon.delay(authenticated_userid(self.request), appstruct.get('provider'), appstruct.get('username'), appstruct.get('password')) self.session['task_id'] = result.id except ValidationFailure as e: self.session.flash("Form validation failed.", queue='danger') return dict(form=e.render()) except Exception as e: msg = '<strong>Error:</strong> ESGF logon failed: {0}.'.format( escape(e.message)) self.session.flash(msg, queue='danger') return HTTPFound(location=self.request.route_path('esgflogon')) else: return HTTPFound( location=self.request.route_path('esgflogon_loading'))
def render_control(self, name, **attrs): inline = attrs.get('inline', self.inline) schema = self.schema field = schema.fields[name] try: options = field.options except AttributeError: try: options = getattr(schema, name + '_options') except AttributeError: pass assert options, "You have specify option" \ " by arg or schema." + name + "_options" selected_value = self.form.data.get(name, None) checkboxes = [] class_ = 'radio-inline' if inline else 'radio' id = attrs['id'] = self.form_renderer.populate_input_id(name, **attrs) i = 0 for value, label in options: check = u' checked' if value == selected_value else '' checkboxes.append(u""" <div class="%(class)s"> <label> <input type="radio" name="%(name)s" value="%(value)s" %(check)s> %(label)s </label> </div> """ % { 'id': '%s_%d' % (id, i), 'class': class_, 'name': name, 'value': escape(value), 'label': label, 'check': check, }) i += 1 return u"\n".join(checkboxes)
def login_success(self, login_id, email=None, name=None, openid=None, local=False): self.session.invalidate() # clear session user = self.collection.find_one(dict(login_id=login_id)) if user is None: LOGGER.warn("new user: %s", login_id) user = self.add_user(login_id=login_id, email=email) subject = 'Phoenix: New user {} logged in on {}'.format( user['name'], self.request.server_name) message = 'Please check the activation of the user {} on the Phoenix host {}.'.format( user['name'], self.request.server_name) self.send_notification(email, subject, message) if local: user['group'] = Admin user['last_login'] = datetime.now() user['openid'] = openid or '' user['name'] = name or 'Guest' self.collection.update({'login_id': login_id}, user) self.session.flash( "Hello <strong>{0}</strong>. Welcome to Fawkes.".format( escape(name)), queue='info') if user.get('group') == Guest: msg = """ <strong>Warning:</strong> You are a member of the <strong>Guest</strong> group. You are only allowed to submit processes <strong>without access restrictions</strong>. """ self.session.flash(msg, queue='warning') else: generate_access_token(self.request.registry, userid=user['identifier']) headers = remember(self.request, user['identifier']) return HTTPFound(location=self.request.route_path('home'), headers=headers)
class ESGFLogon(object): def __init__(self, request): self.request = request self.session = self.request.session if 'callback' in self.request.params: self.session['esgflogon_callback'] = self.request.params.get( 'callback') def appstruct(self): return {} def generate_form(self): submit_button = Button(name='submit', title='Submit', css_class='btn btn-success') return Form(schema=ESGFLogonSchema().bind(request=self.request), buttons=(submit_button, ), formid="esgflogon") def process_form(self, form): try: controls = self.request.POST.items() appstruct = form.validate(controls) result = esgf_logon.delay(authenticated_userid(self.request), appstruct.get('provider'), appstruct.get('username'), appstruct.get('password')) self.session['task_id'] = result.id except ValidationFailure, e: self.session.flash("Form validation failed.", queue='danger') return dict(form=e.render()) except Exception, e: msg = '<strong>Error:</strong> ESGF logon failed: {0}.'.format( escape(e.message)) self.session.flash(msg, queue='danger') return HTTPFound(location=self.request.route_path('esgflogon'))
def test(context, request): # should return false msg = 'Allow ./x? %s' % repr( view_execution_permitted(context, request, 'x')) return Response(escape(msg))
def test(context, request): # should return false msg = 'Allow ./x? %s' % repr(view_execution_permitted( context, request, 'x')) return Response(escape(msg))
def html_quote(s): if s is None: return '' return escape(str(s), 1)
def sa_add(self): bc = breadcrumbs(self.tname, get_table_verbose_name(self.table), 'sa_create') if self.pk: bc = breadcrumbs(self.tname, get_table_verbose_name(self.table), 'sa_update', id=self.pk) dbsession = self.request.dbsession try: obj = get_obj(dbsession, self.table, self.pk) except (NoResultFound, KeyError): raise HTTPNotFound form = SacrudForm(obj=obj, dbsession=dbsession, request=self.request, table=self.table)() def get_responce(form): return dict(form=form.render(), pk=self.pk, obj=obj, breadcrumbs=bc, pk_to_list=pk_to_list) if 'form.submitted' in self.request.params: controls = self.request.POST.items() pstruct = peppercorn.parse(controls) if '__formid__' in pstruct: try: deserialized = form.validate_pstruct(pstruct).values() except deform.ValidationFailure as e: return get_responce(e) data = { k: preprocessing_value(v) for d in deserialized for k, v in d.items() } else: # if not peppercon format data = pstruct try: if self.pk: obj = self.crud.update(self.pk, data) else: obj = self.crud.create(data) name = obj.__repr__() dbsession.flush() except SacrudMessagedException as e: self.flash_message(e.message, status=e.status) return get_responce(form) except Exception as e: transaction.abort() logging.exception("Something awful happened!") raise e transaction.commit() if self.pk: self.flash_message( _ps(u"You updated object of ${name}", mapping={'name': escape(name or '')})) else: self.flash_message( _ps("You created new object of ${name}", mapping={'name': escape(name or '')})) return HTTPFound( location=self.request.route_url('sa_list', table=self.tname)) return get_responce(form)
def hello_view(request): name = request.params.get('name', 'No Name') body = '<p>Hi %s, this <a href="/goto">redirects</a></p>' return Response(body % escape(name))
def render_amd_container(request, name, **kw): registry = request.registry opt =' '.join('data-%s="%s"'%(key, escape(val)) for key, val in kw.items()) return '<div ptah="%s" class="ptah-container" %s></div>'%(name, opt)
def hello_view(request): name = request.params.get('name', 'No Name') body = '<p>Hi %s, this <a href="/goto">redirects</a></p>' # pyramid.compat.escape to prevent Cross-Site Scripting (XSS) [CWE 79] return Response(body % escape(name))