events: add event context to slack webhook

This commit is contained in:
Jens Langhammer 2021-01-14 17:40:19 +01:00
parent eef111bcfd
commit 42c6401ba7
1 changed files with 24 additions and 17 deletions

View File

@ -139,9 +139,7 @@ class Event(models.Model):
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
if not self._state.adding: if not self._state.adding:
raise ValidationError( raise ValidationError("you may not edit an existing Event")
"you may not edit an existing %s" % self._meta.model_name
)
LOGGER.debug( LOGGER.debug(
"Created Event", "Created Event",
action=self.action, action=self.action,
@ -209,7 +207,7 @@ class NotificationTransport(models.Model):
) )
response.raise_for_status() response.raise_for_status()
except RequestException as exc: except RequestException as exc:
raise NotificationTransportError from exc raise NotificationTransportError(exc.response.text) from exc
return [ return [
response.status_code, response.status_code,
response.text, response.text,
@ -217,6 +215,26 @@ class NotificationTransport(models.Model):
def send_webhook_slack(self, notification: "Notification") -> list[str]: def send_webhook_slack(self, notification: "Notification") -> list[str]:
"""Send notification to slack or slack-compatible endpoints""" """Send notification to slack or slack-compatible endpoints"""
fields = [
{
"title": _("Severity"),
"value": notification.severity,
"short": True,
},
{
"title": _("Dispatched for user"),
"value": str(notification.user),
"short": True,
},
]
if notification.event:
for key, value in notification.event.context.items():
if not isinstance(value, str):
continue
# https://birdie0.github.io/discord-webhooks-guide/other/field_limits.html
if len(fields) >= 25:
continue
fields.append({"title": key[:256], "value": value[:1024]})
body = { body = {
"username": "authentik", "username": "authentik",
"icon_url": "https://goauthentik.io/img/icon.png", "icon_url": "https://goauthentik.io/img/icon.png",
@ -227,18 +245,7 @@ class NotificationTransport(models.Model):
"author_icon": "https://goauthentik.io/img/icon.png", "author_icon": "https://goauthentik.io/img/icon.png",
"title": notification.body, "title": notification.body,
"color": "#fd4b2d", "color": "#fd4b2d",
"fields": [ "fields": fields,
{
"title": _("Severity"),
"value": notification.severity,
"short": True,
},
{
"title": _("Dispatched for user"),
"value": str(notification.user),
"short": True,
},
],
"footer": f"authentik v{__version__}", "footer": f"authentik v{__version__}",
} }
], ],
@ -250,7 +257,7 @@ class NotificationTransport(models.Model):
response = post(self.webhook_url, json=body) response = post(self.webhook_url, json=body)
response.raise_for_status() response.raise_for_status()
except RequestException as exc: except RequestException as exc:
raise NotificationTransportError from exc raise NotificationTransportError(exc.response.text) from exc
return [ return [
response.status_code, response.status_code,
response.text, response.text,