feat(usermanager): implement group creation view

This commit is contained in:
Julian Lobbes 2022-11-30 17:04:28 +01:00
parent c158697f7b
commit 182c17ebac
4 changed files with 241 additions and 11 deletions

View File

@ -0,0 +1,164 @@
class UserEntry {
constructor(username, isMember, rowElement) {
this.username = username;
this.isMember = isMember;
this.rowElement = rowElement;
this.buttonElement = $(rowElement).find(".toggleMembershipButton");
if (isMember) {
$(this.buttonElement).click(() => this.onClickLeave());
} else {
$(this.buttonElement).click(() => this.onClickJoin());
}
}
onClickLeave() {
this.isMember = false;
$(this.buttonElement).off("click");
$(this.buttonElement).click(() => this.onClickJoin());
$(this.rowElement).prependTo($("#tableNonMembers").find("tbody"));
this.setButtonAppearanceJoinGroup();
if (membersTableIsEmpty()) {
showEmptyTableNotice();
}
disableCreateGroupButton();
}
onClickJoin() {
this.isMember = true;
$(this.buttonElement).off("click");
$(this.buttonElement).click(() => this.onClickLeave());
$(this.rowElement).prependTo($("#tableMembers").find("tbody"));
this.setButtonAppearanceLeaveGroup();
hideEmptyTableNotice();
enableCreateGroupButton();
}
setButtonAppearanceLeaveGroup() {
this.buttonElement.removeClass("btn-danger btn-success btn-secondary");
this.buttonElement.addClass("btn-danger");
this.buttonElement.empty();
this.buttonElement.html(
'<i class="bi-person-fill-x"></i> Cancel'
);
}
setButtonAppearanceJoinGroup() {
this.buttonElement.removeClass("btn-danger btn-success btn-secondary");
this.buttonElement.addClass("btn-success");
this.buttonElement.empty();
this.buttonElement.html(
'<i class="bi-person-fill-add"></i> Add'
);
}
}
function showErrorMessage(message) {
$("nav").after([
'<div class="alert alert-danger alert-dismissible" role="alert">',
`<div>${message}</div>`,
'<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
'</div>'
].join(''));
}
function getGroupMembers() {
let groupMembers = [];
for (entry of $(membersTable).find(".userEntry")) {
groupMembers.push(entry.id);
}
return groupMembers;
}
function getGroupName() {
return $(groupNameInput).val();
}
function getUserEntries() {
let userEntries = [];
for (let entry of nonMembersTable.find("tbody").find(".userEntry")) {
userEntries.push(new UserEntry(
entry.id,
false,
entry
));
}
return userEntries;
}
function membersTableIsEmpty() {
return $(membersTable).find("tbody").find(".userEntry").length === 0
}
function hideEmptyTableNotice() {
if (emptyTableNotice.parent().length != 0) {
emptyTableNotice.remove();
}
}
function showEmptyTableNotice() {
if (emptyTableNotice.parent().length == 0) {
$(membersTable).find("tbody").append($(emptyTableNotice));
}
}
function disableCreateGroupButton() {
if ($(groupNameInput).val().length == 0 || membersTableIsEmpty()) {
createGroupButton[0].disabled = true;
}
}
function enableCreateGroupButton() {
if ($(groupNameInput).val().length > 0 && !membersTableIsEmpty()) {
createGroupButton[0].disabled = false;
}
}
function createGroupButtonOnClick() {
$.ajax({
url: `/api/group/${getGroupName()}`,
type: "POST",
contentType: 'application/json',
data: JSON.stringify({
"members": getGroupMembers()
}),
dataType: "json",
}).done(function() {
window.location.replace(window.location.origin + `/groups/update/${getGroupName()}`);
}).fail(function(xhr, status, errorThrown) {
console.log(`Error: ${errorThrown}`);
console.log(`Status: ${status}`);
displayTextInputError(xhr.responseJSON['message']);
});
}
function displayTextInputError(message) {
$(createGroupButton).after([
'<div class="alert alert-danger alert-dismissible m-2" role="alert">',
`<div>${message}</div>`,
'<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
'</div>'
].join(''));
}
let nonMembersTable = undefined;
let membersTable = undefined;
let entries = undefined;
let emptyTableNotice = undefined;
let createGroupButton = undefined;
let groupNameInput = undefined;
$(document).ready(function() {
nonMembersTable = $("#tableNonMembers");
membersTable = $("#tableMembers");
entries = getUserEntries();
emptyTableNotice = $("#emptyTableNotice");
createGroupButton = $("#createGroupButton");
groupNameInput = $("#groupNameInput");
disableCreateGroupButton();
$(groupNameInput).on("input", function() {
enableCreateGroupButton();
disableCreateGroupButton();
});
createGroupButton.click(createGroupButtonOnClick);
});

View File

@ -0,0 +1,63 @@
{% extends 'base.html' %}
{% block content %}
<div class="row">
<div class="col text-center">
<h1>Create a new Group</h1>
</div>
</div>
<div class="row align-items-center border rounded m-2">
<label for="groupNameInput" class="col-sm-2 col-form-label text-end m-2">Group Name</label>
<input type="text" class="col-sm form-control m-2" id="groupNameInput">
<a class="col-sm-2 btn btn-secondary m-2" href="{{ url_for('usermanager.group_list') }}" role="button">Cancel</a>
<button class="col-sm-2 btn btn-primary m-2" type="button" id="createGroupButton">Create Group</button>
<p class="col-sm-12 text-danger">
</div>
<div class="row border rounded m-2">
<table class="table table-hover align-middle" id="tableMembers">
<thead>
<tr>
<th class="text-center" scope="col" colspan="3">Members</th>
</tr>
</thead>
<tbody>
<tr class="text-center" id="emptyTableNotice">
<th scope="row" colspan="3">
<p class="text-danger">You must add at least one member.</p>
</th>
</tr>
</tbody>
</table>
</div>
<div class="row border rounded m-2">
<table class="table table-hover align-middle" id="tableNonMembers">
<thead>
<tr>
<th class="text-center" scope="col" colspan="3">Other Users</th>
</tr>
</thead>
<tbody>
{% for user in users|sort %}
<tr class="userEntry text-center" id="{{ user.username }}">
<th scope="row">
<img src="{{ user.get_thumbnail_url() }}"
alt="Profile picture for user {{ user.username }}"
class="img-fluid rounded"
style="max-width: 50px"
>
</th>
<td>
<a href="{{ url_for('usermanager.user_view', username=user.username)}}">{{ user.username }}</a>
</td>
<td>
<button type="button" class="toggleMembershipButton btn btn-success">
<i class="bi-person-fill-add"></i> Add
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<script src="{{ url_for('static', filename='js/group_create.js') }}"></script>
{% endblock content %}

View File

@ -343,18 +343,25 @@ def group_list():
)
@bp.route("/groups/create", methods=("GET", "POST"))
@bp.route("/groups/create")
def group_create():
"""Displays a form allowing group creation."""
"""Creation view for a new group.
Shows a table allowing adding members to this group.
"""
try:
conn = ldap.get_connection()
except Exception:
abort(500)
users = ldap.get_users(conn)
conn.unbind()
# TODO implement
abort(404)
return render_template(
'usermanager/group_create.html',
users=users,
)
@bp.route("/groups/update/<string:groupname>")

View File

@ -462,8 +462,8 @@ class Group:
def assert_is_valid_groupname(input_str: str) -> None:
"""Checks whether the input string is a valid group name.
A valid group name consists of only alphanumeric characters, starts with
a latin character, has minimum length 1 and maximim length 64.
A valid group name consists of only alphabetic characters, has minimum
length 1 and maximum length 64.
Parameters
----------
@ -485,12 +485,8 @@ class Group:
raise InvalidStringFormatException(
"Invalid group name: must contain at least one character."
)
if input_str[0] not in ascii_lowercase + ascii_uppercase:
raise InvalidStringFormatException(
"Invalid group name: must start with a letter."
)
for char in input_str:
if not char in ascii_uppercase + ascii_lowercase + digits:
if not char in ascii_uppercase + ascii_lowercase:
raise InvalidStringFormatException(
f"Invalid character in group name: '{char}'."
)