sources/ldap: migrate to web

Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
This commit is contained in:
Jens Langhammer 2021-04-02 12:12:14 +02:00
parent 742f570c4c
commit 70fc4c0d88
7 changed files with 262 additions and 87 deletions

View File

@ -1,7 +1,6 @@
"""Source API Views""" """Source API Views"""
from typing import Iterable from typing import Iterable
from django.urls import reverse
from drf_yasg.utils import swagger_auto_schema from drf_yasg.utils import swagger_auto_schema
from rest_framework import mixins from rest_framework import mixins
from rest_framework.decorators import action from rest_framework.decorators import action
@ -72,8 +71,7 @@ class SourceViewSet(
{ {
"name": verbose_name(subclass), "name": verbose_name(subclass),
"description": subclass.__doc__, "description": subclass.__doc__,
"link": reverse("authentik_admin:source-create") "link": subclass().component,
+ f"?type={subclass.__name__}",
} }
) )
return Response(TypeCreateSerializer(data, many=True).data) return Response(TypeCreateSerializer(data, many=True).data)

View File

@ -275,6 +275,11 @@ class Source(SerializerModel, PolicyBindingModel):
objects = InheritanceManager() objects = InheritanceManager()
@property
def component(self) -> str:
"""Return component used to edit this object"""
raise NotImplementedError
@property @property
def form(self) -> Type[ModelForm]: def form(self) -> Type[ModelForm]:
"""Return Form class used to edit this object""" """Return Form class used to edit this object"""

View File

@ -1,13 +0,0 @@
{% extends base_template|default:"generic/form.html" %}
{% load i18n %}
{% block above_form %}
<h1>
{% trans 'Import SAML Metadata' %}
</h1>
{% endblock %}
{% block action %}
{% trans 'Import Metadata' %}
{% endblock %}

View File

@ -1,60 +0,0 @@
"""authentik LDAP Forms"""
from django import forms
from django.utils.translation import gettext_lazy as _
from authentik.sources.ldap.models import LDAPPropertyMapping, LDAPSource
class LDAPSourceForm(forms.ModelForm):
"""LDAPSource Form"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["property_mappings"].queryset = LDAPPropertyMapping.objects.all()
self.fields[
"property_mappings_group"
].queryset = LDAPPropertyMapping.objects.all()
class Meta:
model = LDAPSource
fields = [
# we don't use all common fields, as we don't use flows for this
"name",
"slug",
"enabled",
"policy_engine_mode",
# -- start of our custom fields
"server_uri",
"start_tls",
"bind_cn",
"bind_password",
"base_dn",
"sync_users",
"sync_users_password",
"sync_groups",
"property_mappings",
"property_mappings_group",
"additional_user_dn",
"additional_group_dn",
"user_object_filter",
"group_object_filter",
"group_membership_field",
"object_uniqueness_field",
"sync_parent_group",
]
labels = {"property_mappings_group": _("Group property mappings")}
widgets = {
"name": forms.TextInput(),
"server_uri": forms.TextInput(),
"bind_cn": forms.TextInput(),
"bind_password": forms.TextInput(),
"base_dn": forms.TextInput(),
"additional_user_dn": forms.TextInput(),
"additional_group_dn": forms.TextInput(),
"user_object_filter": forms.TextInput(),
"group_object_filter": forms.TextInput(),
"group_membership_field": forms.TextInput(),
"object_uniqueness_field": forms.TextInput(),
}

View File

@ -2,7 +2,6 @@
from typing import Optional, Type from typing import Optional, Type
from django.db import models from django.db import models
from django.forms import ModelForm
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from ldap3 import ALL, Connection, Server from ldap3 import ALL, Connection, Server
from rest_framework.serializers import Serializer from rest_framework.serializers import Serializer
@ -73,10 +72,8 @@ class LDAPSource(Source):
) )
@property @property
def form(self) -> Type[ModelForm]: def component(self) -> str:
from authentik.sources.ldap.forms import LDAPSourceForm return "ak-source-ldap-form"
return LDAPSourceForm
@property @property
def serializer(self) -> Type[Serializer]: def serializer(self) -> Type[Serializer]:

View File

@ -8,11 +8,14 @@ import "../../elements/buttons/ModalButton";
import "../../elements/buttons/SpinnerButton"; import "../../elements/buttons/SpinnerButton";
import "../../elements/buttons/Dropdown"; import "../../elements/buttons/Dropdown";
import "../../elements/forms/DeleteForm"; import "../../elements/forms/DeleteForm";
import "../../elements/forms/ModalForm";
import "../../elements/forms/ProxyForm";
import { until } from "lit-html/directives/until"; import { until } from "lit-html/directives/until";
import { PAGE_SIZE } from "../../constants"; import { PAGE_SIZE } from "../../constants";
import { Source, SourcesApi } from "authentik-api"; import { Source, SourcesApi } from "authentik-api";
import { DEFAULT_CONFIG } from "../../api/Config"; import { DEFAULT_CONFIG } from "../../api/Config";
import { AdminURLManager } from "../../api/legacy"; import { ifDefined } from "lit-html/directives/if-defined";
import "./ldap/LDAPSourceForm";
@customElement("ak-source-list") @customElement("ak-source-list")
export class SourceListPage extends TablePage<Source> { export class SourceListPage extends TablePage<Source> {
@ -57,12 +60,27 @@ export class SourceListPage extends TablePage<Source> {
</a>`, </a>`,
html`${item.verboseName}`, html`${item.verboseName}`,
html` html`
<ak-modal-button href="${AdminURLManager.sources(`${item.pk}/update/`)}"> <ak-forms-modal>
<ak-spinner-button slot="trigger" class="pf-m-secondary"> <span slot="submit">
${gettext("Update")}
</span>
<span slot="header">
${gettext(`Update ${item.verboseName}`)}
</span>
<ak-proxy-form
slot="form"
.args=${{
"sourceSlug": item.slug
}}
type=${ifDefined(item.objectType)}
.typeMap=${{
"ldap": "ak-source-ldap-form",
}}>
</ak-proxy-form>
<button slot="trigger" class="pf-c-button pf-m-secondary">
${gettext("Edit")} ${gettext("Edit")}
</ak-spinner-button> </button>
<div slot="modal"></div> </ak-forms-modal>
</ak-modal-button>
<ak-forms-delete <ak-forms-delete
.obj=${item} .obj=${item}
objectLabel=${gettext("Source")} objectLabel=${gettext("Source")}

View File

@ -0,0 +1,230 @@
import { LDAPSource, SourcesApi, PropertymappingsApi } from "authentik-api";
import { gettext } from "django";
import { customElement, property } from "lit-element";
import { html, TemplateResult } from "lit-html";
import { DEFAULT_CONFIG } from "../../../api/Config";
import { Form } from "../../../elements/forms/Form";
import "../../../elements/forms/FormGroup";
import "../../../elements/forms/HorizontalFormElement";
import { ifDefined } from "lit-html/directives/if-defined";
import { until } from "lit-html/directives/until";
@customElement("ak-source-ldap-form")
export class LDAPSourceForm extends Form<LDAPSource> {
set sourceSlug(value: string) {
new SourcesApi(DEFAULT_CONFIG).sourcesLdapRead({
slug: value,
}).then(source => {
this.source = source;
});
}
@property({attribute: false})
source?: LDAPSource;
getSuccessMessage(): string {
if (this.source) {
return gettext("Successfully updated source.");
} else {
return gettext("Successfully created source.");
}
}
send = (data: LDAPSource): Promise<LDAPSource> => {
if (this.source) {
return new SourcesApi(DEFAULT_CONFIG).sourcesLdapUpdate({
slug: this.source.slug,
data: data
});
} else {
return new SourcesApi(DEFAULT_CONFIG).sourcesLdapCreate({
data: data
});
}
};
renderForm(): TemplateResult {
return html`<form class="pf-c-form pf-m-horizontal">
<ak-form-element-horizontal
label=${gettext("Name")}
?required=${true}
name="name">
<input type="text" value="${ifDefined(this.source?.name)}" class="pf-c-form-control" required>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${gettext("Slug")}
?required=${true}
name="slug">
<input type="text" value="${ifDefined(this.source?.slug)}" class="pf-c-form-control" required>
</ak-form-element-horizontal>
<ak-form-element-horizontal name="enabled">
<div class="pf-c-check">
<input type="checkbox" class="pf-c-check__input" ?checked=${this.source?.enabled || true}>
<label class="pf-c-check__label">
${gettext("Enabled")}
</label>
</div>
</ak-form-element-horizontal>
<ak-form-element-horizontal name="syncUsers">
<div class="pf-c-check">
<input type="checkbox" class="pf-c-check__input" ?checked=${this.source?.syncUsers || true}>
<label class="pf-c-check__label">
${gettext("Sync users")}
</label>
</div>
</ak-form-element-horizontal>
<ak-form-element-horizontal name="syncUsersPassword">
<div class="pf-c-check">
<input type="checkbox" class="pf-c-check__input" ?checked=${this.source?.syncUsersPassword || true}>
<label class="pf-c-check__label">
${gettext("Sync users' passwords")}
</label>
</div>
</ak-form-element-horizontal>
<ak-form-element-horizontal name="syncGroups">
<div class="pf-c-check">
<input type="checkbox" class="pf-c-check__input" ?checked=${this.source?.syncGroups || true}>
<label class="pf-c-check__label">
${gettext("Sync groups")}
</label>
</div>
</ak-form-element-horizontal>
<ak-form-group .expanded=${true}>
<span slot="header">
${gettext("Connection settings")}
</span>
<div slot="body" class="pf-c-form">
<ak-form-element-horizontal
label=${gettext("Server URI")}
?required=${true}
name="serverUri">
<input type="text" value="${ifDefined(this.source?.serverUri)}" class="pf-c-form-control" required>
</ak-form-element-horizontal>
<ak-form-element-horizontal name="startTls">
<div class="pf-c-check">
<input type="checkbox" class="pf-c-check__input" ?checked=${this.source?.startTls || true}>
<label class="pf-c-check__label">
${gettext("Enable StartTLS")}
</label>
</div>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${gettext("Bind CN")}
?required=${true}
name="bindCn">
<input type="text" value="${ifDefined(this.source?.bindCn)}" class="pf-c-form-control" required>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${gettext("Bind Password")}
?required=${true}
name="bindPassword">
<input type="text" value="${ifDefined(this.source?.bindPassword)}" class="pf-c-form-control" required>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${gettext("Base DN")}
?required=${true}
name="baseDn">
<input type="text" value="${ifDefined(this.source?.baseDn)}" class="pf-c-form-control" required>
</ak-form-element-horizontal>
</div>
</ak-form-group>
<ak-form-group>
<span slot="header">
${gettext("Advanced settings")}
</span>
<div slot="body" class="pf-c-form">
<ak-form-element-horizontal
label=${gettext("User Property Mappings")}
?required=${true}
name="propertyMappings">
<select class="pf-c-form-control" multiple>
${until(new PropertymappingsApi(DEFAULT_CONFIG).propertymappingsLdapList({
ordering: "object_field"
}).then(mappings => {
return mappings.results.map(mapping => {
let selected = false;
if (!this.source?.propertyMappings) {
selected = mapping.managed?.startsWith("goauthentik.io/sources/ldap/default") || mapping.managed?.startsWith("goauthentik.io/sources/ldap/ms") || false;
} else {
selected = Array.from(this.source?.propertyMappings).some(su => {
return su == mapping.pk;
});
}
return html`<option value=${ifDefined(mapping.pk)} ?selected=${selected}>${mapping.name}</option>`;
});
}))}
</select>
<p class="pf-c-form__helper-text">${gettext("Property mappings used to user creation.")}</p>
<p class="pf-c-form__helper-text">${gettext("Hold control/command to select multiple items.")}</p>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${gettext("Group Property Mappings")}
?required=${true}
name="propertyMappingsGroup">
<select class="pf-c-form-control" multiple>
${until(new PropertymappingsApi(DEFAULT_CONFIG).propertymappingsLdapList({
ordering: "object_field"
}).then(mappings => {
return mappings.results.map(mapping => {
let selected = false;
if (!this.source?.propertyMappingsGroup) {
selected = mapping.managed === "goauthentik.io/sources/ldap/default-name";
} else {
selected = Array.from(this.source?.propertyMappingsGroup).some(su => {
return su == mapping.pk;
});
}
return html`<option value=${ifDefined(mapping.pk)} ?selected=${selected}>${mapping.name}</option>`;
});
}))}
</select>
<p class="pf-c-form__helper-text">${gettext("Property mappings used to group creation.")}</p>
<p class="pf-c-form__helper-text">${gettext("Hold control/command to select multiple items.")}</p>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${gettext("Addition User DN")}
name="additionalUserDn">
<input type="text" value="${ifDefined(this.source?.additionalUserDn)}" class="pf-c-form-control">
<p class="pf-c-form__helper-text">${gettext("Additional user DN, prepended to the Base DN.")}</p>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${gettext("Addition Group DN")}
name="additionalGroupDn">
<input type="text" value="${ifDefined(this.source?.additionalGroupDn)}" class="pf-c-form-control">
<p class="pf-c-form__helper-text">${gettext("Additional group DN, prepended to the Base DN.")}</p>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${gettext("User object filter")}
?required=${true}
name="userObjectFilter">
<input type="text" value="${this.source?.userObjectFilter || "(objectClass=person)"}" class="pf-c-form-control" required>
<p class="pf-c-form__helper-text">${gettext("Consider Objects matching this filter to be Users.")}</p>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${gettext("Group object filter")}
?required=${true}
name="groupObjectFilter">
<input type="text" value="${this.source?.groupObjectFilter || "(objectClass=group)"}" class="pf-c-form-control" required>
<p class="pf-c-form__helper-text">${gettext("Consider Objects matching this filter to be Groups.")}</p>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${gettext("Group membership field")}
?required=${true}
name="groupMembershipField">
<input type="text" value="${this.source?.groupMembershipField || "member"}" class="pf-c-form-control" required>
<p class="pf-c-form__helper-text">${gettext("Field which contains members of a group.")}</p>
</ak-form-element-horizontal>
<ak-form-element-horizontal
label=${gettext("Object uniqueness field")}
?required=${true}
name="objectUniquenessField">
<input type="text" value="${this.source?.objectUniquenessField || "objectSid"}" class="pf-c-form-control" required>
<p class="pf-c-form__helper-text">${gettext("Field which contains a unique Identifier.")}</p>
</ak-form-element-horizontal>
</div>
</ak-form-group>
</form>`;
}
}