Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eba3f56ba3 | ||
|
|
71ab588c16 | ||
|
|
195375c083 | ||
|
|
34dafcc23e | ||
|
|
507f86fcf1 | ||
|
|
f40654d2c4 | ||
|
|
cd32c175a4 | ||
|
|
9393294af8 | ||
|
|
24c426229c | ||
|
|
3ed6fd4ee8 | ||
|
|
70d83c284a | ||
|
|
8a248cab58 | ||
|
|
e6851e1fe4 | ||
|
|
65ff1256aa | ||
|
|
36dc4302a0 | ||
|
|
938a1f16f1 |
187
Cargo.lock
generated
187
Cargo.lock
generated
@@ -274,6 +274,19 @@ version = "1.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b"
|
||||
|
||||
[[package]]
|
||||
name = "bcrypt"
|
||||
version = "0.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92758ad6077e4c76a6cadbce5005f666df70d4f13b19976b1a8062eef880040f"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"blowfish",
|
||||
"getrandom 0.3.1",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bigdecimal"
|
||||
version = "0.4.7"
|
||||
@@ -323,6 +336,16 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "blowfish"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.17.0"
|
||||
@@ -386,9 +409,19 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "client"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"common",
|
||||
"crossterm",
|
||||
@@ -424,7 +457,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "common"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"prost",
|
||||
"serde",
|
||||
@@ -782,7 +815,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -991,8 +1024,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"wasi 0.11.0+wasi-snapshot-preview1",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1452,6 +1487,15 @@ version = "2.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f4c7245a08504955605670dbf141fceab975f15ca21570696aebe9d2e71576bd"
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "instability"
|
||||
version = "0.3.7"
|
||||
@@ -1499,6 +1543,21 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonwebtoken"
|
||||
version = "9.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"js-sys",
|
||||
"pem",
|
||||
"ring",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"simple_asn1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lasso"
|
||||
version = "0.7.3"
|
||||
@@ -1886,6 +1945,16 @@ version = "1.0.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
||||
|
||||
[[package]]
|
||||
name = "pem"
|
||||
version = "3.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38af38e8470ac9dee3ce1bae1af9c1671fffc44ddfd8bd1d0a3445bf349a8ef3"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pem-rfc7468"
|
||||
version = "0.7.0"
|
||||
@@ -2030,6 +2099,28 @@ dependencies = [
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-error-attr2"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-error2"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"
|
||||
dependencies = [
|
||||
"proc-macro-error-attr2",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.99",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.94"
|
||||
@@ -2281,6 +2372,20 @@ dependencies = [
|
||||
"tstr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"getrandom 0.2.15",
|
||||
"libc",
|
||||
"untrusted",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rsa"
|
||||
version = "0.9.7"
|
||||
@@ -2356,7 +2461,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.4.15",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2369,7 +2474,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.9.2",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2483,12 +2588,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "server"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bcrypt",
|
||||
"chrono",
|
||||
"common",
|
||||
"dashmap",
|
||||
"dotenvy",
|
||||
"jsonwebtoken",
|
||||
"lazy_static",
|
||||
"prost",
|
||||
"regex",
|
||||
@@ -2504,6 +2611,8 @@ dependencies = [
|
||||
"tonic",
|
||||
"tonic-reflection",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"validator",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2574,6 +2683,18 @@ dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simple_asn1"
|
||||
version = "0.6.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-traits",
|
||||
"thiserror 2.0.12",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sized-chunks"
|
||||
version = "0.6.5"
|
||||
@@ -2678,6 +2799,7 @@ dependencies = [
|
||||
"tokio-stream",
|
||||
"tracing",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2760,6 +2882,7 @@ dependencies = [
|
||||
"thiserror 2.0.12",
|
||||
"time",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"whoami",
|
||||
]
|
||||
|
||||
@@ -2799,6 +2922,7 @@ dependencies = [
|
||||
"thiserror 2.0.12",
|
||||
"time",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"whoami",
|
||||
]
|
||||
|
||||
@@ -2825,6 +2949,7 @@ dependencies = [
|
||||
"time",
|
||||
"tracing",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3029,7 +3154,7 @@ dependencies = [
|
||||
"getrandom 0.3.1",
|
||||
"once_cell",
|
||||
"rustix 1.0.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3450,6 +3575,12 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd"
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "url"
|
||||
version = "2.5.4"
|
||||
@@ -3473,6 +3604,46 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9"
|
||||
dependencies = [
|
||||
"getrandom 0.3.1",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "validator"
|
||||
version = "0.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "43fb22e1a008ece370ce08a3e9e4447a910e92621bb49b85d6e48a45397e7cfa"
|
||||
dependencies = [
|
||||
"idna",
|
||||
"once_cell",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"url",
|
||||
"validator_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "validator_derive"
|
||||
version = "0.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7df16e474ef958526d1205f6dda359fdfab79d9aa6d54bafcb92dcd07673dca"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"once_cell",
|
||||
"proc-macro-error2",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.99",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
@@ -3623,7 +3794,7 @@ version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -5,7 +5,7 @@ resolver = "2"
|
||||
[workspace.package]
|
||||
# TODO: idk how to do the name, fix later
|
||||
# name = "Multieko2"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later"
|
||||
authors = ["Filip Priečinský <filippriec@gmail.com>"]
|
||||
|
||||
4
client/src/components/form.rs
Normal file
4
client/src/components/form.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
// src/components/form.rs
|
||||
pub mod form;
|
||||
|
||||
pub use form::*;
|
||||
@@ -7,7 +7,7 @@ use ratatui::{
|
||||
};
|
||||
use crate::config::colors::themes::Theme;
|
||||
use crate::ui::form::FormState;
|
||||
use super::canvas::render_canvas; // Changed to canvas
|
||||
use crate::components::handlers::canvas::render_canvas;
|
||||
|
||||
pub fn render_form(
|
||||
f: &mut Frame,
|
||||
@@ -1,8 +1,6 @@
|
||||
// src/components/handlers.rs
|
||||
pub mod form;
|
||||
pub mod canvas;
|
||||
pub mod sidebar;
|
||||
|
||||
pub use form::*;
|
||||
pub use canvas::*;
|
||||
pub use sidebar::*;
|
||||
|
||||
@@ -9,7 +9,8 @@ use crate::config::colors::themes::Theme;
|
||||
use common::proto::multieko2::table_definition::{ProfileTreeResponse};
|
||||
use ratatui::text::{Span, Line};
|
||||
|
||||
const SIDEBAR_WIDTH: u16 = 16;
|
||||
// Reduced sidebar width
|
||||
const SIDEBAR_WIDTH: u16 = 12;
|
||||
|
||||
pub fn calculate_sidebar_layout(show_sidebar: bool, main_content_area: Rect) -> (Option<Rect>, Rect) {
|
||||
if show_sidebar {
|
||||
@@ -37,46 +38,72 @@ pub fn render_sidebar(
|
||||
let mut items = Vec::new();
|
||||
|
||||
if let Some(profile_name) = selected_profile {
|
||||
if let Some(profile) = profile_tree.profiles.iter()
|
||||
.find(|p| &p.name == profile_name)
|
||||
{
|
||||
// Profile header
|
||||
// Existing code for when a profile is selected...
|
||||
} else {
|
||||
// Show full profile tree when no profile is selected (compact version)
|
||||
for (profile_idx, profile) in profile_tree.profiles.iter().enumerate() {
|
||||
// Profile header - more compact
|
||||
items.push(ListItem::new(Line::from(vec![
|
||||
Span::styled("📁 ", Style::default().fg(theme.accent)),
|
||||
Span::styled("◆", Style::default().fg(theme.accent)),
|
||||
Span::styled(&profile.name, Style::default().fg(theme.highlight)),
|
||||
])));
|
||||
|
||||
// Tables
|
||||
// Tables with compact prefixes
|
||||
for (table_idx, table) in profile.tables.iter().enumerate() {
|
||||
let is_last = table_idx == profile.tables.len() - 1;
|
||||
let prefix = if is_last { "└─ " } else { "├─ " };
|
||||
let is_last_table = table_idx == profile.tables.len() - 1;
|
||||
let is_last_profile = profile_idx == profile_tree.profiles.len() - 1;
|
||||
|
||||
// Shorter prefix characters
|
||||
let prefix = match (is_last_profile, is_last_table) {
|
||||
(true, true) => " └",
|
||||
(true, false) => " ├",
|
||||
(false, true) => "│└",
|
||||
(false, false) => "│├",
|
||||
};
|
||||
|
||||
// Get table name without year prefix to save space
|
||||
let display_name = if table.name.starts_with("2025_") {
|
||||
&table.name[5..] // Skip "2025_" prefix
|
||||
} else {
|
||||
&table.name
|
||||
};
|
||||
|
||||
let mut line = vec![
|
||||
Span::styled(format!(" {}", prefix), Style::default().fg(theme.fg)),
|
||||
Span::styled(&table.name, Style::default().fg(theme.fg)),
|
||||
Span::styled(prefix, Style::default().fg(theme.fg)),
|
||||
Span::styled(display_name, Style::default().fg(theme.fg)),
|
||||
];
|
||||
|
||||
// Show a simple indicator for dependencies instead of listing them
|
||||
if !table.depends_on.is_empty() {
|
||||
line.push(Span::styled(
|
||||
format!(" → {}", table.depends_on.join(", ")),
|
||||
"→",
|
||||
Style::default().fg(theme.secondary)
|
||||
));
|
||||
}
|
||||
|
||||
items.push(ListItem::new(Line::from(line)));
|
||||
}
|
||||
|
||||
// Compact separator between profiles
|
||||
if profile_idx < profile_tree.profiles.len() - 1 {
|
||||
items.push(ListItem::new(Line::from(
|
||||
Span::styled("│", Style::default().fg(theme.secondary))
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
if profile_tree.profiles.is_empty() {
|
||||
items.push(ListItem::new(Span::styled(
|
||||
"No profiles",
|
||||
Style::default().fg(theme.secondary)
|
||||
)));
|
||||
}
|
||||
} else {
|
||||
items.push(ListItem::new(Span::styled(
|
||||
"No profile selected",
|
||||
Style::default().fg(theme.secondary)
|
||||
)));
|
||||
}
|
||||
|
||||
let list = List::new(items)
|
||||
.block(sidebar_block)
|
||||
.highlight_style(Style::default().fg(theme.highlight))
|
||||
.highlight_symbol(">>");
|
||||
.highlight_symbol(">");
|
||||
|
||||
f.render_widget(list, area);
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@ pub mod handlers;
|
||||
pub mod intro;
|
||||
pub mod admin;
|
||||
pub mod common;
|
||||
pub mod form;
|
||||
|
||||
pub use handlers::*;
|
||||
pub use intro::*;
|
||||
pub use admin::*;
|
||||
pub use common::*;
|
||||
pub use form::*;
|
||||
|
||||
@@ -4,7 +4,7 @@ use crossterm::event::{KeyEvent};
|
||||
use crate::config::binds::config::Config;
|
||||
use crate::tui::terminal::grpc_client::GrpcClient;
|
||||
use crate::tui::terminal::core::TerminalCore;
|
||||
use crate::tui::terminal::commands::CommandHandler;
|
||||
use crate::tui::controls::commands::CommandHandler;
|
||||
use crate::ui::handlers::form::FormState;
|
||||
use crate::state::state::AppState;
|
||||
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest};
|
||||
@@ -32,12 +32,19 @@ pub async fn handle_core_action(
|
||||
Ok((false, message))
|
||||
},
|
||||
"force_quit" => {
|
||||
let (should_exit, message) = command_handler.handle_command("force_quit", terminal).await?;
|
||||
Ok((should_exit, message))
|
||||
terminal.cleanup()?;
|
||||
Ok((true, "Force exiting without saving.".to_string()))
|
||||
},
|
||||
"save_and_quit" => {
|
||||
let (should_exit, message) = command_handler.handle_command("save_and_quit", terminal).await?;
|
||||
Ok((should_exit, message))
|
||||
let message = save(
|
||||
form_state,
|
||||
grpc_client,
|
||||
&mut app_state.ui.is_saved,
|
||||
current_position,
|
||||
total_count,
|
||||
).await?;
|
||||
terminal.cleanup()?;
|
||||
Ok((true, format!("{}. Exiting application.", message)))
|
||||
},
|
||||
"revert" => {
|
||||
let message = revert(
|
||||
@@ -132,64 +139,6 @@ pub async fn save(
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
/// Shared logic for force quitting the application
|
||||
pub fn force_quit() -> (bool, String) {
|
||||
(true, "Force quitting application".to_string())
|
||||
}
|
||||
|
||||
/// Shared logic for saving and quitting
|
||||
pub async fn save_and_quit(
|
||||
form_state: &mut FormState,
|
||||
grpc_client: &mut GrpcClient,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
let is_new = *current_position == total_count + 1;
|
||||
|
||||
if is_new {
|
||||
let post_request = PostAdresarRequest {
|
||||
firma: form_state.values[0].clone(),
|
||||
kz: form_state.values[1].clone(),
|
||||
drc: form_state.values[2].clone(),
|
||||
ulica: form_state.values[3].clone(),
|
||||
psc: form_state.values[4].clone(),
|
||||
mesto: form_state.values[5].clone(),
|
||||
stat: form_state.values[6].clone(),
|
||||
banka: form_state.values[7].clone(),
|
||||
ucet: form_state.values[8].clone(),
|
||||
skladm: form_state.values[9].clone(),
|
||||
ico: form_state.values[10].clone(),
|
||||
kontakt: form_state.values[11].clone(),
|
||||
telefon: form_state.values[12].clone(),
|
||||
skladu: form_state.values[13].clone(),
|
||||
fax: form_state.values[14].clone(),
|
||||
};
|
||||
let _ = grpc_client.post_adresar(post_request).await?;
|
||||
} else {
|
||||
let put_request = PutAdresarRequest {
|
||||
id: form_state.id,
|
||||
firma: form_state.values[0].clone(),
|
||||
kz: form_state.values[1].clone(),
|
||||
drc: form_state.values[2].clone(),
|
||||
ulica: form_state.values[3].clone(),
|
||||
psc: form_state.values[4].clone(),
|
||||
mesto: form_state.values[5].clone(),
|
||||
stat: form_state.values[6].clone(),
|
||||
banka: form_state.values[7].clone(),
|
||||
ucet: form_state.values[8].clone(),
|
||||
skladm: form_state.values[9].clone(),
|
||||
ico: form_state.values[10].clone(),
|
||||
kontakt: form_state.values[11].clone(),
|
||||
telefon: form_state.values[12].clone(),
|
||||
skladu: form_state.values[13].clone(),
|
||||
fax: form_state.values[14].clone(),
|
||||
};
|
||||
let _ = grpc_client.put_adresar(put_request).await?;
|
||||
}
|
||||
|
||||
Ok((true, "Saved and exiting application".to_string()))
|
||||
}
|
||||
|
||||
/// Discard changes since last save
|
||||
pub async fn revert(
|
||||
form_state: &mut FormState,
|
||||
|
||||
@@ -4,6 +4,8 @@ use crossterm::event::{KeyEvent, KeyCode, KeyModifiers};
|
||||
use crate::tui::terminal::grpc_client::GrpcClient;
|
||||
use crate::config::binds::config::Config;
|
||||
use crate::ui::handlers::form::FormState;
|
||||
use crate::tui::controls::commands::CommandHandler;
|
||||
use crate::tui::terminal::core::TerminalCore;
|
||||
use crate::modes::{
|
||||
canvas::{common},
|
||||
};
|
||||
@@ -15,7 +17,8 @@ pub async fn handle_command_event(
|
||||
command_input: &mut String,
|
||||
command_message: &mut String,
|
||||
grpc_client: &mut GrpcClient,
|
||||
is_saved: &mut bool,
|
||||
command_handler: &mut CommandHandler,
|
||||
terminal: &mut TerminalCore,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<(bool, String, bool), Box<dyn std::error::Error>> {
|
||||
@@ -37,7 +40,8 @@ pub async fn handle_command_event(
|
||||
command_input,
|
||||
command_message,
|
||||
grpc_client,
|
||||
is_saved,
|
||||
command_handler,
|
||||
terminal,
|
||||
current_position,
|
||||
total_count,
|
||||
).await;
|
||||
@@ -68,7 +72,8 @@ async fn process_command(
|
||||
command_input: &mut String,
|
||||
command_message: &mut String,
|
||||
grpc_client: &mut GrpcClient,
|
||||
is_saved: &mut bool,
|
||||
command_handler: &mut CommandHandler,
|
||||
terminal: &mut TerminalCore,
|
||||
current_position: &mut u64,
|
||||
total_count: u64,
|
||||
) -> Result<(bool, String, bool), Box<dyn std::error::Error>> {
|
||||
@@ -84,32 +89,24 @@ async fn process_command(
|
||||
.unwrap_or("unknown");
|
||||
|
||||
match action {
|
||||
"force_quit" | "save_and_quit" | "quit" => {
|
||||
let (should_exit, message) = command_handler
|
||||
.handle_command(action, terminal)
|
||||
.await?;
|
||||
command_input.clear();
|
||||
Ok((should_exit, message, true))
|
||||
},
|
||||
"save" => {
|
||||
let message = common::save(
|
||||
form_state,
|
||||
grpc_client,
|
||||
is_saved,
|
||||
&mut command_handler.is_saved,
|
||||
current_position,
|
||||
total_count,
|
||||
).await?;
|
||||
command_input.clear();
|
||||
return Ok((false, message, true));
|
||||
},
|
||||
"force_quit" => {
|
||||
let (should_exit, message) = common::force_quit();
|
||||
command_input.clear();
|
||||
return Ok((should_exit, message, true));
|
||||
},
|
||||
"save_and_quit" => {
|
||||
let (should_exit, message) = common::save_and_quit(
|
||||
form_state,
|
||||
grpc_client,
|
||||
current_position,
|
||||
total_count,
|
||||
).await?;
|
||||
command_input.clear();
|
||||
return Ok((should_exit, message, true));
|
||||
},
|
||||
"revert" => {
|
||||
let message = common::revert(
|
||||
form_state,
|
||||
|
||||
@@ -4,8 +4,8 @@ use crossterm::cursor::SetCursorStyle;
|
||||
use crate::tui::terminal::{
|
||||
core::TerminalCore,
|
||||
grpc_client::GrpcClient,
|
||||
commands::CommandHandler,
|
||||
};
|
||||
use crate::tui::controls::commands::CommandHandler;
|
||||
use crate::config::binds::config::Config;
|
||||
use crate::ui::handlers::form::FormState;
|
||||
use crate::ui::handlers::rat_state::UiStateHandler;
|
||||
@@ -224,7 +224,8 @@ impl EventHandler {
|
||||
&mut self.command_input,
|
||||
&mut self.command_message,
|
||||
grpc_client,
|
||||
&mut app_state.ui.is_saved,
|
||||
command_handler,
|
||||
terminal,
|
||||
current_position,
|
||||
total_count,
|
||||
).await?;
|
||||
|
||||
5
client/src/tui/controls.rs
Normal file
5
client/src/tui/controls.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
// src/tui/controls.rs
|
||||
|
||||
pub mod commands;
|
||||
|
||||
pub use commands::*;
|
||||
@@ -1,9 +1,8 @@
|
||||
// src/tui/terminal/commands.rs
|
||||
|
||||
// src/tui/controls/commands.rs
|
||||
use crate::tui::terminal::core::TerminalCore;
|
||||
|
||||
pub struct CommandHandler {
|
||||
is_saved: bool,
|
||||
pub is_saved: bool,
|
||||
}
|
||||
|
||||
impl CommandHandler {
|
||||
@@ -24,7 +23,10 @@ impl CommandHandler {
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_quit(&self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
async fn handle_quit(
|
||||
&self,
|
||||
terminal: &mut TerminalCore,
|
||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
if self.is_saved {
|
||||
terminal.cleanup()?;
|
||||
Ok((true, "Exiting.".into()))
|
||||
@@ -33,12 +35,18 @@ impl CommandHandler {
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_force_quit(&self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
async fn handle_force_quit(
|
||||
&self,
|
||||
terminal: &mut TerminalCore,
|
||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
terminal.cleanup()?;
|
||||
Ok((true, "Force exiting without saving.".into()))
|
||||
}
|
||||
|
||||
async fn handle_save_quit(&mut self, terminal: &mut TerminalCore) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
async fn handle_save_quit(
|
||||
&mut self,
|
||||
terminal: &mut TerminalCore,
|
||||
) -> Result<(bool, String), Box<dyn std::error::Error>> {
|
||||
self.is_saved = true;
|
||||
terminal.cleanup()?;
|
||||
Ok((true, "State saved. Exiting.".into()))
|
||||
@@ -1,2 +1,4 @@
|
||||
// src/tui/mod.rs
|
||||
pub mod terminal;
|
||||
pub mod controls;
|
||||
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
|
||||
pub mod core;
|
||||
pub mod grpc_client;
|
||||
pub mod commands;
|
||||
pub mod event_reader;
|
||||
|
||||
pub use core::TerminalCore;
|
||||
pub use grpc_client::GrpcClient;
|
||||
pub use commands::CommandHandler;
|
||||
pub use event_reader::EventReader;
|
||||
|
||||
@@ -38,7 +38,7 @@ impl FormState {
|
||||
let fields: Vec<&str> = self.fields.iter().map(|s| s.as_str()).collect();
|
||||
let values: Vec<&String> = self.values.iter().collect();
|
||||
|
||||
crate::components::handlers::form::render_form(
|
||||
crate::components::form::form::render_form(
|
||||
f,
|
||||
area,
|
||||
self,
|
||||
|
||||
@@ -4,7 +4,8 @@ use crate::components::{
|
||||
render_background,
|
||||
render_command_line,
|
||||
render_status_line,
|
||||
handlers::{sidebar::{self, calculate_sidebar_layout}, form::render_form},
|
||||
handlers::sidebar::{self, calculate_sidebar_layout},
|
||||
form::form::render_form,
|
||||
intro::{intro},
|
||||
admin::{admin_panel::AdminPanelState},
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::tui::terminal::TerminalCore;
|
||||
use crate::tui::terminal::GrpcClient;
|
||||
use crate::tui::terminal::CommandHandler;
|
||||
use crate::tui::controls::CommandHandler;
|
||||
use crate::tui::terminal::EventReader;
|
||||
use crate::config::colors::themes::Theme;
|
||||
use crate::config::binds::config::Config;
|
||||
|
||||
@@ -8,6 +8,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
&[
|
||||
"proto/common.proto",
|
||||
"proto/adresar.proto",
|
||||
"proto/auth.proto",
|
||||
"proto/uctovnictvo.proto",
|
||||
"proto/table_structure.proto",
|
||||
"proto/table_definition.proto",
|
||||
|
||||
37
common/proto/auth.proto
Normal file
37
common/proto/auth.proto
Normal file
@@ -0,0 +1,37 @@
|
||||
// proto/auth.proto
|
||||
syntax = "proto3";
|
||||
package multieko2.auth;
|
||||
|
||||
import "common.proto";
|
||||
|
||||
service AuthService {
|
||||
rpc Register(RegisterRequest) returns (AuthResponse);
|
||||
rpc Login(LoginRequest) returns (LoginResponse);
|
||||
}
|
||||
|
||||
message RegisterRequest {
|
||||
string username = 1;
|
||||
string email = 2;
|
||||
string password = 3;
|
||||
string password_confirmation = 4;
|
||||
}
|
||||
|
||||
message AuthResponse {
|
||||
string id = 1; // UUID in string format
|
||||
string username = 2; // Registered username
|
||||
string email = 3; // Registered email (if provided)
|
||||
string role = 4; // Default role: 'accountant'
|
||||
}
|
||||
|
||||
message LoginRequest {
|
||||
string identifier = 1; // Can be username or email
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
message LoginResponse {
|
||||
string access_token = 1; // JWT token
|
||||
string token_type = 2; // Usually "Bearer"
|
||||
int32 expires_in = 3; // Expiration in seconds (86400 for 24 hours)
|
||||
string user_id = 4; // User's UUID in string format
|
||||
string role = 5; // User's role
|
||||
}
|
||||
@@ -4,6 +4,9 @@ pub mod proto {
|
||||
pub mod adresar {
|
||||
include!("proto/multieko2.adresar.rs");
|
||||
}
|
||||
pub mod auth {
|
||||
include!("proto/multieko2.auth.rs");
|
||||
}
|
||||
pub mod common {
|
||||
include!("proto/multieko2.common.rs");
|
||||
}
|
||||
|
||||
Binary file not shown.
412
common/src/proto/multieko2.auth.rs
Normal file
412
common/src/proto/multieko2.auth.rs
Normal file
@@ -0,0 +1,412 @@
|
||||
// This file is @generated by prost-build.
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct RegisterRequest {
|
||||
#[prost(string, tag = "1")]
|
||||
pub username: ::prost::alloc::string::String,
|
||||
#[prost(string, tag = "2")]
|
||||
pub email: ::prost::alloc::string::String,
|
||||
#[prost(string, tag = "3")]
|
||||
pub password: ::prost::alloc::string::String,
|
||||
#[prost(string, tag = "4")]
|
||||
pub password_confirmation: ::prost::alloc::string::String,
|
||||
}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct AuthResponse {
|
||||
/// UUID in string format
|
||||
#[prost(string, tag = "1")]
|
||||
pub id: ::prost::alloc::string::String,
|
||||
/// Registered username
|
||||
#[prost(string, tag = "2")]
|
||||
pub username: ::prost::alloc::string::String,
|
||||
/// Registered email (if provided)
|
||||
#[prost(string, tag = "3")]
|
||||
pub email: ::prost::alloc::string::String,
|
||||
/// Default role: 'accountant'
|
||||
#[prost(string, tag = "4")]
|
||||
pub role: ::prost::alloc::string::String,
|
||||
}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct LoginRequest {
|
||||
/// Can be username or email
|
||||
#[prost(string, tag = "1")]
|
||||
pub identifier: ::prost::alloc::string::String,
|
||||
#[prost(string, tag = "2")]
|
||||
pub password: ::prost::alloc::string::String,
|
||||
}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct LoginResponse {
|
||||
/// JWT token
|
||||
#[prost(string, tag = "1")]
|
||||
pub access_token: ::prost::alloc::string::String,
|
||||
/// Usually "Bearer"
|
||||
#[prost(string, tag = "2")]
|
||||
pub token_type: ::prost::alloc::string::String,
|
||||
/// Expiration in seconds (86400 for 24 hours)
|
||||
#[prost(int32, tag = "3")]
|
||||
pub expires_in: i32,
|
||||
/// User's UUID in string format
|
||||
#[prost(string, tag = "4")]
|
||||
pub user_id: ::prost::alloc::string::String,
|
||||
/// User's role
|
||||
#[prost(string, tag = "5")]
|
||||
pub role: ::prost::alloc::string::String,
|
||||
}
|
||||
/// Generated client implementations.
|
||||
pub mod auth_service_client {
|
||||
#![allow(
|
||||
unused_variables,
|
||||
dead_code,
|
||||
missing_docs,
|
||||
clippy::wildcard_imports,
|
||||
clippy::let_unit_value,
|
||||
)]
|
||||
use tonic::codegen::*;
|
||||
use tonic::codegen::http::Uri;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AuthServiceClient<T> {
|
||||
inner: tonic::client::Grpc<T>,
|
||||
}
|
||||
impl AuthServiceClient<tonic::transport::Channel> {
|
||||
/// Attempt to create a new client by connecting to a given endpoint.
|
||||
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
|
||||
where
|
||||
D: TryInto<tonic::transport::Endpoint>,
|
||||
D::Error: Into<StdError>,
|
||||
{
|
||||
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
|
||||
Ok(Self::new(conn))
|
||||
}
|
||||
}
|
||||
impl<T> AuthServiceClient<T>
|
||||
where
|
||||
T: tonic::client::GrpcService<tonic::body::BoxBody>,
|
||||
T::Error: Into<StdError>,
|
||||
T::ResponseBody: Body<Data = Bytes> + std::marker::Send + 'static,
|
||||
<T::ResponseBody as Body>::Error: Into<StdError> + std::marker::Send,
|
||||
{
|
||||
pub fn new(inner: T) -> Self {
|
||||
let inner = tonic::client::Grpc::new(inner);
|
||||
Self { inner }
|
||||
}
|
||||
pub fn with_origin(inner: T, origin: Uri) -> Self {
|
||||
let inner = tonic::client::Grpc::with_origin(inner, origin);
|
||||
Self { inner }
|
||||
}
|
||||
pub fn with_interceptor<F>(
|
||||
inner: T,
|
||||
interceptor: F,
|
||||
) -> AuthServiceClient<InterceptedService<T, F>>
|
||||
where
|
||||
F: tonic::service::Interceptor,
|
||||
T::ResponseBody: Default,
|
||||
T: tonic::codegen::Service<
|
||||
http::Request<tonic::body::BoxBody>,
|
||||
Response = http::Response<
|
||||
<T as tonic::client::GrpcService<tonic::body::BoxBody>>::ResponseBody,
|
||||
>,
|
||||
>,
|
||||
<T as tonic::codegen::Service<
|
||||
http::Request<tonic::body::BoxBody>,
|
||||
>>::Error: Into<StdError> + std::marker::Send + std::marker::Sync,
|
||||
{
|
||||
AuthServiceClient::new(InterceptedService::new(inner, interceptor))
|
||||
}
|
||||
/// Compress requests with the given encoding.
|
||||
///
|
||||
/// This requires the server to support it otherwise it might respond with an
|
||||
/// error.
|
||||
#[must_use]
|
||||
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.inner = self.inner.send_compressed(encoding);
|
||||
self
|
||||
}
|
||||
/// Enable decompressing responses.
|
||||
#[must_use]
|
||||
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.inner = self.inner.accept_compressed(encoding);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of a decoded message.
|
||||
///
|
||||
/// Default: `4MB`
|
||||
#[must_use]
|
||||
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.inner = self.inner.max_decoding_message_size(limit);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of an encoded message.
|
||||
///
|
||||
/// Default: `usize::MAX`
|
||||
#[must_use]
|
||||
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.inner = self.inner.max_encoding_message_size(limit);
|
||||
self
|
||||
}
|
||||
pub async fn register(
|
||||
&mut self,
|
||||
request: impl tonic::IntoRequest<super::RegisterRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::AuthResponse>, tonic::Status> {
|
||||
self.inner
|
||||
.ready()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tonic::Status::unknown(
|
||||
format!("Service was not ready: {}", e.into()),
|
||||
)
|
||||
})?;
|
||||
let codec = tonic::codec::ProstCodec::default();
|
||||
let path = http::uri::PathAndQuery::from_static(
|
||||
"/multieko2.auth.AuthService/Register",
|
||||
);
|
||||
let mut req = request.into_request();
|
||||
req.extensions_mut()
|
||||
.insert(GrpcMethod::new("multieko2.auth.AuthService", "Register"));
|
||||
self.inner.unary(req, path, codec).await
|
||||
}
|
||||
pub async fn login(
|
||||
&mut self,
|
||||
request: impl tonic::IntoRequest<super::LoginRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::LoginResponse>, tonic::Status> {
|
||||
self.inner
|
||||
.ready()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tonic::Status::unknown(
|
||||
format!("Service was not ready: {}", e.into()),
|
||||
)
|
||||
})?;
|
||||
let codec = tonic::codec::ProstCodec::default();
|
||||
let path = http::uri::PathAndQuery::from_static(
|
||||
"/multieko2.auth.AuthService/Login",
|
||||
);
|
||||
let mut req = request.into_request();
|
||||
req.extensions_mut()
|
||||
.insert(GrpcMethod::new("multieko2.auth.AuthService", "Login"));
|
||||
self.inner.unary(req, path, codec).await
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Generated server implementations.
|
||||
pub mod auth_service_server {
|
||||
#![allow(
|
||||
unused_variables,
|
||||
dead_code,
|
||||
missing_docs,
|
||||
clippy::wildcard_imports,
|
||||
clippy::let_unit_value,
|
||||
)]
|
||||
use tonic::codegen::*;
|
||||
/// Generated trait containing gRPC methods that should be implemented for use with AuthServiceServer.
|
||||
#[async_trait]
|
||||
pub trait AuthService: std::marker::Send + std::marker::Sync + 'static {
|
||||
async fn register(
|
||||
&self,
|
||||
request: tonic::Request<super::RegisterRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::AuthResponse>, tonic::Status>;
|
||||
async fn login(
|
||||
&self,
|
||||
request: tonic::Request<super::LoginRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::LoginResponse>, tonic::Status>;
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct AuthServiceServer<T> {
|
||||
inner: Arc<T>,
|
||||
accept_compression_encodings: EnabledCompressionEncodings,
|
||||
send_compression_encodings: EnabledCompressionEncodings,
|
||||
max_decoding_message_size: Option<usize>,
|
||||
max_encoding_message_size: Option<usize>,
|
||||
}
|
||||
impl<T> AuthServiceServer<T> {
|
||||
pub fn new(inner: T) -> Self {
|
||||
Self::from_arc(Arc::new(inner))
|
||||
}
|
||||
pub fn from_arc(inner: Arc<T>) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
accept_compression_encodings: Default::default(),
|
||||
send_compression_encodings: Default::default(),
|
||||
max_decoding_message_size: None,
|
||||
max_encoding_message_size: None,
|
||||
}
|
||||
}
|
||||
pub fn with_interceptor<F>(
|
||||
inner: T,
|
||||
interceptor: F,
|
||||
) -> InterceptedService<Self, F>
|
||||
where
|
||||
F: tonic::service::Interceptor,
|
||||
{
|
||||
InterceptedService::new(Self::new(inner), interceptor)
|
||||
}
|
||||
/// Enable decompressing requests with the given encoding.
|
||||
#[must_use]
|
||||
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.accept_compression_encodings.enable(encoding);
|
||||
self
|
||||
}
|
||||
/// Compress responses with the given encoding, if the client supports it.
|
||||
#[must_use]
|
||||
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.send_compression_encodings.enable(encoding);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of a decoded message.
|
||||
///
|
||||
/// Default: `4MB`
|
||||
#[must_use]
|
||||
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.max_decoding_message_size = Some(limit);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of an encoded message.
|
||||
///
|
||||
/// Default: `usize::MAX`
|
||||
#[must_use]
|
||||
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.max_encoding_message_size = Some(limit);
|
||||
self
|
||||
}
|
||||
}
|
||||
impl<T, B> tonic::codegen::Service<http::Request<B>> for AuthServiceServer<T>
|
||||
where
|
||||
T: AuthService,
|
||||
B: Body + std::marker::Send + 'static,
|
||||
B::Error: Into<StdError> + std::marker::Send + 'static,
|
||||
{
|
||||
type Response = http::Response<tonic::body::BoxBody>;
|
||||
type Error = std::convert::Infallible;
|
||||
type Future = BoxFuture<Self::Response, Self::Error>;
|
||||
fn poll_ready(
|
||||
&mut self,
|
||||
_cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
fn call(&mut self, req: http::Request<B>) -> Self::Future {
|
||||
match req.uri().path() {
|
||||
"/multieko2.auth.AuthService/Register" => {
|
||||
#[allow(non_camel_case_types)]
|
||||
struct RegisterSvc<T: AuthService>(pub Arc<T>);
|
||||
impl<
|
||||
T: AuthService,
|
||||
> tonic::server::UnaryService<super::RegisterRequest>
|
||||
for RegisterSvc<T> {
|
||||
type Response = super::AuthResponse;
|
||||
type Future = BoxFuture<
|
||||
tonic::Response<Self::Response>,
|
||||
tonic::Status,
|
||||
>;
|
||||
fn call(
|
||||
&mut self,
|
||||
request: tonic::Request<super::RegisterRequest>,
|
||||
) -> Self::Future {
|
||||
let inner = Arc::clone(&self.0);
|
||||
let fut = async move {
|
||||
<T as AuthService>::register(&inner, request).await
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
}
|
||||
let accept_compression_encodings = self.accept_compression_encodings;
|
||||
let send_compression_encodings = self.send_compression_encodings;
|
||||
let max_decoding_message_size = self.max_decoding_message_size;
|
||||
let max_encoding_message_size = self.max_encoding_message_size;
|
||||
let inner = self.inner.clone();
|
||||
let fut = async move {
|
||||
let method = RegisterSvc(inner);
|
||||
let codec = tonic::codec::ProstCodec::default();
|
||||
let mut grpc = tonic::server::Grpc::new(codec)
|
||||
.apply_compression_config(
|
||||
accept_compression_encodings,
|
||||
send_compression_encodings,
|
||||
)
|
||||
.apply_max_message_size_config(
|
||||
max_decoding_message_size,
|
||||
max_encoding_message_size,
|
||||
);
|
||||
let res = grpc.unary(method, req).await;
|
||||
Ok(res)
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
"/multieko2.auth.AuthService/Login" => {
|
||||
#[allow(non_camel_case_types)]
|
||||
struct LoginSvc<T: AuthService>(pub Arc<T>);
|
||||
impl<T: AuthService> tonic::server::UnaryService<super::LoginRequest>
|
||||
for LoginSvc<T> {
|
||||
type Response = super::LoginResponse;
|
||||
type Future = BoxFuture<
|
||||
tonic::Response<Self::Response>,
|
||||
tonic::Status,
|
||||
>;
|
||||
fn call(
|
||||
&mut self,
|
||||
request: tonic::Request<super::LoginRequest>,
|
||||
) -> Self::Future {
|
||||
let inner = Arc::clone(&self.0);
|
||||
let fut = async move {
|
||||
<T as AuthService>::login(&inner, request).await
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
}
|
||||
let accept_compression_encodings = self.accept_compression_encodings;
|
||||
let send_compression_encodings = self.send_compression_encodings;
|
||||
let max_decoding_message_size = self.max_decoding_message_size;
|
||||
let max_encoding_message_size = self.max_encoding_message_size;
|
||||
let inner = self.inner.clone();
|
||||
let fut = async move {
|
||||
let method = LoginSvc(inner);
|
||||
let codec = tonic::codec::ProstCodec::default();
|
||||
let mut grpc = tonic::server::Grpc::new(codec)
|
||||
.apply_compression_config(
|
||||
accept_compression_encodings,
|
||||
send_compression_encodings,
|
||||
)
|
||||
.apply_max_message_size_config(
|
||||
max_decoding_message_size,
|
||||
max_encoding_message_size,
|
||||
);
|
||||
let res = grpc.unary(method, req).await;
|
||||
Ok(res)
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
_ => {
|
||||
Box::pin(async move {
|
||||
let mut response = http::Response::new(empty_body());
|
||||
let headers = response.headers_mut();
|
||||
headers
|
||||
.insert(
|
||||
tonic::Status::GRPC_STATUS,
|
||||
(tonic::Code::Unimplemented as i32).into(),
|
||||
);
|
||||
headers
|
||||
.insert(
|
||||
http::header::CONTENT_TYPE,
|
||||
tonic::metadata::GRPC_CONTENT_TYPE,
|
||||
);
|
||||
Ok(response)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<T> Clone for AuthServiceServer<T> {
|
||||
fn clone(&self) -> Self {
|
||||
let inner = self.inner.clone();
|
||||
Self {
|
||||
inner,
|
||||
accept_compression_encodings: self.accept_compression_encodings,
|
||||
send_compression_encodings: self.send_compression_encodings,
|
||||
max_decoding_message_size: self.max_decoding_message_size,
|
||||
max_encoding_message_size: self.max_encoding_message_size,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Generated gRPC service name
|
||||
pub const SERVICE_NAME: &str = "multieko2.auth.AuthService";
|
||||
impl<T> tonic::server::NamedService for AuthServiceServer<T> {
|
||||
const NAME: &'static str = SERVICE_NAME;
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ dotenvy = "0.15.7"
|
||||
prost = "0.13.5"
|
||||
serde = { version = "1.0.218", features = ["derive"] }
|
||||
serde_json = "1.0.140"
|
||||
sqlx = { version = "0.8.3", features = ["chrono", "postgres", "runtime-tokio", "runtime-tokio-native-tls", "time"] }
|
||||
sqlx = { version = "0.8.3", features = ["chrono", "postgres", "runtime-tokio", "runtime-tokio-native-tls", "time", "uuid"] }
|
||||
tokio = { version = "1.43.0", features = ["full", "macros"] }
|
||||
tonic = "0.12.3"
|
||||
tonic-reflection = "0.12.3"
|
||||
@@ -24,6 +24,10 @@ thiserror = "2.0.12"
|
||||
dashmap = "6.1.0"
|
||||
lazy_static = "1.5.0"
|
||||
regex = "1.11.1"
|
||||
bcrypt = "0.17.0"
|
||||
validator = { version = "0.20.0", features = ["derive"] }
|
||||
uuid = { version = "1.16.0", features = ["serde", "v4"] }
|
||||
jsonwebtoken = "9.3.1"
|
||||
|
||||
[lib]
|
||||
name = "server"
|
||||
|
||||
38
server/migrations/20250324192805_auth.sql
Normal file
38
server/migrations/20250324192805_auth.sql
Normal file
@@ -0,0 +1,38 @@
|
||||
-- Add migration script here
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
username VARCHAR(255) NOT NULL UNIQUE,
|
||||
email VARCHAR(255) UNIQUE,
|
||||
password_hash VARCHAR(255),
|
||||
role VARCHAR(20) NOT NULL DEFAULT 'accountant',
|
||||
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Add an index for faster lookups
|
||||
CREATE INDEX idx_users_email_username ON users(email, username);
|
||||
|
||||
ALTER TABLE users
|
||||
ADD CONSTRAINT valid_roles CHECK (role IN (
|
||||
'admin',
|
||||
'moderator',
|
||||
'accountant',
|
||||
'viewer'
|
||||
));
|
||||
|
||||
-- Create JWT sessions table
|
||||
CREATE TABLE user_sessions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
jwt_token TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Add indexes
|
||||
CREATE INDEX idx_sessions_user ON user_sessions(user_id);
|
||||
CREATE INDEX idx_sessions_expires ON user_sessions(expires_at);
|
||||
|
||||
|
||||
|
||||
10
server/src/auth/docs/first_reg.txt
Normal file
10
server/src/auth/docs/first_reg.txt
Normal file
@@ -0,0 +1,10 @@
|
||||
❯ grpcurl -plaintext -d '{
|
||||
"username": "testuser2",
|
||||
"email": "test2@example.com"
|
||||
}' localhost:50051 multieko2.auth.AuthService/Register
|
||||
{
|
||||
"id": "5fa9bbce-85e0-4b06-8364-b561770c2fdd",
|
||||
"username": "testuser2",
|
||||
"email": "test2@example.com",
|
||||
"role": "accountant"
|
||||
}
|
||||
51
server/src/auth/docs/reg_log.txt
Normal file
51
server/src/auth/docs/reg_log.txt
Normal file
@@ -0,0 +1,51 @@
|
||||
❯ grpcurl -plaintext -d '{
|
||||
"username": "testuser3",
|
||||
"email": "test3@example.com",
|
||||
"password": "your_password",
|
||||
"password_confirmation": "your_password"
|
||||
}' localhost:50051 multieko2.auth.AuthService/Register
|
||||
{
|
||||
"id": "96d2fd35-b39d-4c05-916a-66134453d34c",
|
||||
"username": "testuser3",
|
||||
"email": "test3@example.com",
|
||||
"role": "accountant"
|
||||
}
|
||||
❯ grpcurl -plaintext -d '{
|
||||
"identifier": "testuser3"
|
||||
}' localhost:50051 multieko2.auth.AuthService/Login
|
||||
ERROR:
|
||||
Code: Unauthenticated
|
||||
Message: Invalid credentials
|
||||
❯ grpcurl -plaintext -d '{
|
||||
"identifier": "testuser3",
|
||||
"password": "your_password"
|
||||
}' localhost:50051 multieko2.auth.AuthService/Login
|
||||
{
|
||||
"accessToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI5NmQyZmQzNS1iMzlkLTRjMDUtOTE2YS02NjEzNDQ1M2QzNGMiLCJleHAiOjE3NDI5ODE2MTAsInJvbGUiOiJhY2NvdW50YW50In0.78VIR3X4QZohzeI5x3xmkmqcICTusOC6PELPohMV-k8",
|
||||
"tokenType": "Bearer",
|
||||
"expiresIn": 86400,
|
||||
"userId": "96d2fd35-b39d-4c05-916a-66134453d34c",
|
||||
"role": "accountant"
|
||||
}
|
||||
❯ grpcurl -plaintext -d '{
|
||||
"username": "testuser4",
|
||||
"email": "test4@example.com"
|
||||
}' localhost:50051 multieko2.auth.AuthService/Register
|
||||
{
|
||||
"id": "413d7ecc-f231-48af-8c5a-566b1dc2bf0b",
|
||||
"username": "testuser4",
|
||||
"email": "test4@example.com",
|
||||
"role": "accountant"
|
||||
}
|
||||
❯ grpcurl -plaintext -d '{
|
||||
"identifier": "test4@example.com"
|
||||
}' localhost:50051 multieko2.auth.AuthService/Login
|
||||
{
|
||||
"accessToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0MTNkN2VjYy1mMjMxLTQ4YWYtOGM1YS01NjZiMWRjMmJmMGIiLCJleHAiOjE3NDI5ODE3MDEsInJvbGUiOiJhY2NvdW50YW50In0.4Hzu3tTZRNGHnBSgeCbGy2tFTl8EzpPdXBhcW8kuIc8",
|
||||
"tokenType": "Bearer",
|
||||
"expiresIn": 86400,
|
||||
"userId": "413d7ecc-f231-48af-8c5a-566b1dc2bf0b",
|
||||
"role": "accountant"
|
||||
}
|
||||
╭─ ~/Doc/pr/multieko2/server auth ······ ✔
|
||||
╰─
|
||||
7
server/src/auth/handlers.rs
Normal file
7
server/src/auth/handlers.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
// src/auth/handlers.rs
|
||||
|
||||
pub mod register;
|
||||
pub mod login;
|
||||
|
||||
pub use register::*;
|
||||
pub use login::*;
|
||||
46
server/src/auth/handlers/login.rs
Normal file
46
server/src/auth/handlers/login.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
// src/auth/handlers/login.rs
|
||||
use bcrypt::verify;
|
||||
use tonic::{Request, Response, Status};
|
||||
use crate::db::PgPool;
|
||||
use crate::auth::{models::AuthError, logic::jwt}; // Fixed import path
|
||||
use common::proto::multieko2::auth::{LoginRequest, LoginResponse};
|
||||
|
||||
pub async fn login(
|
||||
pool: &PgPool,
|
||||
request: LoginRequest,
|
||||
) -> Result<Response<LoginResponse>, Status> {
|
||||
let user = sqlx::query!(
|
||||
r#"
|
||||
SELECT id, password_hash, role
|
||||
FROM users
|
||||
WHERE username = $1 OR email = $1
|
||||
"#,
|
||||
request.identifier
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|e| Status::internal(e.to_string()))?
|
||||
.ok_or_else(|| Status::unauthenticated("Invalid credentials"))?;
|
||||
|
||||
// Handle the optional password_hash
|
||||
let password_hash = user.password_hash
|
||||
.ok_or_else(|| Status::internal("User account has no password set"))?;
|
||||
|
||||
// Verify the password
|
||||
if !verify(&request.password, &password_hash)
|
||||
.map_err(|e| Status::internal(e.to_string()))?
|
||||
{
|
||||
return Err(Status::unauthenticated("Invalid credentials"));
|
||||
}
|
||||
|
||||
let token = jwt::generate_token(user.id, &user.role)
|
||||
.map_err(|e| Status::internal(e.to_string()))?;
|
||||
|
||||
Ok(Response::new(LoginResponse {
|
||||
access_token: token,
|
||||
token_type: "Bearer".to_string(),
|
||||
expires_in: 86400, // 24 hours
|
||||
user_id: user.id.to_string(),
|
||||
role: user.role,
|
||||
}))
|
||||
}
|
||||
48
server/src/auth/handlers/register.rs
Normal file
48
server/src/auth/handlers/register.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
// src/auth/handlers/register.rs
|
||||
use bcrypt::{hash, DEFAULT_COST};
|
||||
use tonic::{Response, Status};
|
||||
use common::proto::multieko2::auth::{RegisterRequest, AuthResponse};
|
||||
use crate::db::PgPool;
|
||||
use crate::auth::models::AuthError;
|
||||
|
||||
pub async fn register(
|
||||
pool: &PgPool,
|
||||
payload: RegisterRequest,
|
||||
) -> Result<Response<AuthResponse>, Status> {
|
||||
// Validate passwords match
|
||||
if payload.password != payload.password_confirmation {
|
||||
return Err(Status::invalid_argument(AuthError::PasswordMismatch.to_string()));
|
||||
}
|
||||
|
||||
// Hash password
|
||||
let password_hash = hash(payload.password, DEFAULT_COST)
|
||||
.map_err(|e| Status::internal(AuthError::HashingError(e.to_string()).to_string()))?;
|
||||
|
||||
// Insert user
|
||||
let user = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO users (username, email, password_hash, role)
|
||||
VALUES ($1, $2, $3, 'accountant')
|
||||
RETURNING id, username, email, role
|
||||
"#,
|
||||
payload.username,
|
||||
payload.email,
|
||||
password_hash
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
if e.to_string().contains("duplicate key") {
|
||||
Status::already_exists(AuthError::UserExists.to_string())
|
||||
} else {
|
||||
Status::internal(AuthError::DatabaseError(e.to_string()).to_string())
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok(Response::new(AuthResponse {
|
||||
id: user.id.to_string(),
|
||||
username: user.username,
|
||||
email: user.email.unwrap_or_default(),
|
||||
role: user.role,
|
||||
}))
|
||||
}
|
||||
9
server/src/auth/logic.rs
Normal file
9
server/src/auth/logic.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
// src/auth/logic.rs
|
||||
|
||||
pub mod jwt;
|
||||
pub mod middleware;
|
||||
// TODO implement RBAC on all of the endpoints
|
||||
// pub mod rbac;
|
||||
|
||||
pub use jwt::*;
|
||||
pub use middleware::*;
|
||||
55
server/src/auth/logic/jwt.rs
Normal file
55
server/src/auth/logic/jwt.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
// src/auth/jwt.rs
|
||||
use jsonwebtoken::{encode, decode, Header, EncodingKey, DecodingKey, Validation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::{Duration, OffsetDateTime};
|
||||
use uuid::Uuid;
|
||||
use std::sync::OnceLock;
|
||||
use crate::auth::models::AuthError;
|
||||
|
||||
static KEYS: OnceLock<Keys> = OnceLock::new();
|
||||
|
||||
struct Keys {
|
||||
encoding: EncodingKey,
|
||||
decoding: DecodingKey,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Claims {
|
||||
pub sub: Uuid, // User ID
|
||||
pub exp: i64, // Expiration time
|
||||
pub role: String, // User role
|
||||
}
|
||||
|
||||
pub fn init_jwt() -> Result<(), AuthError> {
|
||||
let secret = std::env::var("JWT_SECRET")
|
||||
.map_err(|_| AuthError::ConfigError("JWT_SECRET must be set".to_string()))?;
|
||||
|
||||
KEYS.set(Keys {
|
||||
encoding: EncodingKey::from_secret(secret.as_bytes()),
|
||||
decoding: DecodingKey::from_secret(secret.as_bytes()),
|
||||
}).map_err(|_| AuthError::ConfigError("Failed to initialize JWT keys".to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn generate_token(user_id: Uuid, role: &str) -> Result<String, AuthError> {
|
||||
let keys = KEYS.get().ok_or(AuthError::ConfigError("JWT not initialized".to_string()))?;
|
||||
|
||||
let exp = OffsetDateTime::now_utc() + Duration::days(365000);
|
||||
let claims = Claims {
|
||||
sub: user_id,
|
||||
exp: exp.unix_timestamp(),
|
||||
role: role.to_string(),
|
||||
};
|
||||
|
||||
encode(&Header::default(), &claims, &keys.encoding)
|
||||
.map_err(|e| AuthError::JwtError(e.to_string()))
|
||||
}
|
||||
|
||||
pub fn validate_token(token: &str) -> Result<Claims, AuthError> {
|
||||
let keys = KEYS.get().ok_or(AuthError::ConfigError("JWT not initialized".to_string()))?;
|
||||
|
||||
decode::<Claims>(token, &keys.decoding, &Validation::default())
|
||||
.map(|data| data.claims)
|
||||
.map_err(|e| AuthError::JwtError(e.to_string()))
|
||||
}
|
||||
22
server/src/auth/logic/middleware.rs
Normal file
22
server/src/auth/logic/middleware.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
// src/auth/middleware.rs
|
||||
use tonic::{metadata::MetadataValue, service::Interceptor, Status};
|
||||
use crate::auth::{logic::jwt, models::AuthError};
|
||||
|
||||
pub struct AuthInterceptor;
|
||||
|
||||
impl Interceptor for AuthInterceptor {
|
||||
fn call(&mut self, mut request: tonic::Request<()>) -> Result<tonic::Request<()>, Status> {
|
||||
let metadata = request.metadata();
|
||||
let token = metadata.get("authorization")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.strip_prefix("Bearer "))
|
||||
.ok_or(Status::unauthenticated("Missing authorization header"))?;
|
||||
|
||||
let claims = jwt::validate_token(token)
|
||||
.map_err(|e| Status::unauthenticated(e.to_string()))?;
|
||||
|
||||
// Store claims in request extensions
|
||||
request.extensions_mut().insert(claims);
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
36
server/src/auth/logic/rbac.rs
Normal file
36
server/src/auth/logic/rbac.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
// src/auth/logic/rbac.rs
|
||||
|
||||
use tower::ServiceBuilder;
|
||||
use crate::auth::logic::rbac;
|
||||
|
||||
pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// ... existing setup code ...
|
||||
|
||||
// Create service layers
|
||||
let adresar_layer = ServiceBuilder::new()
|
||||
.layer(rbac::create_adresar_layer())
|
||||
.into_inner();
|
||||
|
||||
let uctovnictvo_layer = ServiceBuilder::new()
|
||||
.layer(rbac::create_uctovnictvo_layer())
|
||||
.into_inner();
|
||||
|
||||
// Create services with layers
|
||||
let adresar_service = AdresarServer::new(AdresarService { db_pool: db_pool.clone() })
|
||||
.layer(adresar_layer);
|
||||
|
||||
let uctovnictvo_service = UctovnictvoServer::new(UctovnictvoService { db_pool: db_pool.clone() })
|
||||
.layer(uctovnictvo_layer);
|
||||
|
||||
// ... repeat for other services ...
|
||||
|
||||
Server::builder()
|
||||
.add_service(auth_server)
|
||||
.add_service(adresar_service)
|
||||
.add_service(uctovnictvo_service)
|
||||
// ... other services ...
|
||||
.serve(addr)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
6
server/src/auth/mod.rs
Normal file
6
server/src/auth/mod.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
// src/auth/mod.rs
|
||||
|
||||
pub mod models;
|
||||
pub mod logic;
|
||||
pub mod handlers;
|
||||
|
||||
41
server/src/auth/models.rs
Normal file
41
server/src/auth/models.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
// src/auth/models.rs
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use validator::Validate;
|
||||
|
||||
#[derive(Debug, Validate, Deserialize)]
|
||||
pub struct RegisterRequest {
|
||||
#[validate(length(min = 1, max = 30))]
|
||||
pub username: String,
|
||||
#[validate(email)]
|
||||
pub email: String,
|
||||
#[validate(length(min = 1))]
|
||||
pub password: String,
|
||||
pub password_confirmation: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Validate, Deserialize)]
|
||||
pub struct LoginRequest {
|
||||
#[validate(length(min = 1))]
|
||||
pub identifier: String,
|
||||
#[validate(length(min = 1))]
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AuthError {
|
||||
#[error("Passwords do not match")]
|
||||
PasswordMismatch,
|
||||
#[error("User already exists")]
|
||||
UserExists,
|
||||
#[error("Database error: {0}")]
|
||||
DatabaseError(String),
|
||||
#[error("Hashing error: {0}")]
|
||||
HashingError(String),
|
||||
#[error("Invalid credentials")]
|
||||
InvalidCredentials,
|
||||
#[error("JWT error: {0}")]
|
||||
JwtError(String),
|
||||
#[error("Configuration error: {0}")]
|
||||
ConfigError(String),
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
// src/db.rs
|
||||
use sqlx::postgres::{PgPool, PgPoolOptions};
|
||||
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
pub use sqlx::postgres::PgPool;
|
||||
use std::time::Duration;
|
||||
use tracing::info;
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// src/lib.rs
|
||||
pub mod db;
|
||||
pub mod auth;
|
||||
pub mod server;
|
||||
pub mod adresar;
|
||||
pub mod uctovnictvo;
|
||||
|
||||
@@ -10,15 +10,22 @@ use crate::server::services::{
|
||||
TableDefinitionService,
|
||||
TablesDataService,
|
||||
TableScriptService,
|
||||
AuthServiceImpl
|
||||
};
|
||||
use common::proto::multieko2::{
|
||||
adresar::adresar_server::AdresarServer,
|
||||
uctovnictvo::uctovnictvo_server::UctovnictvoServer,
|
||||
table_structure::table_structure_service_server::TableStructureServiceServer,
|
||||
table_definition::table_definition_server::TableDefinitionServer,
|
||||
tables_data::tables_data_server::TablesDataServer,
|
||||
table_script::table_script_server::TableScriptServer,
|
||||
auth::auth_service_server::AuthServiceServer
|
||||
};
|
||||
use common::proto::multieko2::adresar::adresar_server::AdresarServer;
|
||||
use common::proto::multieko2::uctovnictvo::uctovnictvo_server::UctovnictvoServer;
|
||||
use common::proto::multieko2::table_structure::table_structure_service_server::TableStructureServiceServer;
|
||||
use common::proto::multieko2::table_definition::table_definition_server::TableDefinitionServer;
|
||||
use common::proto::multieko2::tables_data::tables_data_server::TablesDataServer;
|
||||
use common::proto::multieko2::table_script::table_script_server::TableScriptServer;
|
||||
|
||||
pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Initialize JWT for authentication
|
||||
crate::auth::logic::jwt::init_jwt()?;
|
||||
|
||||
let addr = "[::1]:50051".parse()?;
|
||||
|
||||
let reflection_service = ReflectionBuilder::configure()
|
||||
@@ -27,8 +34,9 @@ pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error:
|
||||
|
||||
// Initialize services
|
||||
let table_definition_service = TableDefinitionService { db_pool: db_pool.clone() };
|
||||
let tables_data_service = TablesDataService { db_pool: db_pool.clone() }; // Add this
|
||||
let tables_data_service = TablesDataService { db_pool: db_pool.clone() };
|
||||
let table_script_service = TableScriptService { db_pool: db_pool.clone() };
|
||||
let auth_service = AuthServiceImpl { db_pool: db_pool.clone() };
|
||||
|
||||
Server::builder()
|
||||
.add_service(AdresarServer::new(AdresarService { db_pool: db_pool.clone() }))
|
||||
@@ -37,6 +45,7 @@ pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error:
|
||||
.add_service(TableDefinitionServer::new(table_definition_service))
|
||||
.add_service(TablesDataServer::new(tables_data_service))
|
||||
.add_service(TableScriptServer::new(table_script_service))
|
||||
.add_service(AuthServiceServer::new(auth_service))
|
||||
.add_service(reflection_service)
|
||||
.serve(addr)
|
||||
.await?;
|
||||
|
||||
36
server/src/server/services/auth_service.rs
Normal file
36
server/src/server/services/auth_service.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
// src/server/services/auth_service.rs
|
||||
use tonic::{Request, Response, Status};
|
||||
use common::proto::multieko2::auth::{
|
||||
auth_service_server::AuthService,
|
||||
RegisterRequest, AuthResponse,
|
||||
LoginRequest, LoginResponse
|
||||
};
|
||||
use crate::auth::handlers::{
|
||||
login::login,
|
||||
register::register
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AuthServiceImpl {
|
||||
pub db_pool: PgPool,
|
||||
}
|
||||
|
||||
#[tonic::async_trait]
|
||||
impl AuthService for AuthServiceImpl {
|
||||
async fn register(
|
||||
&self,
|
||||
request: Request<RegisterRequest>,
|
||||
) -> Result<Response<AuthResponse>, Status> {
|
||||
let response = register(&self.db_pool, request.into_inner()).await?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn login(
|
||||
&self,
|
||||
request: Request<LoginRequest>,
|
||||
) -> Result<Response<LoginResponse>, Status> {
|
||||
let response = login(&self.db_pool, request.into_inner()).await?;
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ pub mod uctovnictvo_service;
|
||||
pub mod table_definition_service;
|
||||
pub mod tables_data_service;
|
||||
pub mod table_script_service;
|
||||
pub mod auth_service;
|
||||
|
||||
pub use adresar_service::AdresarService;
|
||||
pub use table_structure_service::TableStructureHandler;
|
||||
@@ -13,3 +14,4 @@ pub use uctovnictvo_service::UctovnictvoService;
|
||||
pub use table_definition_service::TableDefinitionService;
|
||||
pub use tables_data_service::TablesDataService;
|
||||
pub use table_script_service::TableScriptService;
|
||||
pub use auth_service::AuthServiceImpl;
|
||||
|
||||
Reference in New Issue
Block a user