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 1c95a2709..848a8db5d 100644 --- a/server/core/src/https/views/mod.rs +++ b/server/core/src/https/views/mod.rs @@ -47,6 +47,7 @@ pub fn view_router() -> Router { .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)); @@ -120,6 +121,18 @@ pub fn view_router() -> Router { ) .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")); Router::new().merge(unguarded_router).merge(guarded_router) diff --git a/server/core/src/https/views/profile.rs b/server/core/src/https/views/profile.rs index 002abaaba..1b8b62fb8 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, + legal_name: String, + #[serde(rename = "emails[]")] + emails: Vec, + primary_email: Option, +} + +#[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 = 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); @@ -51,11 +102,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, + Extension(kopid): Extension, + VerifiedClientInformation(client_auth_info): VerifiedClientInformation, + Form(new_attrs): Form, +) -> axum::response::Result { + 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 = 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, + Extension(kopid): Extension, + HxRequest(hx_request): HxRequest, + VerifiedClientInformation(client_auth_info): VerifiedClientInformation, + Form(new_attrs): Form, +) -> axum::response::Result { + 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, + VerifiedClientInformation(_client_auth_info): VerifiedClientInformation, + Extension(_kopid): Extension, +) -> axum::response::Result { + 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 345edecb4..c90fdaac0 100644 --- a/server/core/static/style.css +++ b/server/core/static/style.css @@ -20,6 +20,16 @@ body { max-width: 680px; } +/* +* Bootstrap 5.3 fix for input-group validation +* :has checks that a child can be selected with the selector +* + selects the next sibling. +*/ +.was-validated .input-group:has(.form-control:invalid) + .invalid-feedback { + 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 %) + + (% 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 @@ +
  • +
    + + (% if can_rw %)(% endif %) +
    +
    (( invalid_feedback ))
    +
  • \ 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 %) + +
    + + + + (% for email in new_attrs.emails %) + + (% endfor %) + + + + + + + + + + (% if attrs.account_name != new_attrs.account_name %) + + + + + + (% endif %) + + (% if attrs.display_name != new_attrs.display_name %) + + + + + + (% endif %) + + (% if attrs.legal_name != new_attrs.legal_name %) + + + + + + (% endif %) + + (% if attrs.emails != new_attrs.emails %) + + + + + + + + (% endif %) +
    AttributeOld valueNew value
    User name(( attrs.account_name ))(( new_attrs.account_name ))
    Display name(( attrs.display_name ))(( new_attrs.display_name ))
    Legal name(( attrs.legal_name ))(( new_attrs.legal_name ))
    Emails +
      + (% for email in attrs.emails %) +
    • (( email ))
    • + (% endfor %) +
    +
    +
      + (% for email in new_attrs.emails %) +
    • (( email ))
    • + (% endfor %) +
    +
    + +
    + (% if can_rw %) + + + (% else %) + + + + + (% endif %) +
    + +
    + +(% 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 %) -
    +
    - +
    - -
    - -
    - -
    -
    - +
    - + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    +
    +
      + (% 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 %) +
    +
    + (% if can_rw %)(% endif %)
    - +
    (% endblock %)