Add a form to create users

This commit is contained in:
Valentin Tolmer 2021-06-01 17:30:57 +02:00
parent 2a6d23203c
commit 7465a6b93f
4 changed files with 163 additions and 4 deletions

View File

@ -97,4 +97,22 @@ impl HostService {
});
FetchService::fetch_with_options(request, get_default_options(), handler)
}
pub fn create_user(
request: CreateUserRequest,
callback: Callback<Result<()>>,
) -> Result<FetchTask> {
let url = "/api/users/create";
let request = Request::post(url)
.header("Content-Type", "application/json")
.body(Json(&request))?;
let handler = create_handler(callback, |status, data: String| {
if status.is_success() {
Ok(())
} else {
Err(anyhow!("Could not create a user: [{}]: {}", status, data))
}
});
FetchService::fetch_with_options(request, get_default_options(), handler)
}
}

View File

@ -1,11 +1,12 @@
use crate::cookies::get_cookie;
use crate::login::LoginForm;
use crate::logout::LogoutButton;
use crate::user_table::UserTable;
use crate::{
cookies::get_cookie, create_user::CreateUserForm, login::LoginForm, logout::LogoutButton,
user_table::UserTable,
};
use yew::prelude::*;
use yew::services::ConsoleService;
use yew_router::{
agent::{RouteAgentDispatcher, RouteRequest},
components::RouterAnchor,
route::Route,
router::Router,
service::RouteService,
@ -30,10 +31,14 @@ pub enum AppRoute {
Login,
#[to = "/users"]
ListUsers,
#[to = "/create_user"]
CreateUser,
#[to = "/"]
Index,
}
type Link = RouterAnchor<AppRoute>;
impl Component for App {
type Message = Msg;
type Properties = ();
@ -91,10 +96,17 @@ impl Component for App {
AppRoute::Login => html! {
<LoginForm on_logged_in=link.callback(Msg::Login)/>
},
AppRoute::CreateUser => html! {
<div>
<LogoutButton on_logged_out=link.callback(|_| Msg::Logout) />
<CreateUserForm/>
</div>
},
AppRoute::Index | AppRoute::ListUsers => html! {
<div>
<LogoutButton on_logged_out=link.callback(|_| Msg::Logout) />
<UserTable />
<Link route=AppRoute::CreateUser>{"Create a user"}</Link>
</div>
}
}

128
app/src/create_user.rs Normal file
View File

@ -0,0 +1,128 @@
use crate::api::HostService;
use anyhow::Result;
use lldap_model::*;
use yew::prelude::*;
use yew::services::{fetch::FetchTask, ConsoleService};
use yew_router::{
agent::{RouteAgentDispatcher, RouteRequest},
route::Route,
};
pub struct CreateUserForm {
link: ComponentLink<Self>,
route_dispatcher: RouteAgentDispatcher,
node_ref: NodeRef,
error: Option<anyhow::Error>,
// Used to keep the request alive long enough.
_task: Option<FetchTask>,
}
pub enum Msg {
CreateUserResponse(Result<()>),
SubmitForm,
}
impl CreateUserForm {
fn create_user(&mut self, req: CreateUserRequest) {
match HostService::create_user(req, self.link.callback(Msg::CreateUserResponse)) {
Ok(task) => self._task = Some(task),
Err(e) => {
self._task = None;
ConsoleService::log(format!("Error trying to create user: {}", e).as_str())
}
};
}
}
impl Component for CreateUserForm {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Self {
link,
route_dispatcher: RouteAgentDispatcher::new(),
node_ref: NodeRef::default(),
error: None,
_task: None,
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::SubmitForm => {
use wasm_bindgen::JsCast;
let document = web_sys::window().unwrap().document().unwrap();
let get_element = |name: &str| {
document
.get_element_by_id(name)
.unwrap()
.dyn_into::<web_sys::HtmlInputElement>()
.unwrap()
.value()
};
let req = CreateUserRequest {
user_id: get_element("username"),
email: get_element("email"),
display_name: Some(get_element("displayname")),
first_name: Some(get_element("firstname")),
last_name: Some(get_element("lastname")),
password: get_element("password"),
};
self.create_user(req);
}
Msg::CreateUserResponse(Ok(())) => {
self.route_dispatcher
.send(RouteRequest::ChangeRoute(Route::new_no_state(
"/list_users",
)));
}
Msg::CreateUserResponse(Err(e)) => {
ConsoleService::warn(&format!("Error listing users: {}", e));
}
}
true
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
html! {
<form ref=self.node_ref.clone() onsubmit=self.link.callback(|e: FocusEvent| { e.prevent_default(); Msg::SubmitForm })>
<div>
<label for="username">{"User name:"}</label>
<input type="text" id="username" />
</div>
<div>
<label for="email">{"Email:"}</label>
<input type="text" id="email" />
</div>
<div>
<label for="displayname">{"Display name:"}</label>
<input type="text" id="displayname" />
</div>
<div>
<label for="firstname">{"First name:"}</label>
<input type="text" id="firstname" />
</div>
<div>
<label for="lastname">{"Last name:"}</label>
<input type="text" id="lastname" />
</div>
<div>
<label for="password">{"Password:"}</label>
<input type="password" id="password" />
</div>
<button type="submit">{"Login"}</button>
<div>
{ if let Some(e) = &self.error {
html! { e.to_string() }
} else { html! {} }
}
</div>
</form>
}
}
}

View File

@ -2,6 +2,7 @@
mod api;
mod app;
mod cookies;
mod create_user;
mod login;
mod logout;
mod user_table;