From 245e68c5ba1189a1707b49554dd9cd8f4e703a00 Mon Sep 17 00:00:00 2001 From: ToxicMushroom <32853531+ToxicMushroom@users.noreply.github.com> Date: Fri, 23 Aug 2024 02:47:54 +0200 Subject: [PATCH] - Form validation - Editable emails - Basic profile updating --- server/core/Cargo.toml | 2 +- server/core/src/https/views/mod.rs | 13 + server/core/src/https/views/profile.rs | 226 +++++++++++++++++- server/core/static/external/forms.js | 25 ++ .../static/external/htmx_bs_validation.js | 34 +++ server/core/static/style.css | 1 + server/core/templates/user_settings.html | 2 + ...ifiable_entry_modifiable_list_partial.html | 7 + .../profile_changes_partial.html | 89 +++++++ .../user_settings_profile_partial.html | 50 ++-- 10 files changed, 429 insertions(+), 20 deletions(-) create mode 100644 server/core/static/external/forms.js create mode 100644 server/core/static/external/htmx_bs_validation.js create mode 100644 server/core/templates/user_settings/form_modifiable_entry_modifiable_list_partial.html create mode 100644 server/core/templates/user_settings/profile_changes_partial.html diff --git a/server/core/Cargo.toml b/server/core/Cargo.toml index 1c753cb44..b7ab2004c 100644 --- a/server/core/Cargo.toml +++ b/server/core/Cargo.toml @@ -24,7 +24,7 @@ askama = { workspace = true, features = ["with-axum"] } askama_axum = { workspace = true } axum = { workspace = true } axum-htmx = { workspace = true } -axum-extra = { version = "0.9.6", features = ["cookie"] } +axum-extra = { version = "0.9.6", features = ["cookie", "form"] } axum-macros = "0.4.2" axum-server = { version = "0.7.1", default-features = false } bytes = { workspace = true } diff --git a/server/core/src/https/views/mod.rs b/server/core/src/https/views/mod.rs index b52546180..ffc74c916 100644 --- a/server/core/src/https/views/mod.rs +++ b/server/core/src/https/views/mod.rs @@ -56,6 +56,7 @@ pub fn view_router() -> Router<ServerState> { .route("/reset", get(reset::view_reset_get)) .route("/update_credentials", get(reset::view_self_reset_get)) .route("/profile", get(profile::view_profile_get)) + .route("/profile/diff", get(profile::view_profile_get)) .route("/profile/unlock", get(profile::view_profile_unlock_get)) .route("/logout", get(login::view_logout_get)) .route("/oauth2", get(oauth2::view_index_get)); @@ -129,6 +130,18 @@ pub fn view_router() -> Router<ServerState> { ) .route("/api/cu_cancel", post(reset::cancel_cred_update)) .route("/api/cu_commit", post(reset::commit)) + .route( + "/api/user_settings/add_email", + post(profile::view_new_email_entry_partial), + ) + .route( + "/api/user_settings/edit_profile", + post(profile::view_profile_diff_start_save_post), + ) + .route( + "/api/user_settings/confirm_profile", + post(profile::view_profile_diff_confirm_save_post), + ) .layer(HxRequestGuardLayer::new("/ui")); let admin_router = admin_router(); diff --git a/server/core/src/https/views/profile.rs b/server/core/src/https/views/profile.rs index 9d00bbe1c..93e58ea3b 100644 --- a/server/core/src/https/views/profile.rs +++ b/server/core/src/https/views/profile.rs @@ -7,6 +7,8 @@ use axum::extract::State; use axum::response::Response; use axum::Extension; use axum_extra::extract::cookie::CookieJar; +use axum_htmx::{HxPushUrl, HxRequest}; +use futures_util::TryFutureExt; use kanidm_proto::internal::UserAuthToken; use super::constants::{ProfileMenuItems, UiMessage, Urls}; @@ -26,9 +28,43 @@ pub(crate) struct ProfileView { struct ProfilePartialView { menu_active_item: ProfileMenuItems, can_rw: bool, + attrs: ProfileAttributes, + posix_enabled: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub(crate) struct ProfileAttributes { account_name: String, display_name: String, - email: Option<String>, + legal_name: String, + #[serde(rename = "emails[]")] + emails: Vec<String>, + primary_email: Option<String>, +} + +#[derive(Template, Clone)] +#[template(path = "user_settings/profile_changes_partial.html")] +struct ProfileChangesPartialView { + can_rw: bool, + attrs: ProfileAttributes, + new_attrs: ProfileAttributes +} + +#[derive(Template, Clone)] +#[template(path = "user_settings/form_modifiable_entry_modifiable_list_partial.html")] +// Modifiable entry in a modifiable list partial +pub(crate) struct FormModEntryModListPartial { + can_rw: bool, + r#type: String, + name: String, + value: String, + invalid_feedback: String, +} + +impl Display for ProfileAttributes { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{self:?}") + } } pub(crate) async fn view_profile_get( @@ -42,6 +78,21 @@ pub(crate) async fn view_profile_get( .handle_whoami_uat(client_auth_info, kopid.eventid) .await?; + let filter = filter_all!(f_and!([f_eq( + Attribute::Uuid, + PartialValue::Uuid(uat.uuid) + )])); + let base: Vec<Entry> = state + .qe_r_ref + .handle_internalsearch(client_auth_info.clone(), filter, None, kopid.eventid) + .map_err(|op_err| HtmxError::new(&kopid, op_err)) + .await?; + + let self_entry = base.first().expect("Self no longer exists"); + let empty = vec![]; + let emails = self_entry.attrs.get(ATTR_MAIL).unwrap_or(&empty).clone(); + let primary_email = emails.first().cloned(); + let time = time::OffsetDateTime::now_utc() + time::Duration::new(60, 0); let can_rw = uat.purpose_readwrite_active(time); @@ -52,11 +103,180 @@ pub(crate) async fn view_profile_get( profile_partial: ProfilePartialView { menu_active_item: ProfileMenuItems::UserProfile, can_rw, + attrs: ProfileAttributes { + account_name: uat.name().to_string(), + display_name: uat.displayname.clone(), + legal_name: "hardcoded".to_string(), + emails, + primary_email, + + }, + }) +} + + +pub(crate) async fn view_profile_diff_start_save_post( + State(state): State<ServerState>, + Extension(kopid): Extension<KOpId>, + VerifiedClientInformation(client_auth_info): VerifiedClientInformation, + Form(new_attrs): Form<ProfileAttributes>, +) -> axum::response::Result<Response> { + let uat: UserAuthToken = state + .qe_r_ref + .handle_whoami_uat(client_auth_info.clone(), kopid.eventid) + .map_err(|op_err| HtmxError::new(&kopid, op_err)) + .await?; + + let time = time::OffsetDateTime::now_utc() + time::Duration::new(60, 0); + let can_rw = uat.purpose_readwrite_active(time); + + let filter = filter_all!(f_and!([f_eq( + Attribute::Uuid, + PartialValue::Uuid(uat.uuid) + )])); + let base: Vec<Entry> = state + .qe_r_ref + .handle_internalsearch(client_auth_info.clone(), filter, None, kopid.eventid) + .map_err(|op_err| HtmxError::new(&kopid, op_err)) + .await?; + + let self_entry = base.first().expect("Self no longer exists"); + let empty = vec![]; + let emails = self_entry.attrs.get(ATTR_MAIL).unwrap_or(&empty).clone(); + let primary_email = emails.first().cloned(); + + let profile_view = ProfileChangesPartialView { + can_rw, + attrs: ProfileAttributes { account_name: uat.name().to_string(), display_name: uat.displayname.clone(), - email: uat.mail_primary.clone(), + legal_name: "hardcoded".to_string(), + emails, + primary_email, }, - }) + new_attrs, + posix_enabled: true, + }; + + Ok(( + HxPushUrl(Uri::from_static("/ui/profile/diff")), + HtmlTemplate(profile_view), + ) + .into_response()) +} + +pub(crate) async fn view_profile_diff_confirm_save_post( + State(state): State<ServerState>, + Extension(kopid): Extension<KOpId>, + HxRequest(hx_request): HxRequest, + VerifiedClientInformation(client_auth_info): VerifiedClientInformation, + Form(new_attrs): Form<ProfileAttributes>, +) -> axum::response::Result<Response> { + let uat: UserAuthToken = state + .qe_r_ref + .handle_whoami_uat(client_auth_info.clone(), kopid.eventid) + .map_err(|op_err| HtmxError::new(&kopid, op_err)) + .await?; + dbg!(&new_attrs); + + let filter = filter_all!(f_and!([f_id(uat.uuid.to_string().as_str())])); + + state + .qe_w_ref + .handle_setattribute( + client_auth_info.clone(), + uat.uuid.to_string(), + ATTR_LEGALNAME.to_string(), + vec![new_attrs.legal_name], + filter.clone(), + kopid.eventid, + ) + .map_err(|op_err| HtmxError::new(&kopid, op_err)) + .await?; + + state + .qe_w_ref + .handle_setattribute( + client_auth_info.clone(), + uat.uuid.to_string(), + ATTR_DISPLAYNAME.to_string(), + vec![new_attrs.display_name], + filter.clone(), + kopid.eventid, + ) + .map_err(|op_err| HtmxError::new(&kopid, op_err)) + .await?; + + state + .qe_w_ref + .handle_setattribute( + client_auth_info.clone(), + uat.uuid.to_string(), + ATTR_MAIL.to_string(), + new_attrs.emails, + filter.clone(), + kopid.eventid, + ) + .map_err(|op_err| HtmxError::new(&kopid, op_err)) + .await?; + + // TODO: These are normally not permitted, user should be prevented from changing non modifiable fields in the UI though + // state + // .qe_w_ref + // .handle_setattribute( + // client_auth_info.clone(), + // uat.uuid.to_string(), + // ATTR_EMAIL.to_string(), + // vec![new_attrs.email.unwrap_or("".to_string())], + // filter.clone(), + // kopid.eventid, + // ) + // .map_err(|op_err| HtmxError::new(&kopid, op_err)) + // .await?; + // + // state + // .qe_w_ref + // .handle_setattribute( + // client_auth_info.clone(), + // uat.uuid.to_string(), + // ATTR_NAME.to_string(), + // vec![new_attrs.account_name], + // filter.clone(), + // kopid.eventid, + // ) + // .map_err(|op_err| HtmxError::new(&kopid, op_err)) + // .await?; + + // TODO: Calling this here returns the old attributes + view_profile_get( + State(state), + Extension(kopid), + HxRequest(hx_request), + VerifiedClientInformation(client_auth_info), + ) + .await +} + +// Sends the user a new email input to fill in :) +pub(crate) async fn view_new_email_entry_partial( + State(_state): State<ServerState>, + VerifiedClientInformation(_client_auth_info): VerifiedClientInformation, + Extension(_kopid): Extension<KOpId>, +) -> axum::response::Result<Response> { + let passkey_init_trigger = + HxResponseTrigger::after_swap([HxEvent::new("addEmailSwapped".to_string())]); + Ok(( + passkey_init_trigger, + HtmlTemplate(FormModEntryModListPartial { + can_rw: true, + r#type: "email".to_string(), + name: "emails[]".to_string(), + value: "".to_string(), + invalid_feedback: "Please enter a valid email address.".to_string(), + }) + .into_response(), + ) + .into_response()) } pub(crate) async fn view_profile_unlock_get( diff --git a/server/core/static/external/forms.js b/server/core/static/external/forms.js new file mode 100644 index 000000000..c60b009d2 --- /dev/null +++ b/server/core/static/external/forms.js @@ -0,0 +1,25 @@ +// This file will contain js helpers to have some interactivity on forms that we can't achieve with pure html. +function rehook_string_list_removers() { + const buttons = document.getElementsByClassName("kanidm-remove-list-entry"); + for (let i = 0; i < buttons.length; i++) { + const button = buttons.item(i) + if (button.getAttribute("kanidm_hooked") !== null) return + + button.addEventListener("click", (e) => { + // Expected html nesting: li > div.input-group > button.kanidm-remove-list-entry + let li = button.parentElement?.parentElement; + if (li && li.tagName === "LI") { + li.remove(); + } + }) + button.setAttribute("kanidm_hooked", "") + } +} + +window.onload = function () { + rehook_string_list_removers(); + document.body.addEventListener("addEmailSwapped", () => { + rehook_string_list_removers(); + }) +}; + diff --git a/server/core/static/external/htmx_bs_validation.js b/server/core/static/external/htmx_bs_validation.js new file mode 100644 index 000000000..e5bbb2142 --- /dev/null +++ b/server/core/static/external/htmx_bs_validation.js @@ -0,0 +1,34 @@ +htmx.defineExtension("bs-validation", { + onEvent: function (name, evt) { + let form = evt.detail.elt; + // Htmx propagates attributes onto children like button, which would break those buttons, so we return if not a form. + if (form.tagName !== "FORM") return; + + // check if trigger attribute and submit event exists + // for the form + if (!form.hasAttribute("hx-trigger")) { + // set trigger for custom event bs-send + form.setAttribute("hx-trigger", "bs-send"); + + // and attach the event only once + form.addEventListener("submit", function (event) { + if (form.checkValidity()) { + // trigger custom event hx-trigger="bs-send" + htmx.trigger(form, "bsSend"); + } + + // focus the first :invalid field + let invalidField = form.querySelector(":invalid"); + if (invalidField) { + invalidField.focus(); + } + + console.log("prevented htmx send, form was invalid") + event.preventDefault() + event.stopPropagation() + + form.classList.add("was-validated") + }, false) + } + } +}); \ No newline at end of file diff --git a/server/core/static/style.css b/server/core/static/style.css index a2dc18278..c90fdaac0 100644 --- a/server/core/static/style.css +++ b/server/core/static/style.css @@ -29,6 +29,7 @@ body { display: block !important; } + /* * Sidebar */ diff --git a/server/core/templates/user_settings.html b/server/core/templates/user_settings.html index 636af5b63..811652f23 100644 --- a/server/core/templates/user_settings.html +++ b/server/core/templates/user_settings.html @@ -3,6 +3,8 @@ (% block title %)Profile(% endblock %) (% block head %) +<script src="/pkg/external/forms.js"></script> +<script src="/pkg/external/htmx_bs_validation.js"></script> (% endblock %) (% block main %) diff --git a/server/core/templates/user_settings/form_modifiable_entry_modifiable_list_partial.html b/server/core/templates/user_settings/form_modifiable_entry_modifiable_list_partial.html new file mode 100644 index 000000000..df035e3ec --- /dev/null +++ b/server/core/templates/user_settings/form_modifiable_entry_modifiable_list_partial.html @@ -0,0 +1,7 @@ +<li class="mb-2"> + <div class="input-group"> + <input type="(( type ))" class="form-control" name="(( name ))" value="(( value ))" hx-validate="true" required> + (% if can_rw %)<button type="button" class="btn btn-secondary kanidm-remove-list-entry">Remove</button>(% endif %) + </div> + <div class="invalid-feedback">(( invalid_feedback ))</div> +</li> \ No newline at end of file diff --git a/server/core/templates/user_settings/profile_changes_partial.html b/server/core/templates/user_settings/profile_changes_partial.html new file mode 100644 index 000000000..bc3451c32 --- /dev/null +++ b/server/core/templates/user_settings/profile_changes_partial.html @@ -0,0 +1,89 @@ +(% extends "user_settings_partial_base.html" %) + +(% block selected_setting_group %) +Profile Difference +(% endblock %) + +(% block settings_vertical_point %)lg(% endblock %) + +(% block settings_window %) + +<form> + <input type="hidden" name="account_name" value="(( new_attrs.account_name ))"/> + <input type="hidden" name="display_name" value="(( new_attrs.display_name ))"/> + <input type="hidden" name="legal_name" value="(( new_attrs.legal_name ))"/> + (% for email in new_attrs.emails %) + <input type="hidden" name="emails[]" value="(( email ))"/> + (% endfor %) + + <table class="table table-bordered table-responsive"> + <thead> + <tr> + <th scope="col">Attribute</th> + <th scope="col">Old value</th> + <th scope="col">New value</th> + </tr> + </thead> + (% if attrs.account_name != new_attrs.account_name %) + <tr> + <th scope="row">User name</th> + <td class="text-break">(( attrs.account_name ))</td> + <td class="text-break">(( new_attrs.account_name ))</td> + </tr> + (% endif %) + + (% if attrs.display_name != new_attrs.display_name %) + <tr> + <th scope="row">Display name</th> + <td class="text-break">(( attrs.display_name ))</td> + <td class="text-break">(( new_attrs.display_name ))</td> + </tr> + (% endif %) + + (% if attrs.legal_name != new_attrs.legal_name %) + <tr> + <th scope="row">Legal name</th> + <td class="text-break">(( attrs.legal_name ))</td> + <td class="text-break">(( new_attrs.legal_name ))</td> + </tr> + (% endif %) + + (% if attrs.emails != new_attrs.emails %) + + <!-- TODO: List new items with +, same items with . --> + <tr> + <th scope="row">Emails</th> + <td class="text-break"> + <ul> + (% for email in attrs.emails %) + <li>(( email ))</li> + (% endfor %) + </ul> + </td> + <td class="text-break"> + <ul> + (% for email in new_attrs.emails %) + <li>(( email ))</li> + (% endfor %) + </ul> + </td> + </tr> + (% endif %) + </table> + <!-- Edit button --> + <div class="pt-4" hx-target="#user_settings_container" hx-swap="outerHTML"> + (% if can_rw %) + <button class="btn btn-danger" type="button" hx-get="/ui/profile" hx-target="#user_settings_container" hx-swap="outerHTML">Discard Changes</button> + <button class="btn btn-primary" type="button" hx-post="/ui/api/user_settings/confirm_profile" hx-target="#user_settings_container" hx-swap="outerHTML">Confirm Changes</button> + (% else %) + <a href="/ui/profile/unlock" hx-boost="false"> + <!-- TODO: at the moment, session expiring here means progress is lost. Do we just show an error screen ? We can't pass the update state through the reauth session, and we don't have profile update sessions like cred update. --> + <button class="btn btn-primary" type="button">Unlock Confirm 🔓</button> + </a> + (% endif %) + </div> + +</form> + +(% endblock %) + diff --git a/server/core/templates/user_settings_profile_partial.html b/server/core/templates/user_settings_profile_partial.html index 7d29d5bda..d4ec7487d 100644 --- a/server/core/templates/user_settings_profile_partial.html +++ b/server/core/templates/user_settings_profile_partial.html @@ -6,38 +6,56 @@ Profile (% block settings_window %) -<form> +<form class="needs-validation" hx-post="/ui/api/user_settings/edit_profile" hx-target="#user_settings_container" hx-swap="outerHTML" hx-validate="true" hx-ext="bs-validation" novalidate> <div class="mb-2 row"> - <label for="profileUserName" class="col-12 col-md-3 col-xl-2 col-form-label">User name</label> + <label for="profileUserName" class="col-12 col-md-3 col-lg-2 col-form-label">User name</label> <div class="col-12 col-md-6 col-lg-5"> <input type="text" readonly class="form-control-plaintext" id="profileUserName" value="(( account_name ))"> </div> </div> - - <div class="mb-2 row"> - <label for="profileDisplayName" class="col-12 col-md-3 col-xl-2 col-form-label">Display name</label> - <div class="col-12 col-md-6 col-lg-5"> - <input type="text" class="form-control-plaintext" id="profileDisplayName" value="(( display_name ))" disabled> - </div> - </div> <div class="mb-2 row"> - <label for="profileEmail" class="col-12 col-md-3 col-xl-2 col-form-label">Email</label> + <label for="profileDisplayName" class="col-12 col-md-3 col-lg-2 col-form-label">Display name</label> <div class="col-12 col-md-6 col-lg-5"> - <input type="email" disabled class="form-control-plaintext" id="profileEmail" value="(( email.clone().unwrap_or("None configured".to_string())))"> + <input type="text" class="form-control-plaintext" id="profileDisplayName" value="(( display_name ))"> + </div> + </div> + + <div class="mb-2 row"> + <label for="profileLegalName" class="col-12 col-md-3 col-lg-2 col-form-label">Legal name</label> + <div class="col-12 col-md-6 col-lg-5"> + <input type="text" class="form-control-plaintext" id="profileLegalName" value="(( legal_name ))"> + </div> + </div> + + <div class="mb-2"> + <label for="profileEmail" class="mb-2">Emails</label> + <div> + <div class="row"> + <ul class="col-12 col-md-11 col-lg-8" id="emailList"> + (% for email in attrs.emails %) + (% let type = "email" %) + (% let name = "emails[]" %) + (% let value = email %) + (% let invalid_feedback = "Please enter a valid email address." %) + (% include "user_settings/form_modifiable_entry_modifiable_list_partial.html" %) + (% endfor %) + </ul> + </div> + (% if can_rw %)<button type="button" class="btn btn-primary" hx-post="/ui/api/user_settings/add_email" hx-target="#emailList" hx-swap="beforeend">Add Email</button>(% endif %) </div> </div> <!-- Edit button --> - <!-- <div class="pt-4"> + <div class="pt-4"> (% if can_rw %) - <button class="btn btn-primary" type="button" hx-post="/ui/api/user_settings/edit_profile" disabled>Edit (Currently Not Working!)</button> + <button class="btn btn-primary" type="submit">Edit</button> (% else %) - <a href=(Urls::ProfileUnlock) hx-boost="false"> - <button class="btn btn-primary" type="button">((UiMessage::UnlockEdit))</button> + <a href="/ui/profile/unlock" hx-boost="false"> + <button class="btn btn-primary" type="button">Unlock Edit 🔒</button> </a> (% endif %) - </div> --> + </div> </form> (% endblock %)