app: Migrate create_user to yew_form

This commit is contained in:
Valentin Tolmer 2021-09-19 21:02:23 +02:00 committed by nitnelave
parent fa6427e694
commit dfe1607a3e
4 changed files with 161 additions and 88 deletions

2
Cargo.lock generated
View File

@ -1756,10 +1756,8 @@ dependencies = [
"graphql_client", "graphql_client",
"http", "http",
"jwt", "jwt",
"lazy_static",
"lldap_auth", "lldap_auth",
"rand 0.8.4", "rand 0.8.4",
"regex",
"serde", "serde",
"serde_json", "serde_json",
"validator", "validator",

View File

@ -9,9 +9,7 @@ anyhow = "1"
graphql_client = "0.10" graphql_client = "0.10"
http = "0.2" http = "0.2"
jwt = "0.13" jwt = "0.13"
lazy_static = "*"
rand = "0.8" rand = "0.8"
regex = "*"
serde = "1" serde = "1"
serde_json = "1" serde_json = "1"
validator = "*" validator = "*"

View File

@ -1,9 +1,11 @@
use crate::infra::api::HostService; use crate::infra::api::HostService;
use anyhow::{anyhow, Context, Result}; use anyhow::{bail, Context, Result};
use graphql_client::GraphQLQuery; use graphql_client::GraphQLQuery;
use lldap_auth::{opaque, registration}; use lldap_auth::{opaque, registration};
use validator_derive::Validate;
use yew::prelude::*; use yew::prelude::*;
use yew::services::{fetch::FetchTask, ConsoleService}; use yew::services::{fetch::FetchTask, ConsoleService};
use yew_form_derive::Model;
use yew_router::{ use yew_router::{
agent::{RouteAgentDispatcher, RouteRequest}, agent::{RouteAgentDispatcher, RouteRequest},
route::Route, route::Route,
@ -21,41 +23,70 @@ pub struct CreateUser;
pub struct CreateUserForm { pub struct CreateUserForm {
link: ComponentLink<Self>, link: ComponentLink<Self>,
route_dispatcher: RouteAgentDispatcher, route_dispatcher: RouteAgentDispatcher,
node_ref: NodeRef, form: yew_form::Form<CreateUserModel>,
error: Option<anyhow::Error>, error: Option<anyhow::Error>,
registration_start: Option<opaque::client::registration::ClientRegistration>,
// Used to keep the request alive long enough. // Used to keep the request alive long enough.
_task: Option<FetchTask>, _task: Option<FetchTask>,
} }
#[derive(Model, Validate, PartialEq, Clone, Default)]
pub struct CreateUserModel {
#[validate(length(min = 1, message = "Username is required"))]
username: String,
#[validate(email)]
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(""))
}
}
pub enum Msg { pub enum Msg {
CreateUserResponse(Result<create_user::ResponseData>), Update,
SubmitForm, SubmitForm,
CreateUserResponse(Result<create_user::ResponseData>),
SuccessfulCreation, SuccessfulCreation,
RegistrationStartResponse(Result<Box<registration::ServerRegistrationStartResponse>>), RegistrationStartResponse(
(
opaque::client::registration::ClientRegistration,
Result<Box<registration::ServerRegistrationStartResponse>>,
),
),
RegistrationFinishResponse(Result<()>), RegistrationFinishResponse(Result<()>),
} }
#[allow(clippy::ptr_arg)]
fn not_empty(s: &String) -> bool {
!s.is_empty()
}
impl CreateUserForm { impl CreateUserForm {
fn handle_msg(&mut self, msg: <Self as Component>::Message) -> Result<()> { fn handle_msg(&mut self, msg: <Self as Component>::Message) -> Result<bool> {
match msg { match msg {
Msg::Update => Ok(true),
Msg::SubmitForm => { Msg::SubmitForm => {
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) };
let req = create_user::Variables { let req = create_user::Variables {
user: create_user::CreateUserInput { user: create_user::CreateUserInput {
id: get_element("username") id: model.username,
.filter(not_empty) email: model.email,
.ok_or_else(|| anyhow!("Missing username"))?, displayName: to_option(model.display_name),
email: get_element("email") firstName: to_option(model.first_name),
.filter(not_empty) lastName: to_option(model.last_name),
.ok_or_else(|| anyhow!("Missing email"))?,
displayName: get_element("display-name").filter(not_empty),
firstName: get_element("first-name").filter(not_empty),
lastName: get_element("last-name").filter(not_empty),
}, },
}; };
self._task = Some(HostService::graphql_query::<CreateUser>( self._task = Some(HostService::graphql_query::<CreateUser>(
@ -63,6 +94,7 @@ impl CreateUserForm {
self.link.callback(Msg::CreateUserResponse), self.link.callback(Msg::CreateUserResponse),
"Error trying to create user", "Error trying to create user",
)?); )?);
Ok(true)
} }
Msg::CreateUserResponse(r) => { Msg::CreateUserResponse(r) => {
match r { match r {
@ -72,36 +104,38 @@ impl CreateUserForm {
&r.create_user.id, &r.create_user.creation_date &r.create_user.id, &r.create_user.creation_date
)), )),
}; };
let user_id = get_element("username") let model = self.form.model();
.filter(not_empty) let user_id = model.username;
.ok_or_else(|| anyhow!("Missing username"))?; let password = model.password;
if let Some(password) = get_element("password").filter(not_empty) { if !password.is_empty() {
// User was successfully created, let's register the password. // User was successfully created, let's register the password.
let mut rng = rand::rngs::OsRng; let mut rng = rand::rngs::OsRng;
let client_registration_start = let opaque::client::registration::ClientRegistrationStartResult {
opaque::client::registration::start_registration(&password, &mut rng)?; state,
self.registration_start = Some(client_registration_start.state); message,
} = opaque::client::registration::start_registration(&password, &mut rng)?;
let req = registration::ClientRegistrationStartRequest { let req = registration::ClientRegistrationStartRequest {
username: user_id, username: user_id,
registration_start_request: client_registration_start.message, registration_start_request: message,
}; };
self._task = Some( self._task = Some(
HostService::register_start( HostService::register_start(
req, req,
self.link.callback(Msg::RegistrationStartResponse), self.link
.callback_once(move |r| Msg::RegistrationStartResponse((state, r))),
) )
.context("Error trying to create user")?, .context("Error trying to create user")?,
); );
} else { } else {
self.update(Msg::SuccessfulCreation); self.update(Msg::SuccessfulCreation);
} }
Ok(false)
} }
Msg::RegistrationStartResponse(response) => { Msg::RegistrationStartResponse((registration_start, response)) => {
debug_assert!(self.registration_start.is_some());
let response = response?; let response = response?;
let mut rng = rand::rngs::OsRng; let mut rng = rand::rngs::OsRng;
let registration_upload = opaque::client::registration::finish_registration( let registration_upload = opaque::client::registration::finish_registration(
self.registration_start.take().unwrap(), registration_start,
response.registration_response, response.registration_response,
&mut rng, &mut rng,
)?; )?;
@ -116,34 +150,22 @@ impl CreateUserForm {
) )
.context("Error trying to register user")?, .context("Error trying to register user")?,
); );
Ok(false)
} }
Msg::RegistrationFinishResponse(response) => { Msg::RegistrationFinishResponse(response) => {
if response.is_err() { response?;
return response; self.handle_msg(Msg::SuccessfulCreation)
}
self.update(Msg::SuccessfulCreation);
} }
Msg::SuccessfulCreation => { Msg::SuccessfulCreation => {
self.route_dispatcher self.route_dispatcher
.send(RouteRequest::ChangeRoute(Route::new_no_state( .send(RouteRequest::ChangeRoute(Route::new_no_state(
"/list_users", "/list_users",
))); )));
Ok(true)
} }
} }
Ok(())
} }
} }
fn get_element(name: &str) -> Option<String> {
use wasm_bindgen::JsCast;
Some(
web_sys::window()?
.document()?
.get_element_by_id(name)?
.dyn_into::<web_sys::HtmlInputElement>()
.ok()?
.value(),
)
}
impl Component for CreateUserForm { impl Component for CreateUserForm {
type Message = Msg; type Message = Msg;
@ -153,20 +175,22 @@ impl Component for CreateUserForm {
Self { Self {
link, link,
route_dispatcher: RouteAgentDispatcher::new(), route_dispatcher: RouteAgentDispatcher::new(),
node_ref: NodeRef::default(), form: yew_form::Form::<CreateUserModel>::new(CreateUserModel::default()),
error: None, error: None,
registration_start: None,
_task: None, _task: None,
} }
} }
fn update(&mut self, msg: Self::Message) -> ShouldRender { fn update(&mut self, msg: Self::Message) -> ShouldRender {
self.error = None; self.error = None;
if let Err(e) = self.handle_msg(msg) { match self.handle_msg(msg) {
ConsoleService::error(&e.to_string()); Err(e) => {
self.error = Some(e); ConsoleService::error(&e.to_string());
self.error = Some(e);
true
}
Ok(b) => b,
} }
true
} }
fn change(&mut self, _: Self::Properties) -> ShouldRender { fn change(&mut self, _: Self::Properties) -> ShouldRender {
@ -174,24 +198,28 @@ impl Component for CreateUserForm {
} }
fn view(&self) -> Html { fn view(&self) -> Html {
type Field = yew_form::Field<CreateUserModel>;
html! { html! {
<> <>
<form <form
class="form" class="form">
ref=self.node_ref.clone()
onsubmit=self.link.callback(|e: FocusEvent| { e.prevent_default(); Msg::SubmitForm })>
<div class="form-group row"> <div class="form-group row">
<label for="username" <label for="username"
class="form-label col-sm-2 col-form-label"> class="form-label col-sm-2 col-form-label">
{"User name*:"} {"User name*:"}
</label> </label>
<div class="col-sm-10"> <div class="col-sm-10">
<input <Field
type="text" form=&self.form
id="username" field_name="username"
class="form-control" class="form-control"
class_invalid="is-invalid has-error"
class_valid="has-success"
autocomplete="username" autocomplete="username"
required=true /> oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("username")}
</div>
</div> </div>
</div> </div>
<div class="form-group row"> <div class="form-group row">
@ -200,12 +228,18 @@ impl Component for CreateUserForm {
{"Email*:"} {"Email*:"}
</label> </label>
<div class="col-sm-10"> <div class="col-sm-10">
<input <Field
type="email" form=&self.form
id="email" input_type="email"
field_name="email"
class="form-control" class="form-control"
class_invalid="is-invalid has-error"
class_valid="has-success"
autocomplete="email" autocomplete="email"
required=true /> oninput=self.link.callback(|_| Msg::Update) />
<div class="invalid-feedback">
{&self.form.field_message("email")}
</div>
</div> </div>
</div> </div>
<div class="form-group row"> <div class="form-group row">
@ -214,12 +248,18 @@ impl Component for CreateUserForm {
{"Display name*:"} {"Display name*:"}
</label> </label>
<div class="col-sm-10"> <div class="col-sm-10">
<input <Field
type="text" form=&self.form
autocomplete="name" autocomplete="name"
class="form-control" class="form-control"
id="display-name" /> 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")}
</div> </div>
</div>
</div> </div>
<div class="form-group row"> <div class="form-group row">
<label for="first-name" <label for="first-name"
@ -227,11 +267,17 @@ impl Component for CreateUserForm {
{"First name:"} {"First name:"}
</label> </label>
<div class="col-sm-10"> <div class="col-sm-10">
<input <Field
type="text" form=&self.form
autocomplete="given-name" autocomplete="given-name"
class="form-control" class="form-control"
id="first-name" /> 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>
</div> </div>
</div> </div>
<div class="form-group row"> <div class="form-group row">
@ -240,11 +286,17 @@ impl Component for CreateUserForm {
{"Last name:"} {"Last name:"}
</label> </label>
<div class="col-sm-10"> <div class="col-sm-10">
<input <Field
type="text" form=&self.form
autocomplete="family-name" autocomplete="family-name"
class="form-control" class="form-control"
id="last-name" /> 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>
</div> </div>
</div> </div>
<div class="form-group row"> <div class="form-group row">
@ -253,18 +305,47 @@ impl Component for CreateUserForm {
{"Password:"} {"Password:"}
</label> </label>
<div class="col-sm-10"> <div class="col-sm-10">
<input <Field
type="password" form=&self.form
id="password" input_type="password"
field_name="password"
class="form-control" class="form-control"
class_invalid="is-invalid has-error"
class_valid="has-success"
autocomplete="new-password" autocomplete="new-password"
minlength="8" /> 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>
</div> </div>
</div> </div>
<div class="form-group row"> <div class="form-group row">
<button <button
class="btn btn-primary col-sm-1 col-form-label" class="btn btn-primary col-sm-1 col-form-label"
type="submit">{"Submit"}</button> type="button"
onclick=self.link.callback(|e: MouseEvent| {e.prevent_default(); Msg::SubmitForm})>
{"Submit"}
</button>
</div> </div>
</form> </form>
{ if let Some(e) = &self.error { { if let Some(e) = &self.error {

View File

@ -8,14 +8,10 @@ use yew::{
}; };
use yew_form_derive::Model; use yew_form_derive::Model;
lazy_static::lazy_static! {
static ref EMAIL_RE: regex::Regex = regex::Regex::new("^[^@]+@[^@]+\\.[^@]+$").unwrap();
}
/// The fields of the form, with the editable details and the constraints. /// The fields of the form, with the editable details and the constraints.
#[derive(Model, Validate, PartialEq, Clone)] #[derive(Model, Validate, PartialEq, Clone)]
pub struct UserModel { pub struct UserModel {
#[validate(regex(path = "EMAIL_RE", message = "Enter a valid email"))] #[validate(email)]
email: String, email: String,
#[validate(length(min = 1, message = "Display name is required"))] #[validate(length(min = 1, message = "Display name is required"))]
display_name: String, display_name: String,