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
use kanidm_proto::v1::{SingleStringRequest, UserAuthToken};
use uuid::Uuid;
use wasm_bindgen::{JsCast, JsValue, UnwrapThrowExt};
use wasm_bindgen_futures::JsFuture;
use web_sys::{FormData, HtmlFormElement, Request, RequestInit, RequestMode, Response};
use yew::prelude::*;
use crate::error::*;
use crate::utils;
#[derive(PartialEq)]
enum PwCheck {
Init,
Valid,
Invalid,
}
pub struct ChangeUnixPassword {
state: State,
pw_check: PwCheck,
pw_val: String,
pw_check_val: String,
}
#[derive(Debug, Default)]
struct FormValues {
password_input: String,
}
impl From<FormData> for FormValues {
fn from(data: FormData) -> Self {
#[allow(clippy::expect_used)]
Self {
password_input: data
.get("password_input")
.as_string()
.expect_throw("Failed to pull the password input field"),
}
}
}
pub enum Msg {
Submit(FormData),
Error { emsg: String, kopid: Option<String> },
Success,
PasswordCheck,
}
impl From<FetchError> for Msg {
fn from(fe: FetchError) -> Self {
Msg::Error {
emsg: fe.as_string(),
kopid: None,
}
}
}
pub enum State {
Init,
Error { emsg: String, kopid: Option<String> },
}
#[derive(PartialEq, Eq, Properties)]
pub struct ChangeUnixPasswordProps {
pub uat: UserAuthToken,
pub enabled: bool,
}
impl Component for ChangeUnixPassword {
type Message = Msg;
type Properties = ChangeUnixPasswordProps;
fn create(_ctx: &Context<Self>) -> Self {
Self {
state: State::Init,
pw_check: PwCheck::Init,
pw_val: "".to_string(),
pw_check_val: "".to_string(),
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Submit(data) => {
let fd: FormValues = data.into();
let id = ctx.props().uat.uuid;
ctx.link().send_future(async move {
match Self::update_unix_password(id, fd.password_input).await {
Ok(v) => v,
Err(v) => v.into(),
}
});
false
}
Msg::Error { emsg, kopid } => {
self.reset();
self.state = State::Error { emsg, kopid };
self.pw_check = PwCheck::Init;
true
}
Msg::Success => {
self.reset();
utils::modal_hide_by_id(crate::constants::ID_UNIX_PASSWORDCHANGE);
self.state = State::Init;
true
}
Msg::PasswordCheck => {
let pw = utils::get_value_from_element_id("password_input").unwrap_or_default();
let check =
utils::get_value_from_element_id("password_repeat_input").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;
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let flash = match &self.state {
State::Error { emsg, kopid } => {
let message = match kopid {
Some(k) => format!("An error occurred - {} - {}", emsg, k),
None => format!("An error occurred - {} - No Operation ID", emsg),
};
html! {
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{ message }
<button type="button" class="btn btn-close" data-dismiss="alert" aria-label="Close"></button>
</div>
}
}
_ => html! { <></> },
};
let submit_enabled = self.pw_check == PwCheck::Valid;
let button_enabled = ctx.props().enabled;
let pw_val = self.pw_val.clone();
let pw_check_val = self.pw_check_val.clone();
let pw_check_class = match &self.pw_check {
PwCheck::Init | PwCheck::Valid => classes!("form-control"),
PwCheck::Invalid => classes!("form-control", "is-invalid"),
};
html! {
<>
<button type="button" class="btn btn-primary"
disabled={ !button_enabled }
data-bs-toggle="modal"
data-bs-target={format!("#{}", crate::constants::ID_UNIX_PASSWORDCHANGE)}
>
{ "Update your Unix Password" }
</button>
<div class="modal" tabindex="-1" role="dialog" id={crate::constants::ID_UNIX_PASSWORDCHANGE}>
<div class="modal-dialog" role="document">
<form
onsubmit={
ctx.link().callback(|e: SubmitEvent| {
e.prevent_default();
#[allow(clippy::expect_used)]
let form = e.target().and_then(|t| t.dyn_into::<HtmlFormElement>().ok()).expect("Failed to pull the form data from the browser");
#[allow(clippy::expect_used)]
Msg::Submit(FormData::new_with_form(&form).expect("Failed to send the form data across the channel"))
})
}
>
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{"Update your unix password"}</h5>
</div>
<div class="modal-body">
<p> { "This password is used when logging into a unix-like system as well as applications utilizing LDAP" } </p>
{ flash }
<div class="form-group">
<label for="password_input"> {"New Password" }</label>
<input
autofocus=true
class="autofocus form-control"
name="password_input"
id="password_input"
type="password"
value={ pw_val }
oninput={
ctx.link()
.callback(move |_| {
Msg::PasswordCheck
})
}
/>
</div>
<div class="form-group">
<label for="password_repeat_input"> {"Repeat Password" }</label>
<input
class={ pw_check_class }
name="password_repeat_input"
id="password_repeat_input"
type="password"
value={ pw_check_val }
oninput={
ctx.link()
.callback(move |_| {
Msg::PasswordCheck
})
}
/>
<div class="invalid-feedback">
{ "Passwords do not match." }
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" disabled={ !submit_enabled }>{ "Update Password" }</button>
<button type="button" class="btn btn-secondary"
onclick={
ctx.link().callback(|_e| {
Msg::Success
})
}
>{"Cancel"}</button>
</div>
</div>
</form>
</div>
</div>
</>
}
}
fn changed(&mut self, _ctx: &Context<Self>, _props: &Self::Properties) -> bool {
false
}
fn rendered(&mut self, _ctx: &Context<Self>, _first_render: bool) {}
fn destroy(&mut self, _ctx: &Context<Self>) {}
}
impl ChangeUnixPassword {
async fn update_unix_password(id: Uuid, new_password: String) -> Result<Msg, FetchError> {
let changereq_jsvalue = serde_json::to_string(&SingleStringRequest {
value: new_password,
})
.map(|s| JsValue::from(&s))
.expect_throw("Failed to change request");
let mut opts = RequestInit::new();
opts.method("PUT");
opts.mode(RequestMode::SameOrigin);
opts.body(Some(&changereq_jsvalue));
let uri = format!("/v1/person/{}/_unix/_credential", id);
let request = Request::new_with_str_and_init(uri.as_str(), &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();
if status == 200 {
Ok(Msg::Success)
} else {
let headers = resp.headers();
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 })
}
}
fn reset(&mut self) {
self.pw_val = "".to_string();
self.pw_check_val = "".to_string();
self.pw_check = PwCheck::Init;
}
}