summary refs log tree commit diff stats
path: root/src/pages/login.rs
blob: af3f66070200a307f6978da444de5ed69c6085f8 (plain) (blame)
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
use leptos::{
    IntoView, component,
    prelude::{Get, Show, signal},
    task::spawn_local,
    view,
};
use leptos_router::{
    NavigateOptions,
    hooks::{use_navigate, use_query_map},
};
use rocie_client::models::LoginInfo;
use rocie_macros::Form;

use crate::{
    api::{get_config, login_external_wrapped},
    components::{banner::Banner, catch_errors::CatchErrors, site_header::SiteHeader},
};

#[component]
pub fn Login() -> impl IntoView {
    let back = || {
        let back = use_query_map()
            .get()
            .get("back")
            .expect("Should always have a back, because the router would otherwise not match");

        if back.starts_with('/') {
            back
        } else {
            // Prevent a redirect like `/login?back=https://gnu.org` to work
            "/".to_owned()
        }
    };

    let (error_message, error_message_set) = signal(None);

    view! {
        <CatchErrors>
            <SiteHeader logo=icondata_io::IoArrowBack back_location="/" name="Login" />

            <Show when=move || error_message.get().is_some()>
                <Banner text=move || error_message.get().expect("Is some") />
            </Show>

            {
                Form! {
                    on_submit = |user_name, password| {
                        let config = get_config!();
                        let navigate = use_navigate();
                        let back = back();

                        spawn_local(async move {
                            match login_external_wrapped(
                                &config,
                                LoginInfo { user_name, password }
                            ).await {
                                Ok(()) => {
                                    navigate(back.as_str(), NavigateOptions::default());
                                }
                                Err(err) => error_message_set.set(Some(format!("Failed to login: {err}"))),
                            }
                        });
                    };

                    <Input
                        name=user_name,
                        rust_type=String,
                        html_type="text",
                        label="Username"
                    />
                    <Input
                        name=password,
                        rust_type=String,
                        html_type="password",
                        label="Password"
                    />
                }
            }
        </CatchErrors>
    }
}