lldap/app/src/components/create_user.rs

361 lines
13 KiB
Rust
Raw Normal View History

2021-10-11 16:54:53 +00:00
use crate::{components::router::AppRoute, infra::api::HostService};
2021-09-19 19:02:23 +00:00
use anyhow::{bail, Context, Result};
2021-08-30 07:50:10 +00:00
use graphql_client::GraphQLQuery;
use lldap_auth::{opaque, registration};
2021-09-19 19:02:23 +00:00
use validator_derive::Validate;
2021-06-01 15:30:57 +00:00
use yew::prelude::*;
use yew::services::{fetch::FetchTask, ConsoleService};
2021-09-19 19:02:23 +00:00
use yew_form_derive::Model;
2021-06-01 15:30:57 +00:00
use yew_router::{
agent::{RouteAgentDispatcher, RouteRequest},
route::Route,
};
2021-08-30 07:50:10 +00:00
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "../schema.graphql",
query_path = "queries/create_user.graphql",
response_derives = "Debug",
custom_scalars_module = "crate::infra::graphql"
2021-08-30 07:50:10 +00:00
)]
pub struct CreateUser;
2021-06-01 15:30:57 +00:00
pub struct CreateUserForm {
link: ComponentLink<Self>,
route_dispatcher: RouteAgentDispatcher,
2021-09-19 19:02:23 +00:00
form: yew_form::Form<CreateUserModel>,
2021-06-01 15:30:57 +00:00
error: Option<anyhow::Error>,
// Used to keep the request alive long enough.
_task: Option<FetchTask>,
}
2021-09-19 19:02:23 +00:00
#[derive(Model, Validate, PartialEq, Clone, Default)]
pub struct CreateUserModel {
#[validate(length(min = 1, message = "Username is required"))]
username: String,
#[validate(email(message = "A valid email is required"))]
2021-09-19 19:02:23 +00:00
email: String,
#[validate(length(min = 1, message = "Display name is required"))]
display_name: String,
first_name: String,
last_name: String,
#[validate(custom(
function = "empty_or_long",
message = "Password should be longer than 8 characters (or left empty)"
))]
password: String,
#[validate(must_match(other = "password", message = "Passwords must match"))]
confirm_password: String,
}
fn empty_or_long(value: &str) -> Result<(), validator::ValidationError> {
if value.is_empty() || value.len() >= 8 {
Ok(())
} else {
Err(validator::ValidationError::new(""))
}
}
2021-06-01 15:30:57 +00:00
pub enum Msg {
2021-09-19 19:02:23 +00:00
Update,
2021-06-01 15:30:57 +00:00
SubmitForm,
2021-09-19 19:02:23 +00:00
CreateUserResponse(Result<create_user::ResponseData>),
SuccessfulCreation,
2021-09-19 19:02:23 +00:00
RegistrationStartResponse(
(
opaque::client::registration::ClientRegistration,
Result<Box<registration::ServerRegistrationStartResponse>>,
),
),
RegistrationFinishResponse(Result<()>),
}
2021-06-01 15:30:57 +00:00
impl CreateUserForm {
2021-09-19 19:02:23 +00:00
fn handle_msg(&mut self, msg: <Self as Component>::Message) -> Result<bool> {
match msg {
2021-09-19 19:02:23 +00:00
Msg::Update => Ok(true),
Msg::SubmitForm => {
2021-09-19 19:02:23 +00:00
if !self.form.validate() {
bail!("Check the form for errors");
}
let model = self.form.model();
let to_option = |s: String| if s.is_empty() { None } else { Some(s) };
2021-08-30 07:50:10 +00:00
let req = create_user::Variables {
2021-09-01 08:00:51 +00:00
user: create_user::CreateUserInput {
2021-09-19 19:02:23 +00:00
id: model.username,
email: model.email,
displayName: to_option(model.display_name),
firstName: to_option(model.first_name),
lastName: to_option(model.last_name),
2021-08-30 07:50:10 +00:00
},
};
2021-08-30 07:50:10 +00:00
self._task = Some(HostService::graphql_query::<CreateUser>(
req,
self.link.callback(Msg::CreateUserResponse),
"Error trying to create user",
)?);
2021-09-19 19:02:23 +00:00
Ok(true)
}
Msg::CreateUserResponse(r) => {
2021-08-30 07:50:10 +00:00
match r {
Err(e) => return Err(e),
Ok(r) => ConsoleService::log(&format!(
"Created user '{}' at '{}'",
&r.create_user.id, &r.create_user.creation_date
)),
};
2021-09-19 19:02:23 +00:00
let model = self.form.model();
let user_id = model.username;
let password = model.password;
if !password.is_empty() {
// User was successfully created, let's register the password.
let mut rng = rand::rngs::OsRng;
2021-09-19 19:02:23 +00:00
let opaque::client::registration::ClientRegistrationStartResult {
state,
message,
} = opaque::client::registration::start_registration(&password, &mut rng)?;
let req = registration::ClientRegistrationStartRequest {
username: user_id,
2021-09-19 19:02:23 +00:00
registration_start_request: message,
};
self._task = Some(
HostService::register_start(
req,
2021-09-19 19:02:23 +00:00
self.link
.callback_once(move |r| Msg::RegistrationStartResponse((state, r))),
)
2021-08-26 19:56:42 +00:00
.context("Error trying to create user")?,
);
} else {
self.update(Msg::SuccessfulCreation);
}
2021-09-19 19:02:23 +00:00
Ok(false)
}
2021-09-19 19:02:23 +00:00
Msg::RegistrationStartResponse((registration_start, response)) => {
let response = response?;
let mut rng = rand::rngs::OsRng;
let registration_upload = opaque::client::registration::finish_registration(
2021-09-19 19:02:23 +00:00
registration_start,
response.registration_response,
&mut rng,
)?;
let req = registration::ClientRegistrationFinishRequest {
server_data: response.server_data,
registration_upload: registration_upload.message,
};
self._task = Some(
HostService::register_finish(
req,
self.link.callback(Msg::RegistrationFinishResponse),
)
2021-08-26 19:56:42 +00:00
.context("Error trying to register user")?,
);
2021-09-19 19:02:23 +00:00
Ok(false)
}
Msg::RegistrationFinishResponse(response) => {
2021-09-19 19:02:23 +00:00
response?;
self.handle_msg(Msg::SuccessfulCreation)
}
Msg::SuccessfulCreation => {
self.route_dispatcher
2021-10-11 16:54:53 +00:00
.send(RouteRequest::ChangeRoute(Route::from(AppRoute::ListUsers)));
2021-09-19 19:02:23 +00:00
Ok(true)
2021-06-01 15:30:57 +00:00
}
}
2021-06-01 15:30:57 +00:00
}
}
impl Component for CreateUserForm {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
route_dispatcher: RouteAgentDispatcher::new(),
2021-09-19 19:02:23 +00:00
form: yew_form::Form::<CreateUserModel>::new(CreateUserModel::default()),
2021-06-01 15:30:57 +00:00
error: None,
_task: None,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
self.error = None;
2021-09-19 19:02:23 +00:00
match self.handle_msg(msg) {
Err(e) => {
ConsoleService::error(&e.to_string());
self.error = Some(e);
true
}
Ok(b) => b,
2021-06-01 15:30:57 +00:00
}
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
2021-09-19 19:02:23 +00:00
type Field = yew_form::Field<CreateUserModel>;
2021-06-01 15:30:57 +00:00
html! {
2021-09-19 17:44:53 +00:00
<>
<form
2021-09-19 19:02:23 +00:00
class="form">
2021-09-19 17:44:53 +00:00
<div class="form-group row">
<label for="username"
class="form-label col-sm-2 col-form-label">
{"User name*:"}
</label>
<div class="col-sm-10">
2021-09-19 19:02:23 +00:00
<Field
form=&self.form
field_name="username"
2021-09-19 17:44:53 +00:00
class="form-control"
2021-09-19 19:02:23 +00:00
class_invalid="is-invalid has-error"
class_valid="has-success"
2021-09-19 17:44:53 +00:00
autocomplete="username"
2021-09-19 19:02:23 +00:00
oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("username")}
</div>
2021-06-01 15:30:57 +00:00
</div>
2021-09-19 17:44:53 +00:00
</div>
<div class="form-group row">
<label for="email"
class="form-label col-sm-2 col-form-label">
{"Email*:"}
</label>
<div class="col-sm-10">
2021-09-19 19:02:23 +00:00
<Field
form=&self.form
input_type="email"
field_name="email"
2021-09-19 17:44:53 +00:00
class="form-control"
2021-09-19 19:02:23 +00:00
class_invalid="is-invalid has-error"
class_valid="has-success"
2021-09-19 17:44:53 +00:00
autocomplete="email"
2021-09-19 19:02:23 +00:00
oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("email")}
</div>
2021-06-01 15:30:57 +00:00
</div>
2021-09-19 17:44:53 +00:00
</div>
<div class="form-group row">
<label for="display-name"
class="form-label col-sm-2 col-form-label">
{"Display name*:"}
</label>
<div class="col-sm-10">
2021-09-19 19:02:23 +00:00
<Field
form=&self.form
2021-09-19 17:44:53 +00:00
autocomplete="name"
class="form-control"
2021-09-19 19:02:23 +00:00
class_invalid="is-invalid has-error"
class_valid="has-success"
field_name="display_name"
oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("display_name")}
2021-09-19 17:44:53 +00:00
</div>
2021-09-19 19:02:23 +00:00
</div>
2021-09-19 17:44:53 +00:00
</div>
<div class="form-group row">
<label for="first-name"
class="form-label col-sm-2 col-form-label">
{"First name:"}
</label>
<div class="col-sm-10">
2021-09-19 19:02:23 +00:00
<Field
form=&self.form
2021-09-19 17:44:53 +00:00
autocomplete="given-name"
class="form-control"
2021-09-19 19:02:23 +00:00
class_invalid="is-invalid has-error"
class_valid="has-success"
field_name="first_name"
oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("first_name")}
</div>
2021-06-01 15:30:57 +00:00
</div>
2021-09-19 17:44:53 +00:00
</div>
<div class="form-group row">
<label for="last-name"
class="form-label col-sm-2 col-form-label">
{"Last name:"}
</label>
<div class="col-sm-10">
2021-09-19 19:02:23 +00:00
<Field
form=&self.form
2021-09-19 17:44:53 +00:00
autocomplete="family-name"
class="form-control"
2021-09-19 19:02:23 +00:00
class_invalid="is-invalid has-error"
class_valid="has-success"
field_name="last_name"
oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("last_name")}
</div>
2021-06-01 15:30:57 +00:00
</div>
2021-09-19 17:44:53 +00:00
</div>
<div class="form-group row">
<label for="password"
class="form-label col-sm-2 col-form-label">
{"Password:"}
</label>
<div class="col-sm-10">
2021-09-19 19:02:23 +00:00
<Field
form=&self.form
input_type="password"
field_name="password"
2021-09-19 17:44:53 +00:00
class="form-control"
2021-09-19 19:02:23 +00:00
class_invalid="is-invalid has-error"
class_valid="has-success"
2021-09-19 17:44:53 +00:00
autocomplete="new-password"
2021-09-19 19:02:23 +00:00
oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("password")}
</div>
</div>
</div>
<div class="form-group row">
<label for="confirm_password"
class="form-label col-sm-2 col-form-label">
{"Confirm password:"}
</label>
<div class="col-sm-10">
<Field
form=&self.form
input_type="password"
field_name="confirm_password"
class="form-control"
class_invalid="is-invalid has-error"
class_valid="has-success"
autocomplete="new-password"
oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("confirm_password")}
</div>
2021-06-01 15:30:57 +00:00
</div>
2021-09-19 17:44:53 +00:00
</div>
<div class="form-group row">
<button
class="btn btn-primary col-sm-1 col-form-label"
type="submit"
2021-09-19 19:02:23 +00:00
onclick=self.link.callback(|e: MouseEvent| {e.prevent_default(); Msg::SubmitForm})>
{"Submit"}
</button>
2021-09-19 17:44:53 +00:00
</div>
2021-06-01 15:30:57 +00:00
</form>
2021-09-19 17:44:53 +00:00
{ if let Some(e) = &self.error {
html! {
<div class="alert alert-danger">
{e.to_string() }
</div>
}
} else { html! {} }
}
</>
2021-06-01 15:30:57 +00:00
}
}
}