def get_saml2_config(): config = saml2.config.Config() saml_settings = { 'metadata': { 'remote': [{ 'url': current_app.config['SAML2_METADATA_URL'], }] }, 'entityid': absolute_url(), 'service': { 'sp': { 'endpoints': { 'assertion_consumer_service': [ (absolute_url('/auth/saml'), saml2.BINDING_HTTP_POST) ] }, 'allow_unsolicited': True, 'authn_requests_signed': False, 'want_assertions_signed': True, 'want_response_signed': False } } } if current_app.config['SAML2_ENTITY_ID']: saml_settings['entityid'] = current_app.config['SAML2_ENTITY_ID'] if current_app.config['SAML2_CONFIG'].get('metadata'): saml_settings['metadata'] = current_app.config['SAML2_CONFIG']['metadata'] merge(saml_settings, current_app.config['SAML2_CONFIG']) # allow settings override config.load(saml_settings) config.allow_unknown_attributes = True return config
def index(): links = [] for rule in current_app.url_map.iter_rules(): links.append({ 'rel': rule.endpoint, 'href': absolute_url(rule.rule), 'method': ','.join([m for m in rule.methods if m not in ['HEAD', 'OPTIONS']]) }) return jsonify(status='ok', uri=absolute_url(), data={'description': 'Alerta API'}, links=sorted(links, key=lambda k: k['href']))
def serialize(self) -> Dict[str, Any]: return { 'id': self.id, 'href': absolute_url('/alert/' + self.id), 'resource': self.resource, 'event': self.event, 'environment': self.environment, 'severity': self.severity, 'correlate': self.correlate, 'status': self.status, 'service': self.service, 'group': self.group, 'value': self.value, 'text': self.text, 'tags': self.tags, 'attributes': self.attributes, 'origin': self.origin, 'type': self.event_type, 'createTime': self.create_time, 'timeout': self.timeout, 'rawData': self.raw_data, 'customer': self.customer, 'duplicateCount': self.duplicate_count, 'repeat': self.repeat, 'previousSeverity': self.previous_severity, 'trendIndication': self.trend_indication, 'receiveTime': self.receive_time, 'lastReceiveId': self.last_receive_id, 'lastReceiveTime': self.last_receive_time, 'updateTime': self.update_time, 'history': [h.serialize for h in sorted(self.history, key=lambda x: x.update_time)] }
def serialize(self) -> Dict[str, Any]: note = { 'id': self.id, 'href': absolute_url('/note/' + self.id), 'text': self.text, 'user': self.user, 'attributes': self.attributes, 'type': self.note_type, 'createTime': self.create_time, 'updateTime': self.update_time, '_links': dict(), 'customer': self.customer } # type: Dict[str, Any] if self.alert: note['_links'] = {'alert': absolute_url('/alert/' + self.alert)} return note
def add_note(alert_id): note_text = request.json.get('note', None) if not note_text: raise ApiError("must supply 'note' text") customers = g.get('customers', None) alert = Alert.find_by_id(alert_id, customers) if not alert: raise ApiError('not found', 404) note = alert.add_note(note_text) write_audit_trail.send(current_app._get_current_object(), event='alert-note-added', message='', user=g.login, customers=g.customers, scopes=g.scopes, resource_id=note.id, type='note', request=request) if note: return jsonify(status='ok', id=note.id, note=note.serialize), 201, { 'Location': absolute_url('/alert/{}/note/{}'.format(alert.id, note.id)) } else: raise ApiError('failed to add note for alert', 500)
def create_blackout(): try: blackout = Blackout.parse(request.json) except Exception as e: raise ApiError(str(e), 400) if 'admin' in g.scopes or 'admin:blackouts' in g.scopes: blackout.user = blackout.user or g.user else: blackout.user = g.user blackout.customer = assign_customer(wanted=blackout.customer, permission='admin:blackouts') try: blackout = blackout.create() except Exception as e: raise ApiError(str(e), 500) if blackout: return jsonify(status='ok', id=blackout.id, blackout=blackout.serialize), 201, { 'Location': absolute_url('/blackout/' + blackout.id) } else: raise ApiError('insert blackout failed', 500)
def serialize(self) -> Dict[str, Any]: return { 'id': self.id, 'href': absolute_url('/perm/' + self.id), 'match': self.match, 'scopes': self.scopes }
def serialize(self) -> Dict[str, Any]: return { 'id': self.id, 'href': absolute_url('/customer/' + self.id), 'match': self.match, 'customer': self.customer }
def create_token(user_id: str, name: str, login: str, provider: str, customers: List[str], scopes: List[str], email: str = None, email_verified: bool = None, picture: str = None, **kwargs) -> 'Jwt': now = datetime.utcnow() return Jwt(iss=request.url_root, typ='Bearer', sub=user_id, aud=current_app.config.get('OAUTH2_CLIENT_ID') or current_app.config.get('SAML2_ENTITY_ID') or absolute_url(), exp=(now + timedelta(days=current_app.config['TOKEN_EXPIRE_DAYS'])), nbf=now, iat=now, jti=str(uuid4()), name=name, preferred_username=login, email=email, email_verified=email_verified, provider=provider, scopes=scopes, customers=customers, picture=picture, **kwargs)
def serialize(self): data = { 'id': self.id, 'href': absolute_url('/alert/' + self.id), 'resource': self.resource, 'event': self.event, 'environment': self.environment, 'service': self.service, 'group': self.group, 'text': self.text, 'tags': self.tags, 'attributes': self.attributes, 'origin': self.origin, 'updateTime': self.update_time, 'user': self.user, 'type': self.change_type, 'customer': self.customer } if self.severity: data['severity'] = self.severity if self.status: data['status'] = self.status if self.value: data['value'] = self.value return data
def serialize(self): data = { 'id': self.id, 'href': absolute_url('/alert/' + self.id), 'resource': self.resource, 'event': self.event, 'environment': self.environment, 'service': self.service, 'group': self.group, 'text': self.text, 'tags': self.tags, 'attributes': self.attributes, 'origin': self.origin, 'updateTime': self.update_time, 'type': self.change_type, 'customer': self.customer } if self.severity: data['severity'] = self.severity if self.status: data['status'] = self.status if self.value: data['value'] = self.value return data
def get_topn_count(self, query=None, group='event', topn=100): query = query or Query() select = """ SELECT event, COUNT(1) as count, SUM(duplicate_count) AS duplicate_count, array_agg(DISTINCT environment) AS environments, array_agg(DISTINCT svc) AS services, array_agg(DISTINCT ARRAY[id, resource]) AS resources FROM alerts, UNNEST (service) svc WHERE {where} GROUP BY {group} ORDER BY count DESC """.format(where=query.where, group=group) return [{ 'count': t.count, 'duplicateCount': t.duplicate_count, 'environments': t.environments, 'services': t.services, '%s' % group: t.event, 'resources': [{ 'id': r[0], 'resource': r[1], 'href': absolute_url('/alert/%s' % r[0]) } for r in t.resources] } for t in self._fetchall(select, query.vars, limit=topn)]
def get_topn_standing(self, query=None, group='event', topn=100): query = query or Query() select = """ WITH topn AS (SELECT * FROM alerts WHERE {where}) SELECT topn.event, COUNT(1) as count, SUM(duplicate_count) AS duplicate_count, SUM(last_receive_time - create_time) as life_time, array_agg(DISTINCT environment) AS environments, array_agg(DISTINCT svc) AS services, array_agg(DISTINCT ARRAY[topn.id, resource]) AS resources FROM topn, UNNEST (service) svc, UNNEST (history) hist WHERE hist.type='severity' GROUP BY topn.{group} ORDER BY life_time DESC """.format(where=query.where, group=group) return [{ 'count': t.count, 'duplicateCount': t.duplicate_count, 'environments': t.environments, 'services': t.services, 'event': t.event, 'resources': [{ 'id': r[0], 'resource': r[1], 'href': absolute_url('/alert/%s' % r[0]) } for r in t.resources] } for t in self._fetchall(select, query.vars, limit=topn)]
def serialize(self) -> Dict[str, Any]: return { 'id': self.id, 'href': absolute_url('/alert/' + self.id), 'resource': self.resource, 'event': self.event, 'environment': self.environment, 'severity': self.severity, 'correlate': self.correlate, 'status': self.status, 'service': self.service, 'group': self.group, 'value': self.value, 'text': self.text, 'tags': self.tags, 'attributes': self.attributes, 'origin': self.origin, 'type': self.event_type, 'createTime': self.create_time, 'timeout': self.timeout, 'rawData': self.raw_data, 'customer': self.customer, 'duplicateCount': self.duplicate_count, 'repeat': self.repeat, 'previousSeverity': self.previous_severity, 'trendIndication': self.trend_indication, 'receiveTime': self.receive_time, 'lastReceiveId': self.last_receive_id, 'lastReceiveTime': self.last_receive_time, 'history': [h.serialize for h in sorted(self.history, key=lambda x: x.update_time)] }
def serialize(self) -> Dict[str, Any]: return { 'id': self.id, 'href': absolute_url('/user/' + self.id), 'login': self.login, 'name': self.name, 'status': self.status }
def serialize(self) -> Dict[str, Any]: return { 'id': self.id, 'href': absolute_url('/group/' + self.id), 'name': self.name, 'text': self.text, 'count': self.count }
def config(): return jsonify({ 'debug': current_app.debug, 'endpoint': absolute_url().rstrip('/'), # FIXME - shouldn't need to rstrip() 'alarm_model': { 'name': alarm_model.name, 'severity': alarm_model.Severity, 'colors': alarm_model.Colors, 'status': alarm_model.Status, 'defaults': { 'status': alarm_model.DEFAULT_STATUS, 'normal_severity': alarm_model.DEFAULT_NORMAL_SEVERITY, 'previous_severity': alarm_model.DEFAULT_PREVIOUS_SEVERITY } }, 'auth_required': current_app.config['AUTH_REQUIRED'], 'provider': current_app.config['AUTH_PROVIDER'], 'customer_views': current_app.config['CUSTOMER_VIEWS'], 'signup_enabled': current_app.config['SIGNUP_ENABLED'] if current_app.config['AUTH_PROVIDER'] == 'basic' else False, 'email_verification': current_app.config['EMAIL_VERIFICATION'], 'client_id': current_app.config['OAUTH2_CLIENT_ID'], 'azure_tenant': current_app.config['AZURE_TENANT'], 'aws_region': current_app.config['AWS_REGION'], 'cognito_domain': current_app.config['COGNITO_DOMAIN'], 'github_url': current_app.config['GITHUB_URL'], 'gitlab_url': current_app.config['GITLAB_URL'], 'keycloak_url': current_app.config['KEYCLOAK_URL'], 'keycloak_realm': current_app.config['KEYCLOAK_REALM'], 'oidc_auth_url': current_app.config['OIDC_AUTH_URL'], 'site_logo_url': current_app.config['SITE_LOGO_URL'], 'severity': alarm_model.Severity, # FIXME - moved to alarm model 'colors': alarm_model.Colors, # FIXME - moved to alarm model 'timeouts': { 'alert': current_app.config['ALERT_TIMEOUT'], 'heartbeat': current_app.config['HEARTBEAT_TIMEOUT'], 'ack': current_app.config['ACK_TIMEOUT'], 'shelve': current_app.config['SHELVE_TIMEOUT'] }, 'dates': { 'shortTime': current_app.config['DATE_FORMAT_SHORT_TIME'], 'mediumDate': current_app.config['DATE_FORMAT_MEDIUM_DATE'], 'longDate': current_app.config['DATE_FORMAT_LONG_DATE'] }, 'font': current_app.config['DEFAULT_FONT'], 'audio': { 'new': current_app.config['DEFAULT_AUDIO_FILE'] }, 'columns': current_app.config['COLUMNS'], 'sort_by': current_app.config['SORT_LIST_BY'], 'filter': current_app.config['DEFAULT_FILTER'], 'indicators': { 'severity': current_app.config['ASI_SEVERITY'], 'queries': current_app.config['ASI_QUERIES'] }, 'actions': current_app.config['ACTIONS'], 'tracking_id': current_app.config['GOOGLE_TRACKING_ID'], 'refresh_interval': current_app.config['AUTO_REFRESH_INTERVAL'] })
def get_saml2_config(): config = saml2.config.Config() default_config = { 'entityid': absolute_url(), 'service': { 'sp': { 'endpoints': { 'assertion_consumer_service': [(absolute_url('/auth/saml'), saml2.BINDING_HTTP_POST)] } } } } config.load(deepmerge(default_config, current_app.config['SAML2_CONFIG'])) return config
def config(): return jsonify({ 'endpoint': absolute_url().rstrip('/'), # FIXME - shouldn't need to rstrip() 'alarm_model': { 'name': alarm_model.name }, 'auth_required': current_app.config['AUTH_REQUIRED'], 'provider': current_app.config['AUTH_PROVIDER'], 'customer_views': current_app.config['CUSTOMER_VIEWS'], 'signup_enabled': current_app.config['SIGNUP_ENABLED'] if current_app.config['AUTH_PROVIDER'] == 'basic' else False, 'email_verification': current_app.config['EMAIL_VERIFICATION'], 'client_id': current_app.config['OAUTH2_CLIENT_ID'], 'azure_tenant': current_app.config['AZURE_TENANT'], 'github_url': current_app.config['GITHUB_URL'], 'gitlab_url': current_app.config['GITLAB_URL'], 'keycloak_url': current_app.config['KEYCLOAK_URL'], 'keycloak_realm': current_app.config['KEYCLOAK_REALM'], 'pingfederate_url': current_app.config['PINGFEDERATE_URL'], 'site_logo_url': current_app.config['SITE_LOGO_URL'], 'severity': alarm_model.Severity, 'colors': alarm_model.Colors, 'dates': { 'shortTime': current_app.config['DATE_FORMAT_SHORT_TIME'], 'mediumDate': current_app.config['DATE_FORMAT_MEDIUM_DATE'], 'longDate': current_app.config['DATE_FORMAT_LONG_DATE'] }, 'audio': { 'new': current_app.config['DEFAULT_AUDIO_FILE'] }, 'columns': current_app.config['COLUMNS'], 'sort_by': current_app.config['SORT_LIST_BY'], 'actions': current_app.config['ACTIONS'], 'tracking_id': current_app.config['GOOGLE_TRACKING_ID'], 'refresh_interval': current_app.config['AUTO_REFRESH_INTERVAL'] })
def index(): links = [] for rule in current_app.url_map.iter_rules(): links.append({ 'rel': rule.endpoint, 'href': absolute_url(rule.rule), 'method': ','.join([m for m in rule.methods if m not in ['HEAD', 'OPTIONS']]) }) for rule in custom_webhooks.iter_rules(): links.append({ 'rel': rule.endpoint, 'href': absolute_url(rule.rule), 'method': ','.join(rule.methods) }) return jsonify(status='ok', uri=absolute_url(), data={'description': 'Alerta API'}, links=sorted(links, key=lambda k: k['href']))
def get_saml2_config(): config = saml2.config.Config() default_config = { 'entityid': absolute_url(), 'service': { 'sp': { 'endpoints': { 'assertion_consumer_service': [ (absolute_url('/auth/saml'), saml2.BINDING_HTTP_POST) ] } } } } config.load(deepmerge(default_config, current_app.config['SAML2_CONFIG'])) return config
def serialize(self): return { 'id': self.id, 'href': absolute_url('/alert/' + self.id), 'event': self.event, 'severity': self.severity, 'status': self.status, 'value': self.value, 'text': self.text, 'type': self.change_type, 'updateTime': self.update_time }
def serialize(self): return { 'id': self.id, 'href': absolute_url('/alert/' + self.id), 'event': self.event, 'severity': self.severity, 'status': self.status, 'value': self.value, 'text': self.text, 'type': self.change_type, 'updateTime': self.update_time, 'user': self.user }
def serialize(self) -> Dict[str, Any]: return { 'id': self.id, 'key': self.key, 'href': absolute_url('/key/' + self.key), 'user': self.user, 'scopes': self.scopes, 'type': self.type, 'text': self.text, 'expireTime': self.expire_time, 'count': self.count, 'lastUsedTime': self.last_used_time, 'customer': self.customer }
def add_note(alert_id): note_text = request.json.get('text') or request.json.get('note') if not note_text: raise ApiError("must supply 'note' text", 400) customers = g.get('customers', None) alert = Alert.find_by_id(alert_id, customers) if not alert: raise ApiError('not found', 404) try: alert, note_text = process_note(alert, note_text) note = alert.add_note(note_text) except RejectException as e: write_audit_trail.send(current_app._get_current_object(), event='alert-note-rejected', message='', user=g.login, customers=g.customers, scopes=g.scopes, resource_id=note.id, type='note', request=request) raise ApiError(str(e), 400) except ForwardingLoop as e: return jsonify(status='ok', message=str(e)), 202 except AlertaException as e: raise ApiError(e.message, code=e.code, errors=e.errors) except Exception as e: raise ApiError(str(e), 500) write_audit_trail.send(current_app._get_current_object(), event='alert-note-added', message='', user=g.login, customers=g.customers, scopes=g.scopes, resource_id=note.id, type='note', request=request) if note: return jsonify(status='ok', id=note.id, note=note.serialize), 201, { 'Location': absolute_url('/alert/{}/note/{}'.format(alert.id, note.id)) } else: raise ApiError('failed to add note for alert', 500)
def serialize(self) -> Dict[str, Any]: return { 'id': self.id, 'href': absolute_url('/heartbeat/' + self.id), 'origin': self.origin, 'tags': self.tags, 'type': self.event_type, 'createTime': self.create_time, 'timeout': self.timeout, 'receiveTime': self.receive_time, 'customer': self.customer, 'latency': self.latency, 'since': self.since, 'status': self.status }
def serialize(self) -> Dict[str, Any]: note = { 'id': self.id, 'href': absolute_url('/note/' + self.id), 'text': self.text, 'user': self.user, 'attributes': self.attributes, 'type': self.note_type, 'createTime': self.create_time, 'updateTime': self.update_time, 'related': dict(), 'customer': self.customer } if self.alert: note['related']['alert'] = self.alert return note
def serialize(self) -> Dict[str, Any]: return { 'id': self.id, 'type': self.type, 'href': absolute_url('/twiliorule/' + self.id), 'priority': self.priority, 'environment': self.environment, 'fromNumber': self.from_number, 'toNumbers': self.to_numbers, 'service': self.service, 'severity': self.severity, 'resource': self.resource, 'event': self.event, 'group': self.group, 'tags': self.tags, 'customer': self.customer, 'status': self.status, 'user': self.user, 'createTime': self.create_time, 'text': self.text, 'startTime': self.start_time.strftime('%H:%M') if self.start_time is not None else None, 'endTime': self.end_time.strftime('%H:%M') if self.end_time is not None else None, 'days': self.days, }
def serialize(self) -> Dict[str, Any]: return { 'id': self.id, 'href': absolute_url('/user/' + self.id), 'name': self.name, 'login': self.login, 'email': self.email, 'domain': self.domain, 'status': self.status, 'roles': self.roles, 'attributes': self.attributes, 'createTime': self.create_time, 'lastLogin': self.last_login, 'text': self.text, 'updateTime': self.update_time, 'email_verified': self.email_verified or False }
def create_twilio_rule(): try: twilio_rule = TwilioRule.parse(request.json) except Exception as e: raise ApiError(str(e), 400) if Scope.admin in g.scopes or Scope.admin_twilio_rules in g.scopes: twilio_rule.user = twilio_rule.user or g.login else: twilio_rule.user = g.login twilio_rule.customer = assign_customer(wanted=twilio_rule.customer, permission=Scope.admin_twilio_rules) try: twilio_rule = twilio_rule.create() except Exception as e: raise ApiError(str(e), 500) write_audit_trail.send( current_app._get_current_object(), event='twiliorule-created', message='', user=g.login, customers=g.customers, scopes=g.scopes, resource_id=twilio_rule.id, type='twilio_rule', request=request, ) if twilio_rule: return ( jsonify(status='ok', id=twilio_rule.id, twilioRule=twilio_rule.serialize), 201, { 'Location': absolute_url('/twiliorule/' + twilio_rule.id) }, ) else: raise ApiError('insert twilio rule failed', 500)
def build_slack_response(alert: Alert, action: str, user: str, data: ImmutableMultiDict) -> JSON: response = json.loads(data['payload']).get('original_message', {}) actions = ['watch', 'unwatch'] message = ('User {user} is {action}ing alert {alert}' if action in actions else 'The status of alert {alert} is {status} now!').format( alert=alert.get_id(short=True), status=alert.status.capitalize(), action=action, user=user) attachment_response = { 'fallback': message, 'pretext': 'Action done!', 'color': '#808080', 'title': message, 'title_link': absolute_url('/alert/' + alert.id) } # clear interactive buttons and add new attachment as response of action if action not in actions: attachments = response.get('attachments', []) for attachment in attachments: attachment.pop('actions', None) attachments.append(attachment_response) response['attachments'] = attachments return response # update the interactive button of all actions next_action = actions[(actions.index(action) + 1) % len(actions)] for attachment in response.get('attachments', []): for attached_action in attachment.get('actions', []): if action == attached_action.get('value'): attached_action.update({ 'name': next_action, 'value': next_action, 'text': next_action.capitalize() }) return response
def serialize(self) -> Dict[str, Any]: return { 'id': self.id, 'href': absolute_url('/blackout/' + self.id), 'priority': self.priority, 'environment': self.environment, 'service': self.service, 'resource': self.resource, 'event': self.event, 'group': self.group, 'tags': self.tags, 'customer': self.customer, 'startTime': self.start_time, 'endTime': self.end_time, 'duration': self.duration, 'status': self.status, 'remaining': self.remaining, 'user': self.user, 'createTime': self.create_time, 'text': self.text }
def config(): return jsonify({ 'debug': current_app.debug, 'endpoint': absolute_url().rstrip('/'), # FIXME - shouldn't need to rstrip() 'alarm_model': { 'name': alarm_model.name, 'severity': alarm_model.Severity, 'colors': alarm_model.Colors, 'status': alarm_model.Status }, 'auth_required': current_app.config['AUTH_REQUIRED'], 'provider': current_app.config['AUTH_PROVIDER'], 'customer_views': current_app.config['CUSTOMER_VIEWS'], 'signup_enabled': current_app.config['SIGNUP_ENABLED'] if current_app.config['AUTH_PROVIDER'] == 'basic' else False, 'email_verification': current_app.config['EMAIL_VERIFICATION'], 'client_id': current_app.config['OAUTH2_CLIENT_ID'], 'azure_tenant': current_app.config['AZURE_TENANT'], 'github_url': current_app.config['GITHUB_URL'], 'gitlab_url': current_app.config['GITLAB_URL'], 'keycloak_url': current_app.config['KEYCLOAK_URL'], 'keycloak_realm': current_app.config['KEYCLOAK_REALM'], 'oidc_auth_url': current_app.config['OIDC_AUTH_URL'], 'pingfederate_url': current_app.config['PINGFEDERATE_URL'], 'site_logo_url': current_app.config['SITE_LOGO_URL'], 'severity': alarm_model.Severity, # FIXME - moved to alarm model 'colors': alarm_model.Colors, # FIXME - moved to alarm model 'dates': { 'shortTime': current_app.config['DATE_FORMAT_SHORT_TIME'], 'mediumDate': current_app.config['DATE_FORMAT_MEDIUM_DATE'], 'longDate': current_app.config['DATE_FORMAT_LONG_DATE'] }, 'audio': { 'new': current_app.config['DEFAULT_AUDIO_FILE'] }, 'columns': current_app.config['COLUMNS'], 'sort_by': current_app.config['SORT_LIST_BY'], 'actions': current_app.config['ACTIONS'], 'tracking_id': current_app.config['GOOGLE_TRACKING_ID'], 'refresh_interval': current_app.config['AUTO_REFRESH_INTERVAL'] })
def bulk_action_alert(): from alerta.tasks import action_alerts action = request.json.get('action', None) text = request.json.get('text', 'bulk status update') timeout = request.json.get('timeout', None) if not action: raise ApiError("must supply 'action' as json data", 400) query = qb.from_params(request.args) alerts = [alert.id for alert in Alert.find_all(query)] if not alerts: raise ApiError('not found', 404) task = action_alerts.delay(alerts, action, text, timeout) return jsonify(status='ok', message=f'{len(alerts)} alerts queued for action'), 202, { 'Location': absolute_url('/_bulk/task/' + task.id) }
def parse(cls, token: str, key: str = None, verify: bool = True, algorithm: str = 'HS256') -> 'Jwt': try: json = jwt.decode(token, key=key or current_app.config['SECRET_KEY'], verify=verify, algorithms=algorithm, audience=current_app.config['OAUTH2_CLIENT_ID'] or current_app.config['SAML2_ENTITY_ID'] or absolute_url()) except (DecodeError, ExpiredSignatureError, InvalidAudienceError): raise return Jwt( iss=json.get('iss', None), typ=json.get('typ', None), sub=json.get('sub', None), aud=json.get('aud', None), exp=json.get('exp', None), nbf=json.get('nbf', None), iat=json.get('iat', None), jti=json.get('jti', None), name=json.get('name', None), preferred_username=json.get('preferred_username', None), email=json.get('email', None), provider=json.get('provider', None), orgs=json.get('orgs', list()), groups=json.get('groups', list()), roles=json.get('roles', list()), scopes=json.get('scope', '').split( ' '), # eg. scope='read write' => scopes=['read', 'write'] email_verified=json.get('email_verified', None), picture=json.get('picture', None), customers=[json['customer']] if 'customer' in json else json.get( 'customers', list()), oid=json.get('oid'))
def create_blackout(): try: blackout = Blackout.parse(request.json) except Exception as e: raise ApiError(str(e), 400) if Scope.admin in g.scopes or Scope.admin_blackouts in g.scopes: blackout.user = blackout.user or g.user else: blackout.user = g.user blackout.customer = assign_customer(wanted=blackout.customer, permission=Scope.admin_blackouts) try: blackout = blackout.create() except Exception as e: raise ApiError(str(e), 500) write_audit_trail.send(current_app._get_current_object(), event='blackout-created', message='', user=g.user, customers=g.customers, scopes=g.scopes, resource_id=blackout.id, type='blackout', request=request) if blackout: return jsonify(status='ok', id=blackout.id, blackout=blackout.serialize), 201, { 'Location': absolute_url('/blackout/' + blackout.id) } else: raise ApiError('insert blackout failed', 500)
def build_slack_response(alert: Alert, action: str, user: str, data: ImmutableMultiDict) -> JSON: response = json.loads(data['payload']).get('original_message', {}) actions = ['watch', 'unwatch'] message = ( 'User {user} is {action}ing alert {alert}' if action in actions else 'The status of alert {alert} is {status} now!').format( alert=alert.get_id(short=True), status=alert.status.capitalize(), action=action, user=user ) attachment_response = { 'fallback': message, 'pretext': 'Action done!', 'color': '#808080', 'title': message, 'title_link': absolute_url('/alert/' + alert.id) } # clear interactive buttons and add new attachment as response of action if action not in actions: attachments = response.get('attachments', []) for attachment in attachments: attachment.pop('actions', None) attachments.append(attachment_response) response['attachments'] = attachments return response # update the interactive button of all actions next_action = actions[(actions.index(action) + 1) % len(actions)] for attachment in response.get('attachments', []): for attached_action in attachment.get('actions', []): if action == attached_action.get('value'): attached_action.update({ 'name': next_action, 'value': next_action, 'text': next_action.capitalize() }) return response
def bulk_action_alert(): from alerta.tasks import action_alerts action = request.json.get('action', None) text = request.json.get('text', 'bulk status update') timeout = request.json.get('timeout', None) if not action: raise ApiError("must supply 'action' as json data", 400) query = qb.from_params(request.args) alerts = [alert.id for alert in Alert.find_all(query)] if not alerts: raise ApiError('not found', 404) task = action_alerts.delay(alerts, action, text, timeout) return jsonify(status='ok', message='{} alerts queued for action'.format(len(alerts))), 202, {'Location': absolute_url('/_bulk/task/' + task.id)}