def create_menu(endpoint): if not current_user.has_permission(code='admin'): return False menu = {'name': 'Admin', 'submenu': [], 'active': False} entries = [] if current_user.has_permission(code='manage-liquidsoap'): entries.append( ['admin.liquidsoap_manage', 'Liquidsoap-Manager', 'admin']) entries.append( ['admin.liquidsoap_config', 'Liquidsoap-Config', 'admin']) entries.append(['admin.stream_list', 'Streams', 'admin']) entries.append(['admin.relay_list', 'Relays', 'admin']) entries.append(['admin.user_list', 'Users', 'admin']) entries.append(['admin.log_list', 'Logs', 'admin']) entries.append(['admin.listener_list', 'Listeners', 'admin']) for entry in entries: active = endpoint == entry[0] menu['submenu'].append({ 'name': entry[1], 'url': url_for(entry[0]), 'active': (active) }) if active: menu['active'] = True return menu
def _editDomain(self, id=None): query = request.get_json() if id is None: domain = Domain() else: domain = Domain.query.get(id) for upstream in domain.upstreams: db.session.delete(upstream) for alias in domain.aliases: db.session.delete(alias) db.session.commit() uri = query['uri'] htpasswd = query.get('htpasswd') ssl_key = query.get('ssl_key') aliases = query.get('aliases', []) domain_controller = query.get('domain_controller') domain.upstreams = [] for upstreamInfo in query.get('upstreams', []): upstream = Upstream() upstream.ip = upstreamInfo['ip'] upstream.port = upstreamInfo['port'] upstream.port_ssl = upstreamInfo['port_ssl'] or None upstream.state = upstreamInfo['state'] domain.upstreams.append(upstream) domain.aliases = [] for aliasInfo in aliases: alias = Alias() alias.uri = aliasInfo['uri'] domain.aliases.append(alias) domain.domain_controller = None if domain_controller: domain_controller = DomainController.query.get( domain_controller['id']) domain.domain_controller = domain_controller domain.uri = uri domain.htpasswd = htpasswd domain.ssl_key = ssl_key if id is None: if current_user.has_permission( CreateDomainPermission, getattr(domain.domain_controller, 'id')) is False: return abort(403) else: if current_user.has_permission( EditDomainPermission, getattr(domain.domain_controller, 'id')) is False: return abort(403) db.session.add(domain) db.session.commit() return domain
def request_change_division(request_id): srp_request = Request.query.get_or_404(request_id) if not current_user.has_permission(PermissionType.review, srp_request) and\ current_user != srp_request.submitter: current_app.logger.warn(u"User '{}' does not have permission to change" u" request #{}'s division".format( current_user, srp_request.id)) abort(403) if srp_request.finalized: msg = (u"Cannot change request #{}'s division as it is in a finalized" u" state").format(srp_request.id) current_app.logger.info(msg) flash( u"Cannot change the division as this request is in a finalized" u" state", u'warning') return redirect(url_for('.get_request_details', request_id=request_id)) division_choices = srp_request.submitter.submit_divisions() try: division_choices.remove( (srp_request.division.id, srp_request.division.name)) except ValueError: pass if len(division_choices) == 0: current_app.logger.debug(u"No other divisions to move request #{} to."\ .format(srp_request.id)) flash(u"No other divisions to move to.", u'info') return redirect(url_for('.get_request_details', request_id=request_id)) form = DivisionChange() form.division.choices = division_choices if form.validate_on_submit(): new_division = Division.query.get(form.division.data) archive_note = u"Moving from division '{}' to division '{}'.".format( srp_request.division.name, new_division.name) if srp_request.status == ActionType.evaluating: type_ = ActionType.comment else: type_ = ActionType.evaluating archive_action = Action(srp_request, current_user, archive_note, type_) srp_request.division = new_division db.session.commit() flash( u'Request #{} moved to {} division'.format(srp_request.id, new_division.name), u'success') if current_user.has_permission(PermissionType.elevated, new_division) \ or current_user == srp_request.submitter: return redirect( url_for('.get_request_details', request_id=request_id)) else: return redirect(url_for('.list_pending_requests')) else: current_app.logger.warn(u"Form validation failed for division change:" u" {}.".format(form.errors)) form.division.data = srp_request.division.id return render_template('form.html', form=form, title=u"Change #{}'s Division".format( srp_request.id))
def request_change_division(request_id): srp_request = Request.query.get_or_404(request_id) if not current_user.has_permission(PermissionType.review, srp_request) and\ current_user != srp_request.submitter: current_app.logger.warn(u"User '{}' does not have permission to change" u" request #{}'s division".format( current_user, srp_request.id)) abort(403) if srp_request.finalized: msg = (u"Cannot change request #{}'s division as it is in a finalized" u" state").format(srp_request.id) current_app.logger.info(msg) flash(u"Cannot change the division as this request is in a finalized" u" state", u'warning') return redirect(url_for('.get_request_details', request_id=request_id)) division_choices = srp_request.submitter.submit_divisions() try: division_choices.remove( (srp_request.division.id, srp_request.division.name)) except ValueError: pass if len(division_choices) == 0: current_app.logger.debug(u"No other divisions to move request #{} to."\ .format(srp_request.id)) flash(u"No other divisions to move to.", u'info') return redirect(url_for('.get_request_details', request_id=request_id)) form = DivisionChange() form.division.choices = division_choices # Default to the first value of there's only once choice. if len(division_choices) == 1: form.division.data = form.division.choices[0][0] if form.validate_on_submit(): new_division = Division.query.get(form.division.data) archive_note = u"Moving from division '{}' to division '{}'.".format( srp_request.division.name, new_division.name) if srp_request.status == ActionType.evaluating: type_ = ActionType.comment else: type_ = ActionType.evaluating archive_action = Action(srp_request, current_user, archive_note, type_) srp_request.division = new_division db.session.commit() flash(u'Request #{} moved to {} division'.format(srp_request.id, new_division.name), u'success') if current_user.has_permission(PermissionType.elevated, new_division) \ or current_user == srp_request.submitter: return redirect(url_for('.get_request_details', request_id=request_id)) else: return redirect(url_for('.list_pending_requests')) else: current_app.logger.warn(u"Form validation failed for division change:" u" {}.".format(form.errors)) form.division.data = srp_request.division.id return render_template('form.html', form=form, title=u"Change #{}'s Division".format(srp_request.id))
def get_request_details(request_id=None, srp_request=None): """Handles responding to all of the :py:class:`~.models.Request` detail functions. The various modifier functions all depend on this function to create the actual response content. Only one of the arguments is required. The ``srp_request`` argument is a conveniece to other functions calling this function that have already retrieved the request. :param int request_id: the ID of the request. :param srp_request: the request. :type srp_request: :py:class:`~.models.Request` """ if srp_request is None: srp_request = Request.query.get_or_404(request_id) # Different templates are used for different roles if current_user.has_permission(PermissionType.review, srp_request.division): template = 'request_review.html' elif current_user.has_permission(PermissionType.pay, srp_request.division): template = 'request_pay.html' elif current_user == srp_request.submitter or current_user.has_permission( PermissionType.audit): template = 'request_detail.html' else: abort(403) if request.is_json or request.is_xhr: # dump the load to encode srp_request as json and then get a dictionary # form of it. We need this to add a few bits of information to the # standard request encoding enc_request = json.loads(json.dumps(srp_request)) enc_request[u'actions'] = srp_request.actions enc_request[u'modifiers'] = srp_request.modifiers valid_actions = map(lambda a: a.value, srp_request.valid_actions(current_user)) enc_request[u'valid_actions'] = valid_actions enc_request[u'current_user'] = current_user._get_current_object() return jsonify(enc_request) if request.is_xml: return xmlify('request.xml', srp_request=srp_request) return render_template(template, srp_request=srp_request, modifier_form=ModifierForm(formdata=None), payout_form=PayoutForm(formdata=None), action_form=ActionForm(formdata=None), void_form=VoidModifierForm(formdata=None), details_form=ChangeDetailsForm(formdata=None, obj=srp_request), note_form=AddNote(formdata=None), title=u'Request #{}'.format(srp_request.id))
def get_request_details(request_id=None, srp_request=None): """Handles responding to all of the :py:class:`~.models.Request` detail functions. The various modifier functions all depend on this function to create the actual response content. Only one of the arguments is required. The ``srp_request`` argument is a conveniece to other functions calling this function that have already retrieved the request. :param int request_id: the ID of the request. :param srp_request: the request. :type srp_request: :py:class:`~.models.Request` """ if srp_request is None: srp_request = Request.query.get_or_404(request_id) # Different templates are used for different roles if current_user.has_permission(PermissionType.review, srp_request.division): template = 'request_review.html' elif current_user.has_permission(PermissionType.pay, srp_request.division): template = 'request_pay.html' elif current_user == srp_request.submitter or current_user.has_permission( PermissionType.audit): template = 'request_detail.html' else: abort(403) if request.is_json or request.is_xhr: # dump the load to encode srp_request as json and then get a dictionary # form of it. We need this to add a few bits of information to the # standard request encoding enc_request = json.loads(json.dumps(srp_request)) enc_request[u'actions'] = srp_request.actions enc_request[u'modifiers'] = srp_request.modifiers valid_actions = map( lambda a: a.value, srp_request.valid_actions(current_user)) enc_request[u'valid_actions'] = valid_actions enc_request[u'current_user'] = current_user._get_current_object() return jsonify(enc_request) if request.is_xml: return xmlify('request.xml', srp_request=srp_request) return render_template(template, srp_request=srp_request, modifier_form=ModifierForm(formdata=None), payout_form=PayoutForm(formdata=None), action_form=ActionForm(formdata=None), void_form=VoidModifierForm(formdata=None), details_form=ChangeDetailsForm(formdata=None, obj=srp_request), note_form=AddNote(formdata=None), title=u'Request #{}'.format(srp_request.id))
def main(): if current_user.is_anonymous(): return redirect(url_for('users.login', next=url_for('.main'))) if current_user.has_permission('admin'): return redirect(url_for('.proposals')) if current_user.has_permission('cfp_anonymiser'): return redirect(url_for('.anonymisation')) if current_user.has_permission('cfp_reviewer'): return redirect(url_for('.review_list')) abort(404)
def main(): if current_user.is_anonymous(): return redirect(url_for("users.login", next=url_for(".main"))) if current_user.has_permission("admin"): return redirect(url_for(".proposals")) if current_user.has_permission("cfp_anonymiser"): return redirect(url_for(".anonymisation")) if current_user.has_permission("cfp_reviewer"): return redirect(url_for(".review_list")) abort(404)
def dispatch_request(self, filters='', **kwargs): if not current_user.has_permission(self.permissions): abort(403) return super(PayoutListing, self).dispatch_request( filters, title=u', '.join(map(lambda s: s.description, self.statuses)), form=ActionForm())
def get_user_payment_or_abort(payment_id, provider=None, valid_states=None, allow_admin=False): try: payment = Payment.query.get(payment_id) except Exception as e: app.logger.warning('Exception %r getting payment %s', e, payment_id) abort(404) if not payment: app.logger.warning('Payment %s does not exist.', payment_id) abort(404) if not (payment.user == current_user or (allow_admin and current_user.has_permission('admin'))): app.logger.warning('User not allowed to access payment %s', payment_id) abort(404) if provider and payment.provider != provider: app.logger.warning('Payment %s is of type %s, not %s', payment.provider, provider) abort(404) if valid_states and payment.state not in valid_states: app.logger.warning("Payment %s is %s, not one of %s", payment_id, payment.state, valid_states) abort(404) return payment
def post(self, instance_id): instance = self._getInstance(instance_id) or abort(404) query = request.get_json() # force async request.json['async'] = True machineName = query.get('machine', "") action = query.get('action') permission = states.get(action) if permission: if current_user.has_permission(permission, instance_id): if action == 'runScript': job_id = instance.runScript( query.get('script'), machineName) elif action == 'rsync': job_id = instance.rsync() elif action == 'sync': job_id = instance.sync() else: job_id = getattr(self, action)(instance_id, machineName) else: abort(403) console = redis_conn.get('{}:console'.format(job_id)) or '' return { 'id': job_id, 'console': console }
def add_permission(): """add permission""" if not current_user.has_permission("admin"): abort(403) if request.method == 'POST': # validate data if 'name' in request.form and len(request.form['name']): # TODO is das hier fies?! hart nach str konvertieren? _name = str(request.form['name']) if 'comment' in request.form and len(request.form['comment']): _comment = str(request.form['comment']) else: _comment = None try: new_permission = Permission.add(name=_name, comment=_comment) flash("Successfully created " + _name + " with ID " + str(new_permission.id), "success") return redirect("/admin/permissions/1") except Exception as e: flash("Something went wrong.", "danger") return redirect("/admin/permissions/1") else: return render_template("admin_add_permission.html")
def list_entities(): """Return a JSON object with a list of all of the specified entity type. Example output:: { entities: [ {name: 'Bar', id: 1, source: 'Auth Source', type: 'User'}, {name: 'Foo', id: 0, source: 'Another Auth Source', type: 'Group'}, {name: 'Baz', id: 20, source: 'Auth Source', type: 'Group'} ] } This method is only accesible to administrators. :param str entity_type: Either ``'user'`` or ``'group'``. """ if not current_user.admin and not \ current_user.has_permission(PermissionType.admin): abort(403) user_query = db.session.query(User.id, User.name, User.authmethod) group_query = db.session.query(Group.id, Group.name, Group.authmethod) users = map(lambda e: { u'id': e.id, u'name': e.name, u'type': u'User', u'source': e.authmethod}, user_query) groups = map(lambda e: { u'id': e.id, u'name': e.name, u'type': u'Group', u'source': e.authmethod}, group_query) return jsonify(entities=chain(users, groups))
def list_transformers(division_id, attribute=None): """API method to get a list of transformers for a division. :param division_id int: the ID of the division to look up :param attribute str: a specific attribute to look up. Optional. :return: JSON """ division = Division.query.get_or_404(division_id) if not current_user.admin and not \ current_user.has_permission(PermissionType.admin, division): abort(403) if attribute is None: attrs = six.iterkeys(current_app.url_transformers) else: attrs = (attribute, ) choices = {} for attr in attrs: raw_choices = transformer_choices(attr) current = division.transformers.get(attr, None) if current is not None: choices[attr] = \ [(c[0], c[1], c[1] == current.name) for c in raw_choices] else: choices[attr] = \ [(c[0], c[1], False) for c in raw_choices] return jsonify(choices)
def post(self, id): instance = self._getInstance(id) or abort(404) changed = False query = request.get_json() if 'name' in query: if query['name'] != instance.name: instance.name = query['name'] changed = True if changed: instance.save() if 'machine' in query: machineName = query['machine'] state = query.get('state') permission = states.get(state) if permission: if current_user.has_permission(permission, id): if state == 'runScript': instance.runScript(query.get('script'), machineName) elif state == 'rsync': instance.rsync() elif state == 'sync': instance.sync() else: getattr(self, state)(id, machineName) else: abort(403)
def put(self, id=None): domain = Domain.query.get(id) if current_user.has_permission(EditDomainPermission, getattr(domain.domain_controller, 'id')): if 'domain_controller' in request.json: # If the controller is to be changed in the _edit, # Delete the domain on the current controller if domain.domain_controller is not None and\ request.json['domain_controller'] is not None: self._delete_on_dc(domain) # If the domain is currently on the default controller and the # new controller is expected to be different, delete it on the # default controller if domain.domain_controller is None and\ request.json['domain_controller'] is not None: self._delete_on_dc(domain) # If we are changing the controller to be the default one if domain.domain_controller is not None and\ request.json['domain_controller'] is None: self._delete_on_dc(domain) domain = self._editDomain(id) req.put('{}/{}'.format(self._get_url(domain), id), headers=self._get_headers(), data=json.dumps(marshal(domain, domain_fields)), verify=self._get_verify(domain)) return self.get(domain.id)
def division_permissions(division_id, permission): division = Division.query.get_or_404(division_id) if not current_user.admin and not \ current_user.has_permission(PermissionType.admin, division): abort(403) permission = PermissionType.from_string(permission) # Can't use normal Entity JSON encoder as it doesn't include the # authentication source or their type (explicitly. Ain't nobody got time # for parsing the entity type out of the href). entities = [] for entity in map(lambda p: p.entity, division.permissions[permission]): entity_info = { u'name': entity.name, u'id': entity.id, u'source': str(entity.authmethod), } if hasattr(entity, u'users'): entity_info[u'type'] = u'Group' entity_info[u'length'] = len(entity.users) else: entity_info[u'type'] = u'User' entities.append(entity_info) return jsonify( entities=entities, name=permission.name, description=permission.description)
def change_user_password(user_id): """change user password""" if not current_user.has_permission("admin"): abort(403) _user = User.query.get_or_404(user_id) if request.method == 'POST': # validate data if not ('password' in request.form and len(request.form['password']) and 'password2' in request.form and len(request.form['password2'])): flash("Something went wrong.", "danger") return redirect("/admin/users/1") _password = str(request.form['password']) _password2 = str(request.form['password2']) if _password != _password2: flash("Entered Passwords do not match.", "danger") return redirect("/admin/users/1") try: _user.change_password(clear_pw=_password) flash("Successfully changed password for: " + _user.username, "success") return redirect("/admin/users/1") except Exception as e: flash("Something went wrong.", "danger") return redirect("/admin/users/1") return render_template("admin_change_user_pw.html", user=_user)
def put(self, id=None): domain = Domain.query.get(id) if current_user.has_permission( EditDomainPermission, getattr(domain.domain_controller, 'id') ): if 'domain_controller' in request.json: # If the controller is to be changed in the _edit, # Delete the domain on the current controller if domain.domain_controller is not None and\ request.json['domain_controller'] is not None: self._delete_on_dc(domain) # If the domain is currently on the default controller and the # new controller is expected to be different, delete it on the # default controller if domain.domain_controller is None and\ request.json['domain_controller'] is not None: self._delete_on_dc(domain) # If we are changing the controller to be the default one if domain.domain_controller is not None and\ request.json['domain_controller'] is None: self._delete_on_dc(domain) domain = self._editDomain(id) req.put( '{}/{}'.format(self._get_url(domain), id), headers=self._get_headers(), data=json.dumps(marshal(domain, domain_fields)), verify=self._get_verify(domain) ) return self.get(domain.id)
def list_transformers(division_id, attribute=None): """API method to get a list of transformers for a division. :param division_id int: the ID of the division to look up :param attribute str: a specific attribute to look up. Optional. :return: JSON """ division = Division.query.get_or_404(division_id) if not current_user.admin and not \ current_user.has_permission(PermissionType.admin, division): abort(403) if attribute is None: attrs = six.iterkeys(current_app.url_transformers) else: attrs = (attribute,) choices = {} for attr in attrs: raw_choices = transformer_choices(attr) current = division.transformers.get(attr, None) if current is not None: choices[attr] = \ [(c[0], c[1], c[1] == current.name) for c in raw_choices] else: choices[attr] = \ [(c[0], c[1], False) for c in raw_choices] return jsonify(choices)
def post(self, instance_id): instance = self._getInstance(instance_id) or abort(404) query = request.get_json() # force async request.json['async'] = True machineName = query.get('machine', "") action = query.get('action') permission = states.get(action) if permission: if current_user.has_permission(permission, instance_id): if action == 'runScript': job_id = instance.runScript(query.get('script'), machineName) elif action == 'rsync': job_id = instance.rsync() elif action == 'sync': job_id = instance.sync() else: job_id = getattr(self, action)(instance_id, machineName) else: abort(403) console = redis_conn.get('{}:console'.format(job_id)) or '' return {'id': job_id, 'console': console}
def parseInstance(inst): ret = {} for field, rule in config.iteritems(): conf = rule.get('outputConfig', {}) if conf.get("neverReturn", False): continue if conf.get("alwaysReturn", False): pass elif current_user.has_permission(conf.get("needPermission", [])): pass else: continue if conf.get('primary_key', False): if '_id' not in inst: continue else: ret[field] = inst['_id'] else: if field not in inst: if "default" in conf: if hasattr(conf["default"], '__call__'): ret[field] = conf["default"]() else: ret[field] = conf["default"] else: continue else: ret[field] = inst[field] ret['__write_permission'] = instanceWritePermission(inst) if not instanceReadPermission(inst): return None else: return ret
def get(self, id=None): if id is None: domain_controllers = DomainController.query.order_by('name') domain_controllers = filter( lambda domain_controller: current_user.has_permission( ( ViewDomainPermission, EditDomainPermission, CreateDomainPermission ), domain_controller.id ), domain_controllers ) return { 'domain_controllers': map( lambda t: marshal( t, domain_controller_fields_with_domains ), domain_controllers ), } else: domain_controller = DomainController.query.get(id) return marshal( domain_controller, domain_controller_fields_with_domains )
def users(page=1): """admin page - used to manage user accounts and permissions""" if not current_user.has_permission("admin"): abort(403) _users = User.query.paginate(page, app.config["ITEMS_PER_PAGE"]) return render_template("admin_users.html", users=_users)
def dispatch_request(self, filters='', **kwargs): if not current_user.has_permission(self.permissions): abort(403) else: return super(PermissionRequestListing, self).dispatch_request( filters, title=self.title, **kwargs)
def dispatch_request(self, filters='', **kwargs): if not current_user.has_permission(self.permissions): abort(403) else: return super(PermissionRequestListing, self).dispatch_request(filters, title=self.title, **kwargs)
def validate_division(form, field): division = Division.query.get(field.data) if division is None: raise ValidationError(u"No division with ID '{}'.".format( field.data)) if not current_user.has_permission(PermissionType.submit, division): raise ValidationError(u"You do not have permission to submit to " u"division '{}'.".format(division.name))
def get_all_instances(self): instances = filter( lambda instance: current_user.has_permission( ViewInstancePermission, instance.id ), self.instances ) return instances
def get_request_details(request_id=None, srp_request=None): """Handles responding to all of the :py:class:`~.models.Request` detail functions. The various modifier functions all depend on this function to create the actual response content. Only one of the arguments is required. The ``srp_request`` argument is a conveniece to other functions calling this function that have already retrieved the request. :param int request_id: the ID of the request. :param srp_request: the request. :type srp_request: :py:class:`~.models.Request` """ if srp_request is None: srp_request = Request.query.get_or_404(request_id) # Different templates are used for different roles if current_user.has_permission(PermissionType.review, srp_request.division): template = 'request_review.html' elif current_user.has_permission(PermissionType.pay, srp_request.division): template = 'request_pay.html' elif current_user == srp_request.submitter or current_user.has_permission( PermissionType.audit): template = 'request_detail.html' else: abort(403) if request.is_json or request.is_xhr: return jsonify(srp_request._json(True)) if request.is_xml: return xmlify('request.xml', srp_request=srp_request) return render_template(template, srp_request=srp_request, modifier_form=ModifierForm(formdata=None), payout_form=PayoutForm(formdata=None), action_form=ActionForm(formdata=None), void_form=VoidModifierForm(formdata=None), details_form=ChangeDetailsForm(formdata=None, obj=srp_request), note_form=AddNote(formdata=None), # TRANS: Title for the page showing the details about a single # TRANS: SRP request. title=gettext(u"Request #%(request_id)s", request_id=srp_request.id))
def _change_payout(srp_request): form = PayoutForm() if not current_user.has_permission(PermissionType.review, srp_request): flash(u"Only reviewers can change the base payout.", u'error') elif form.validate(): try: srp_request.base_payout = form.value.data * 1000000 db.session.commit() except ModifierError as e: flash(unicode(e), u'error') return get_request_details(srp_request=srp_request)
def submit_request(): """Submit a :py:class:`~.models.Request`\. Displays a form for submitting a request and then processes the submitted information. Verifies that the user has the appropriate permissions to submit a request for the chosen division and that the killmail URL given is valid. Also enforces that the user submitting this requests controls the character from the killmail and prevents duplicate requests. """ if not current_user.has_permission(PermissionType.submit): abort(403) form = RequestForm() # Do it in here so we can access current_app (needs to be in an app # context) form.url.description = get_killmail_descriptions() form.details.description = current_app.config['SRP_DETAILS_DESCRIPTION'] # Create a list of divisions this user can submit to form.division.choices = current_user.submit_divisions() if len(form.division.choices) == 1: form.division.data = form.division.choices[0][0] if form.validate_on_submit(): mail = form.killmail # Prevent submitting other people's killmails pilot = Pilot.query.get(mail.pilot_id) if not pilot or pilot not in current_user.pilots: # TRANS: Error message shown when trying to submit a lossmail from # TRANS: A character not associated with your user account. flash(gettext(u"You can only submit killmails of characters you " u"control"), u'warning') return render_template('form.html', form=form) # Prevent duplicate killmails # The name 'request' is already used by Flask. # Hooray name collisions! srp_request = Request.query.get(mail.kill_id) if srp_request is None: division = Division.query.get(form.division.data) srp_request = Request(current_user, form.details.data, division, mail) srp_request.pilot = pilot db.session.add(srp_request) db.session.commit() return redirect(url_for('.get_request_details', request_id=srp_request.id)) else: # TRANS: Error message shown when trying to submit a killmail for # TRANS: SRP a second time. flash(gettext(u"This kill has already been submitted"), u'warning') return redirect(url_for('.get_request_details', request_id=srp_request.id)) return render_template('form.html', form=form, # TRANS: Title for the page showing the form for submitting SRP requests. title=gettext(u'Submit Request'))
def get(self, id=None): if id is None: domains = Domain.query.all() domains = filter( lambda domain: current_user.has_permission( (ViewDomainPermission, EditDomainPermission, CreateDomainPermission), domain.domain_controller and domain.domain_controller.id or None), domains) else: domains = Domain.query.get(id) return marshal(domains, domain_fields)
def create_menu(endpoint): if not current_user.has_permission(code='admin'): return False menu = {'name': 'Admin', 'submenu': [], 'active': False} entries = [] if current_user.has_permission(code='manage-liquidsoap'): entries.append(['admin.liquidsoap_manage', 'Liquidsoap-Manager', 'admin']) entries.append(['admin.liquidsoap_config', 'Liquidsoap-Config', 'admin']) entries.append(['admin.stream_list', 'Streams', 'admin']) entries.append(['admin.relay_list', 'Relays', 'admin']) entries.append(['admin.user_list', 'Users', 'admin']) entries.append(['admin.log_list', 'Logs', 'admin']) entries.append(['admin.listener_list', 'Listeners', 'admin']) for entry in entries: active = endpoint == entry[0] menu['submenu'].append({'name': entry[1], 'url': url_for(entry[0]), 'active': (active)}) if active: menu['active'] = True return menu
def decorated_function(*args, **kwargs): if not current_user.is_authenticated(): if ajax: return emit_error(0, 'Not Logged In!') else: return 'not logged in' if permission is not None and not current_user.has_permission(permission): if ajax: return emit_error(0, 'insufficient permissions') else: return 'insufficient permissions' return f(*args, **kwargs)
def dispatch_request(self, filters='', **kwargs): if not current_user.has_permission(self.permissions): abort(403) else: if 'title' in kwargs: title = kwargs.pop('title') else: title = u', '.join(map(lambda s: s.description, self.statuses)) return super(PermissionRequestListing, self).dispatch_request( filters, title=title, **kwargs)
def listeners(): # check if current_user is logged in and if user is streaming or if user is admin if not current_user.is_anonymous(): is_streaming = UserShow.query.join(User).filter(UserShow.status == UserShow.STATUS.STREAMING, UserShow.user == current_user).first() if is_streaming or current_user.has_permission('admin'): show_listener_list = True else: show_listener_list = False else: show_listener_list = False # get current bandwidth of all active relays total_bandwidth = 0 relays = Relay.query.filter(Relay.status == Relay.STATUS.ONLINE).all() active_relays = len(relays) for relay in relays: total_bandwidth += relay.usage total_bandwidth *= 128 # convert kbit to byte # get all current listeners current_listener = Listener.get_current_listeners() # generate per country stats per_country = {} for listener in current_listener: country = listener.country try: per_country[country]['count'] += 1 except KeyError: per_country[country] = {'count': 1} per_country[country]['ball'] = country per_country = sorted(per_country.iteritems(), key=lambda (k, v): v['count'], reverse=True) # get recent listener count to calculate a trend try: stats_total = Statistic.query.filter(Statistic.identifier == 'lst-total').one() stats = stats_total.get(start=now() - datetime.timedelta(minutes=2), stop=now()) except exc.NoResultFound: stats = None if stats and stats.count() > 0: listener_sum = 0 for stat in stats: listener_sum += stat.value average_listeners = listener_sum / stats.count() else: average_listeners = len(current_listener) return render_template('listenergraph.html', TITLE='Listeners', show_listener_list=show_listener_list, listeners=current_listener, per_country=per_country, total_bandwidth=total_bandwidth, active_relays=active_relays, average_listeners=average_listeners)
def _change_payout(srp_request): form = PayoutForm() if not current_user.has_permission(PermissionType.review, srp_request): # TRANS: Error message when someone who does not have the reviewer # TRANS: permission tries to change the base payout of a request. flash(gettext(u"Only reviewers can change the base payout."), u'error') elif form.validate(): try: srp_request.base_payout = form.value.data * 1000000 db.session.commit() except ModifierError as e: flash(unicode(e), u'error') return get_request_details(srp_request=srp_request)
def validate_division(form, field): division = Division.query.get(field.data) if division is None: # TRANS: Error message shown when trying to submit a request to a # TRANS: non-existant division. raise ValidationError(gettext(u"No division with ID '%(div_id)s'.", div_id=field.data)) if not current_user.has_permission(PermissionType.submit, division): # TRANS: Error message shown when trying to a submit a request to a # TRANS: division you do not have the submission permission in. raise ValidationError(gettext(u"You do not have permission to " u"submit to division '%(name)s'.", name=division.name))
def dispatch_request(self, filters='', **kwargs): if hasattr(request, 'json_extended'): if isinstance(request.json_extended, bool): old_value = request.json_extended request.json_extended = defaultdict(lambda: old_value) else: request.json_extended = {} request.json_extended[Request] = True if not current_user.has_permission(self.permissions): abort(403) return super(PayoutListing, self).dispatch_request( filters, form=ActionForm())
def permissions(): """Show a page listing all divisions. """ if current_user.admin: return render_template('divisions.html', divisions=Division.query.all()) if current_user.has_permission(PermissionType.admin): admin_permissions = current_user.permissions.filter_by( permission=PermissionType.admin).values(Permission.division_id) admin_permissions = map(lambda x: x[0], admin_permissions) divisions = db.session.query(Division).\ filter(Division.id.in_(admin_permissions)) return render_template('divisions.html', divisions=divisions) return render_template('permissions.html') return abort(403)
def update_navbar(response): if "application/json" not in response.mimetype: return response response_json = json.loads(response.get_data()) nav_bar = {"pending": False, "payouts": False, "completed": False, "submit": False} counts = {"pending": 0, "payouts": 0} nav_bar["counts"] = counts response_json["nav_bar"] = nav_bar # Unauthenticated users get nothing if not current_user.is_authenticated(): response.set_data(json.dumps(response_json)) return response if current_user.has_permission((PermissionType.review, PermissionType.audit)): nav_bar["pending"] = True counts["pending"] = request_count(PermissionType.review) if current_user.has_permission(PermissionType.pay): nav_bar["payouts"] = True counts["payouts"] = request_count(PermissionType.pay) if current_user.has_permission(PermissionType.elevated): nav_bar["completed"] = True if current_user.has_permission(PermissionType.submit): nav_bar["submit"] = True response.set_data(json.dumps(response_json)) return response
def submit_request(): """Submit a :py:class:`~.models.Request`\. Displays a form for submitting a request and then processes the submitted information. Verifies that the user has the appropriate permissions to submit a request for the chosen division and that the killmail URL given is valid. Also enforces that the user submitting this requests controls the character from the killmail and prevents duplicate requests. """ if not current_user.has_permission(PermissionType.submit): abort(403) form = RequestForm() # Do it in here so we can access current_app (needs to be in an app # context) form.url.description = get_killmail_descriptions() form.details.description = current_app.config['SRP_DETAILS_DESCRIPTION'] # Create a list of divisions this user can submit to form.division.choices = current_user.submit_divisions() if len(form.division.choices) == 1: form.division.data = 1 if form.validate_on_submit(): mail = form.killmail # Prevent submitting other people's killmails pilot = Pilot.query.get(mail.pilot_id) if not pilot or pilot not in current_user.pilots: flash(u"You can only submit killmails of characters you control", u'warning') return render_template('form.html', form=form) # Prevent duplicate killmails # The name 'request' is already used by Flask. # Hooray name collisions! srp_request = Request.query.get(mail.kill_id) if srp_request is None: division = Division.query.get(form.division.data) srp_request = Request(current_user, form.details.data, division, mail) srp_request.pilot = pilot db.session.add(srp_request) db.session.commit() return redirect( url_for('.get_request_details', request_id=srp_request.id)) else: flash(u"This kill has already been submitted", u'warning') return redirect( url_for('.get_request_details', request_id=srp_request.id)) return render_template('form.html', form=form, title=u'Submit Request')
def modify_division(division_id): """Dispatches modification requests to the specialized view function for that operation. """ division = Division.query.get_or_404(division_id) if not current_user.admin and not \ current_user.has_permission(PermissionType.admin, division): abort(403) form_id = request.form.get('form_id') if form_id == 'entity': return _modify_division_entity(division) elif form_id == 'transformer': return _modify_division_transformer(division) else: current_app.logger.warn( "Invalid division modification POST: {}".format(request.form)) abort(400)
def receipt(user_id=None): if current_user.has_permission('admin') and user_id is not None: user = User.query.get(user_id).one() else: user = current_user if not user.tickets.filter_by(paid=True).all(): abort(404) png = bool(request.args.get('png')) pdf = bool(request.args.get('pdf')) page = render_receipt(user, png, pdf) if pdf: return send_file(render_pdf(page), mimetype='application/pdf') return page
def get(self, id=None): if id is None: hostsAll = Host.query.order_by('name') permittedHosts = [] for host in hostsAll: if current_user.has_permission(ViewHostPermission, host.id): permittedHosts.append(host) return { 'hosts': map(lambda t: marshal(t, host_fields), permittedHosts), } else: host = Host.query.get(id) host.params = host.params.replace('\r\n', '<br>') host.params = host.params.replace('\n', '<br>') return marshal(host, host_fields)
def get(self, id=None): if id is None: domain_controllers = DomainController.query.order_by('name') domain_controllers = filter( lambda domain_controller: current_user.has_permission( (ViewDomainPermission, EditDomainPermission, CreateDomainPermission), domain_controller.id), domain_controllers) return { 'domain_controllers': map( lambda t: marshal(t, domain_controller_fields_with_domains ), domain_controllers), } else: domain_controller = DomainController.query.get(id) return marshal(domain_controller, domain_controller_fields_with_domains)
def division_detail(division_id): """Get the details of a division. :param int division_id: The ID of the division """ division = Division.query.get_or_404(division_id) if not current_user.admin and not \ current_user.has_permission(PermissionType.admin, division): abort(403) permissions = {} for perm in PermissionType.all: key = perm.name + '_href' permissions[key] = url_for('.division_permissions', division_id=division_id, permission=perm.name) return jsonify( name=division.name, requests=division.requests, permissions=permissions)
def _add_note(srp_request): form = AddNote() if not current_user.has_permission(PermissionType.elevated): flash(u"You do not have permission to add a note to a user.", u'error') elif form.validate(): # Linkify killmail IDs note_content = Markup.escape(form.note.data) for match in killmail_re.findall(note_content): kill_id = int(match) check_request = db.session.query(Request.id).filter_by(id=kill_id) if db.session.query(check_request.exists()): link = u'<a href="{url}">#{kill_id}</a>'.format( url=url_for('.get_request_details', request_id=kill_id), kill_id=kill_id) link = Markup(link) note_content = note_content.replace(u'#' + match, link) # Create the note note = Note(srp_request.submitter, current_user, note_content) db.session.commit() return get_request_details(srp_request=srp_request)
def get_division_details(division_id=None, division=None): """Generate a page showing the details of a division. Shows which groups and individuals have been granted permissions to each division. Only accesible to administrators. :param int division_id: The ID number of the division """ if division is None: division = Division.query.get_or_404(division_id) if not current_user.admin and not \ current_user.has_permission(PermissionType.admin, division): abort(403) if request.is_json or request.is_xhr: # Non-default way of encoding the division to include all the info in a # normal response entities = {} for perm in PermissionType.all: members = [] for member in [p.entity for p in division.permissions[perm]]: member_info = { 'id': member.id, 'name': member.name, 'source': member.authmethod, } if hasattr(member, 'users'): member_info['length'] = len(member.users) members.append(member_info) entities[perm.name] = members return jsonify(name=division.name, entities=entities, id=division.id) return render_template( 'division_detail.html', division=division, entity_form=ChangeEntity(formdata=None), transformer_form=ChangeTransformer(formdata=None), )
def has_permission_or_owner(permission, object_owner_id): return int(object_owner_id ) == current_user.id or current_user.has_permission(permission)
def choose(flow=None): token = session.get('ticket_token') sales_state = get_sales_state() if flow is None: admissions = True elif flow == 'other': admissions = False else: abort(404) if sales_state in ['unavailable', 'sold-out']: # For the main entry point, we assume people want admissions tickets, # but we still need to sell people e.g. parking tickets or tents until # the final cutoff (sales-ended). if not admissions: sales_state = 'available' # Allow people with valid discount tokens to buy tickets elif token is not None and TicketType.get_types_for_token(token): sales_state = 'available' if app.config.get('DEBUG'): sales_state = request.args.get("sales_state", sales_state) if sales_state == 'available': pass elif not current_user.is_anonymous() and current_user.has_permission( 'admin'): pass else: return render_template("tickets-cutoff.html") form = TicketAmountsForm() # If this is the main page, exclude tents and other paraphernalia. # For the non-admissions page, only exclude actual admissions tickets. # This means both pages show parking and caravan tickets. if admissions: tts = TicketType.query.filter(~TicketType.admits.in_(['other'])) else: tts = TicketType.query.filter(~TicketType.admits.in_(['full', 'kid'])) tts = tts.order_by(TicketType.order).all() limits = dict((tt.id, tt.user_limit(current_user, token)) for tt in tts) if request.method != 'POST': # Empty form - populate ticket types for tt in tts: form.types.append_entry() form.types[-1].type_id.data = tt.id tts = {tt.id: tt for tt in tts} for f in form.types: t_id = f.type_id.data f._type = tts[t_id] values = range(limits[t_id] + 1) f.amount.values = values f._any = any(values) if form.validate_on_submit(): if form.buy.data or form.buy_other.data: set_user_currency(form.currency_code.data) basket = [] for f in form.types: if f.amount.data: tt = f._type app.logger.info('Adding %s %s tickets to basket', f.amount.data, tt.name) basket += [tt.id] * f.amount.data if basket: session['basket'] = basket return redirect(url_for('tickets.pay', flow=flow)) elif admissions: flash("Please select at least one ticket to buy.") else: flash("Please select at least one item to buy.") if request.method == 'POST' and form.set_currency.data: if form.set_currency.validate(form): app.logger.info("Updating currency to %s only", form.set_currency.data) set_user_currency(form.set_currency.data) for field in form: field.errors = [] form.currency_code.data = get_user_currency() return render_template("tickets-choose.html", form=form, admissions=admissions)
def call(f, *args, **kwargs): if current_user.is_authenticated(): if current_user.has_permission(permission): return f(*args, **kwargs) abort(404) return app.login_manager.unauthorized()
def get_all_instances(self): instances = filter( lambda instance: current_user.has_permission( ViewInstancePermission, instance.id), self.instances) return instances
def dispatch_request(self, filters='', **kwargs): if not current_user.has_permission(self.permissions): abort(403) return super(PayoutListing, self).dispatch_request(filters, form=ActionForm())