1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
use gloo::console;
use kanidm_proto::v1::{CURequest, CUSessionToken, CUStatus, OperationError, PasswordFeedback};
use wasm_bindgen::{JsCast, JsValue, UnwrapThrowExt};
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response};
use yew::prelude::*;
use super::reset::{EventBusMsg, ModalProps};
use crate::error::*;
use crate::utils;
enum PwState {
Init,
Feedback(Vec<PasswordFeedback>),
Waiting,
}
enum PwCheck {
Init,
Valid,
Invalid,
}
pub struct PwModalApp {
state: PwState,
pw_check: PwCheck,
pw_val: String,
pw_check_val: String,
}
#[allow(clippy::large_enum_variant)]
pub enum Msg {
PasswordCheck,
PasswordSubmit,
PasswordCancel,
PasswordResponseQuality { feedback: Vec<PasswordFeedback> },
PasswordResponseSuccess { status: CUStatus },
Error { emsg: String, kopid: Option<String> },
}
impl From<FetchError> for Msg {
fn from(fe: FetchError) -> Self {
Msg::Error {
emsg: fe.as_string(),
kopid: None,
}
}
}
impl PwModalApp {
fn reset_and_hide(&mut self) {
utils::modal_hide_by_id("staticPassword");
self.pw_val = "".to_string();
self.pw_check_val = "".to_string();
self.pw_check = PwCheck::Init;
self.state = PwState::Init;
}
async fn submit_password_update(token: CUSessionToken, pw: String) -> Result<Msg, FetchError> {
let intentreq_jsvalue = serde_json::to_string(&(CURequest::Password(pw), token))
.map(|s| JsValue::from(&s))
.expect_throw("Failed to serialise pw curequest");
let mut opts = RequestInit::new();
opts.method("POST");
opts.mode(RequestMode::SameOrigin);
opts.body(Some(&intentreq_jsvalue));
let request = Request::new_with_str_and_init("/v1/credential/_update", &opts)?;
request
.headers()
.set("content-type", "application/json")
.expect_throw("failed to set header");
let window = utils::window();
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
let resp: Response = resp_value.dyn_into().expect_throw("Invalid response type");
let status = resp.status();
let headers = resp.headers();
if status == 200 {
let jsval = JsFuture::from(resp.json()?).await?;
let status: CUStatus =
serde_wasm_bindgen::from_value(jsval).expect_throw("Invalid response type");
Ok(Msg::PasswordResponseSuccess { status })
} else if status == 400 {
let kopid = headers.get("x-kanidm-opid").ok().flatten();
let jsval = JsFuture::from(resp.json()?).await?;
let status: OperationError =
serde_wasm_bindgen::from_value(jsval).expect_throw("Invalid response type");
match status {
OperationError::PasswordQuality(feedback) => {
Ok(Msg::PasswordResponseQuality { feedback })
}
e => Ok(Msg::Error {
emsg: format!("Invalid PWResp State Transition due to {:?}", e),
kopid,
}),
}
} else {
let kopid = headers.get("x-kanidm-opid").ok().flatten();
let text = JsFuture::from(resp.text()?).await?;
let emsg = text.as_string().unwrap_or_default();
Ok(Msg::Error { emsg, kopid })
}
}
}
impl Component for PwModalApp {
type Message = Msg;
type Properties = ModalProps;
fn create(_ctx: &Context<Self>) -> Self {
#[cfg(debug_assertions)]
console::debug!("pw modal create");
PwModalApp {
state: PwState::Init,
pw_check: PwCheck::Init,
pw_val: "".to_string(),
pw_check_val: "".to_string(),
}
}
fn changed(&mut self, _ctx: &Context<Self>, _props: &Self::Properties) -> bool {
#[cfg(debug_assertions)]
console::debug!("pw modal::change");
false
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
#[cfg(debug_assertions)]
console::debug!("pw modal::update");
let cb = ctx.props().cb.clone();
match msg {
Msg::PasswordCheck => {
let pw = utils::get_value_from_element_id("new-password").unwrap_or_default();
let check =
utils::get_value_from_element_id("new-password-check").unwrap_or_default();
if pw == check {
self.pw_check = PwCheck::Valid
} else {
self.pw_check = PwCheck::Invalid
}
self.pw_val = pw;
self.pw_check_val = check;
}
Msg::PasswordCancel => {
self.reset_and_hide();
}
Msg::PasswordSubmit => {
self.state = PwState::Waiting;
let pw = utils::get_value_from_element_id("new-password").unwrap_or_default();
let token_c = ctx.props().token.clone();
ctx.link().send_future(async {
match Self::submit_password_update(token_c, pw).await {
Ok(v) => v,
Err(v) => v.into(),
}
});
}
Msg::PasswordResponseQuality { feedback } => self.state = PwState::Feedback(feedback),
Msg::PasswordResponseSuccess { status } => {
cb.emit(EventBusMsg::UpdateStatus { status });
self.reset_and_hide();
}
Msg::Error { emsg, kopid } => {
cb.emit(EventBusMsg::Error { emsg, kopid });
self.reset_and_hide();
}
};
true
}
fn rendered(&mut self, _ctx: &Context<Self>, _first_render: bool) {
#[cfg(debug_assertions)]
console::debug!("pw modal::rendered");
}
fn destroy(&mut self, _ctx: &Context<Self>) {
#[cfg(debug_assertions)]
console::debug!("pw modal::destroy");
}
fn view(&self, ctx: &Context<Self>) -> Html {
#[cfg(debug_assertions)]
console::debug!("pw modal::view");
let (pw_class, pw_feedback) = match &self.state {
PwState::Feedback(feedback) => {
let fb = html! {
<div id="password-validation-feedback" class="invalid-feedback">
<ul>
{
feedback.iter()
.map(|item| {
html! { <li>{ format!("{:?}", item) }</li> }
})
.collect::<Html>()
}
</ul>
</div>
};
(classes!("form-control", "is-invalid"), fb)
}
_ => {
let fb = html! {
<div id="password-validation-feedback" class="invalid-feedback">
</div>
};
(classes!("form-control"), fb)
}
};
let pw_check_class = match &self.pw_check {
PwCheck::Init => classes!("form-control"),
PwCheck::Valid => classes!("form-control", "is-valid"),
PwCheck::Invalid => classes!("form-control", "is-invalid"),
};
let submit_enabled = matches!(
(&self.state, &self.pw_check),
(PwState::Feedback(_), PwCheck::Valid) | (PwState::Init, PwCheck::Valid),
);
let pw_val = self.pw_val.clone();
let pw_check_val = self.pw_check_val.clone();
html! {
<div class="modal fade" id="staticPassword" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticPasswordLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticPasswordLabel">{ "Add a New Password" }</h5>
<button type="button" class="btn-close" aria-label="Close"
onclick={
ctx.link()
.callback(move |_| {
Msg::PasswordCancel
})
}
></button>
</div>
<div class="modal-body">
<form class="row g-3 needs-validation" novalidate=true
onsubmit={ ctx.link().callback(move |e: SubmitEvent| {
console::debug!("pw modal::on form submit prevent default");
e.prevent_default();
if submit_enabled {
Msg::PasswordSubmit
} else {
Msg::PasswordCancel
}
} ) }
>
<input hidden=true type="text" autocomplete="username" />
<label for="new-password" class="form-label">{ "Enter New Password" }</label>
<input
aria-describedby="password-validation-feedback"
autocomplete="new-password"
class={ pw_class }
id="new-password"
oninput={
ctx.link()
.callback(move |_| {
Msg::PasswordCheck
})
}
placeholder=""
required=true
type="password"
value={ pw_val }
/>
{ pw_feedback }
<label for="new-password-check" class="form-label">{ "Repeat Password" }</label>
<input
aria-describedby="new-password-check-feedback"
autocomplete="new-password"
class={ pw_check_class }
id="new-password-check"
oninput={
ctx.link()
.callback(move |_| {
Msg::PasswordCheck
})
}
placeholder=""
required=true
type="password"
value={ pw_check_val }
/>
if !submit_enabled {
<div class="invalid-feedback">
{ "Passwords do not match." }
</div>
}
</form>
</div>
<div class="modal-footer">
<button id="password-cancel" type="button" class="btn btn-secondary"
onclick={
ctx.link()
.callback(move |_| {
Msg::PasswordCancel
})
}
>{ "Cancel" }</button>
<button id="password-submit" type="button" class="btn btn-primary"
disabled={ !submit_enabled }
onclick={
ctx.link()
.callback(move |_| {
Msg::PasswordSubmit
})
}
>{ "Submit" }</button>
</div>
</div>
</div>
</div>
}
}
}