Add real auth, authorization, server push and pinned TLS
Browse files at this commit5f39b7676c5243ebdec27b6d823fc56563a37218Parent: c2e3b2d- feat
- add real auth, authorization, server push and pinned TLS
35 changed files +1607 -864
- configs/client_config.toml +1 -0
- configs/server_config.example.toml +2 -0
- crates/client/Cargo.toml +2 -0
- crates/client/src/gui.rs +12 -43
- crates/client/src/gui/auth.rs +25 -10
- crates/client/src/gui/chat.rs +246 -82
- crates/client/src/lib.rs +8 -6
- crates/client/src/main.rs +2 -0
- crates/client/src/network.rs +134 -128
- crates/common/Cargo.toml +2 -0
- crates/common/src/certificate.rs +8 -0
- crates/common/src/config.rs +28 -13
- crates/common/src/constant.rs +2 -1
- crates/common/src/error.rs +24 -23
- crates/common/src/event.rs +14 -0
- crates/common/src/lib.rs +2 -0
- crates/common/src/model.rs +1 -0
- crates/common/src/network.rs +8 -9
- crates/common/src/request.rs +13 -14
- crates/common/src/response.rs +8 -21
- crates/common/src/validate.rs +13 -2
- crates/server/Cargo.toml +6 -5
- crates/server/src/authentication.rs +124 -7
- crates/server/src/certificate.rs +42 -0
- crates/server/src/community.rs +88 -41
- crates/server/src/database.rs +75 -34
- crates/server/src/error.rs +9 -22
- crates/server/src/lib.rs +24 -20
- crates/server/src/main.rs +4 -2
- crates/server/src/message.rs +68 -62
- crates/server/src/network.rs +128 -119
- crates/server/src/request.rs +322 -78
- crates/server/src/test.rs +1 -4
- crates/server/src/user.rs +71 -47
- crates/server/src/user_community.rs +90 -71
configs/client_config.tomlmodified+1 -0
| @@ -1,3 +1,4 @@ | |||
| 1 | [client_config] | 1 | [client_config] |
| 2 | server_address = "127.0.0.1:2026" | 2 | server_address = "127.0.0.1:2026" |
| 3 | server_name = "localhost" | 3 | server_name = "localhost" |
| 4 | +server_fingerprint = "" | ||
configs/server_config.example.tomlmodified+2 -0
| @@ -1,3 +1,5 @@ | |||
| 1 | [server_config] | 1 | [server_config] |
| 2 | database_path = "yumush.db" | 2 | database_path = "yumush.db" |
| 3 | server_address = "127.0.0.1:2026" | 3 | server_address = "127.0.0.1:2026" |
| 4 | +certificate_path = "server_certificate.der" | ||
| 5 | +key_path = "server_key.der" | ||
crates/client/Cargo.tomlmodified+2 -0
| @@ -9,6 +9,8 @@ tokio.workspace = true | |||
| 9 | quinn = { workspace = true, features = ["rustls-ring"] } | 9 | quinn = { workspace = true, features = ["rustls-ring"] } |
| 10 | 10 | ||
| 11 | gpui-kit = "0.7.0" | 11 | gpui-kit = "0.7.0" |
| 12 | +tracing = "0.1.44" | ||
| 13 | +tracing-subscriber = "0.3.23" | ||
| 12 | 14 | ||
| 13 | [lints] | 15 | [lints] |
| 14 | workspace = true | 16 | workspace = true |
crates/client/src/gui.rsmodified+12 -43
| @@ -1,5 +1,4 @@ | |||
| 1 | use std::fmt::Display; | 1 | use std::fmt::Display; |
| 2 | -use std::time::Duration; | ||
| 3 | 2 | ||
| 4 | use common::model::User; | 3 | use common::model::User; |
| 5 | use gpui_kit::{ | 4 | use gpui_kit::{ |
| @@ -20,8 +19,6 @@ mod chat; | |||
| 20 | use auth::Auth; | 19 | use auth::Auth; |
| 21 | use chat::Chat; | 20 | use chat::Chat; |
| 22 | 21 | ||
| 23 | -const CHECK_INTERVAL: Duration = Duration::from_secs(3); | ||
| 24 | - | ||
| 25 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 22 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 26 | enum Route { | 23 | enum Route { |
| 27 | Login, | 24 | Login, |
| @@ -68,43 +65,17 @@ impl Yumush { | |||
| 68 | } | 65 | } |
| 69 | } | 66 | } |
| 70 | 67 | ||
| 71 | - fn start_polling(&self, window: &mut Window, cx: &mut Context<Self>) { | ||
| 72 | - cx.spawn_in(window, async move |this, cx| { | ||
| 73 | - loop { | ||
| 74 | - cx.background_executor().timer(CHECK_INTERVAL).await; | ||
| 75 | - | ||
| 76 | - let keep_going = this.update_in(cx, |yumush, window, cx| { | ||
| 77 | - if yumush.user.is_none() { | ||
| 78 | - return false; | ||
| 79 | - } | ||
| 80 | - | ||
| 81 | - if yumush.connected { | ||
| 82 | - yumush.get_chat_users(window, cx); | ||
| 83 | - yumush.get_communities(window, cx); | ||
| 84 | - } | ||
| 85 | - | ||
| 86 | - true | ||
| 87 | - }); | ||
| 88 | - | ||
| 89 | - if !matches!(keep_going, Ok(true)) { | ||
| 90 | - break; | ||
| 91 | - } | ||
| 92 | - } | ||
| 93 | - }) | ||
| 94 | - .detach(); | ||
| 95 | - } | ||
| 96 | - | ||
| 97 | fn logout(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 68 | fn logout(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 98 | - let Some(user) = self.user.take() else { | 69 | + if self.user.take().is_none() { |
| 99 | return; | 70 | return; |
| 100 | - }; | 71 | + } |
| 101 | let network = self.network.clone(); | 72 | let network = self.network.clone(); |
| 102 | 73 | ||
| 103 | self.chat.reset(); | 74 | self.chat.reset(); |
| 104 | self.change_page(Route::Login, window, cx); | 75 | self.change_page(Route::Login, window, cx); |
| 105 | 76 | ||
| 106 | cx.spawn_in(window, async move |this, cx| { | 77 | cx.spawn_in(window, async move |this, cx| { |
| 107 | - if let Err(error) = network.deauthenticate(&user.username).await { | 78 | + if let Err(error) = network.logout().await { |
| 108 | notify_error(&this, cx, error); | 79 | notify_error(&this, cx, error); |
| 109 | } | 80 | } |
| 110 | }) | 81 | }) |
| @@ -128,21 +99,19 @@ impl Yumush { | |||
| 128 | cx: &mut Context<Self>, | 99 | cx: &mut Context<Self>, |
| 129 | ) { | 100 | ) { |
| 130 | match event { | 101 | match event { |
| 131 | - NetworkEvent::Connected(user) => { | 102 | + NetworkEvent::Connected => { |
| 132 | self.connected = true; | 103 | self.connected = true; |
| 133 | - match user { | 104 | + if self.user.is_some() { |
| 134 | - Some(user) => self.user = Some(user), | 105 | + self.reload(window, cx); |
| 135 | - None if self.user.is_some() => { | ||
| 136 | - self.user = None; | ||
| 137 | - self.change_page(Route::Login, window, cx); | ||
| 138 | - } | ||
| 139 | - None => {} | ||
| 140 | } | 106 | } |
| 141 | } | 107 | } |
| 142 | - NetworkEvent::ConnectionFailed(_) | NetworkEvent::Disconnected(_) => { | 108 | + NetworkEvent::Disconnected(_) => self.connected = false, |
| 143 | - self.connected = false; | 109 | + NetworkEvent::SessionLost => { |
| 110 | + self.user = None; | ||
| 111 | + self.chat.reset(); | ||
| 112 | + self.change_page(Route::Login, window, cx); | ||
| 144 | } | 113 | } |
| 145 | - NetworkEvent::MessageReceived(message) => self.chat.merge_messages(vec![message]), | 114 | + NetworkEvent::Pushed(event) => self.chat.apply_event(event), |
| 146 | } | 115 | } |
| 147 | 116 | ||
| 148 | cx.notify(); | 117 | cx.notify(); |
crates/client/src/gui/auth.rsmodified+25 -10
| @@ -11,21 +11,29 @@ use crate::gui::{Route, Yumush, new_input, notify_error}; | |||
| 11 | 11 | ||
| 12 | pub struct Auth { | 12 | pub struct Auth { |
| 13 | username_input: Entity<InputState>, | 13 | username_input: Entity<InputState>, |
| 14 | + password_input: Entity<InputState>, | ||
| 14 | } | 15 | } |
| 15 | 16 | ||
| 16 | impl Auth { | 17 | impl Auth { |
| 17 | pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self { | 18 | pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self { |
| 18 | let username_input = new_input("Username...", window, cx); | 19 | let username_input = new_input("Username...", window, cx); |
| 20 | + let password_input = new_input("Password...", window, cx); | ||
| 21 | + password_input.update(cx, |input, cx| input.set_masked(true, window, cx)); | ||
| 19 | username_input.update(cx, |input, cx| input.focus(window, cx)); | 22 | username_input.update(cx, |input, cx| input.focus(window, cx)); |
| 20 | 23 | ||
| 21 | - cx.subscribe_in(&username_input, window, |this, _, event, window, cx| { | 24 | + for input in [&username_input, &password_input] { |
| 22 | - if matches!(event, InputEvent::PressEnter { .. }) { | 25 | + cx.subscribe_in(input, window, |this, _, event, window, cx| { |
| 23 | - submit(this, window, cx); | 26 | + if matches!(event, InputEvent::PressEnter { .. }) { |
| 24 | - } | 27 | + submit(this, window, cx); |
| 25 | - }) | 28 | + } |
| 26 | - .detach(); | 29 | + }) |
| 30 | + .detach(); | ||
| 31 | + } | ||
| 27 | 32 | ||
| 28 | - Self { username_input } | 33 | + Self { |
| 34 | + username_input, | ||
| 35 | + password_input, | ||
| 36 | + } | ||
| 29 | } | 37 | } |
| 30 | 38 | ||
| 31 | pub fn focus(&self, window: &mut Window, cx: &mut Context<Yumush>) { | 39 | pub fn focus(&self, window: &mut Window, cx: &mut Context<Yumush>) { |
| @@ -36,21 +44,26 @@ impl Auth { | |||
| 36 | 44 | ||
| 37 | fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context<Yumush>) { | 45 | fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context<Yumush>) { |
| 38 | let username = this.auth.username_input.read(cx).text().to_string(); | 46 | let username = this.auth.username_input.read(cx).text().to_string(); |
| 47 | + let password = this.auth.password_input.read(cx).text().to_string(); | ||
| 39 | let route = this.current_route; | 48 | let route = this.current_route; |
| 40 | let network = this.network.clone(); | 49 | let network = this.network.clone(); |
| 41 | 50 | ||
| 42 | cx.spawn_in(window, async move |this, cx| { | 51 | cx.spawn_in(window, async move |this, cx| { |
| 43 | let result = match route { | 52 | let result = match route { |
| 44 | - Route::Register => network.create_user(&username).await, | 53 | + Route::Register => network.register(&username, &password).await, |
| 45 | - _ => network.authenticate(&username).await, | 54 | + _ => network.login(&username, &password).await, |
| 46 | }; | 55 | }; |
| 47 | 56 | ||
| 48 | match result { | 57 | match result { |
| 49 | Ok(user) => { | 58 | Ok(user) => { |
| 50 | let _ = this.update_in(cx, |yumush, window, cx| { | 59 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 60 | + yumush | ||
| 61 | + .auth | ||
| 62 | + .password_input | ||
| 63 | + .update(cx, |input, cx| input.set_value("", window, cx)); | ||
| 51 | yumush.user = Some(user); | 64 | yumush.user = Some(user); |
| 52 | yumush.change_page(Route::Chat, window, cx); | 65 | yumush.change_page(Route::Chat, window, cx); |
| 53 | - yumush.start_polling(window, cx); | 66 | + yumush.load_communities(window, cx); |
| 54 | }); | 67 | }); |
| 55 | } | 68 | } |
| 56 | Err(error) => notify_error(&this, cx, error), | 69 | Err(error) => notify_error(&this, cx, error), |
| @@ -85,6 +98,8 @@ impl Yumush { | |||
| 85 | .w_1_5() | 98 | .w_1_5() |
| 86 | .child("Username") | 99 | .child("Username") |
| 87 | .child(Input::new(&self.auth.username_input)) | 100 | .child(Input::new(&self.auth.username_input)) |
| 101 | + .child("Password") | ||
| 102 | + .child(Input::new(&self.auth.password_input)) | ||
| 88 | .child(action_button) | 103 | .child(action_button) |
| 89 | .child(switch_button) | 104 | .child(switch_button) |
| 90 | } | 105 | } |
crates/client/src/gui/chat.rsmodified+246 -82
| @@ -1,5 +1,6 @@ | |||
| 1 | use common::{ | 1 | use common::{ |
| 2 | - constant::NEWEST_MESSAGE_MARKER, | 2 | + constant::MESSAGE_PAGE_LIMIT, |
| 3 | + event::Event, | ||
| 3 | model::{Community, Message, User}, | 4 | model::{Community, Message, User}, |
| 4 | validate::{validate_community_name, validate_message_body}, | 5 | validate::{validate_community_name, validate_message_body}, |
| 5 | }; | 6 | }; |
| @@ -24,11 +25,28 @@ enum Panel { | |||
| 24 | Join, | 25 | Join, |
| 25 | } | 26 | } |
| 26 | 27 | ||
| 28 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 29 | +enum History { | ||
| 30 | + More, | ||
| 31 | + End, | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +impl History { | ||
| 35 | + fn of_page(length: usize) -> Self { | ||
| 36 | + if length < MESSAGE_PAGE_LIMIT { | ||
| 37 | + History::End | ||
| 38 | + } else { | ||
| 39 | + History::More | ||
| 40 | + } | ||
| 41 | + } | ||
| 42 | +} | ||
| 43 | + | ||
| 27 | pub struct Chat { | 44 | pub struct Chat { |
| 28 | communities: Vec<Community>, | 45 | communities: Vec<Community>, |
| 29 | selected_community_id: Option<String>, | 46 | selected_community_id: Option<String>, |
| 30 | - users: Vec<User>, | 47 | + members: Vec<User>, |
| 31 | messages: Vec<Message>, | 48 | messages: Vec<Message>, |
| 49 | + history: History, | ||
| 32 | panel: Panel, | 50 | panel: Panel, |
| 33 | message_input: Entity<InputState>, | 51 | message_input: Entity<InputState>, |
| 34 | community_name_input: Entity<InputState>, | 52 | community_name_input: Entity<InputState>, |
| @@ -73,8 +91,9 @@ impl Chat { | |||
| 73 | Self { | 91 | Self { |
| 74 | communities: vec![], | 92 | communities: vec![], |
| 75 | selected_community_id: None, | 93 | selected_community_id: None, |
| 76 | - users: vec![], | 94 | + members: vec![], |
| 77 | messages: vec![], | 95 | messages: vec![], |
| 96 | + history: History::End, | ||
| 78 | panel: Panel::None, | 97 | panel: Panel::None, |
| 79 | message_input, | 98 | message_input, |
| 80 | community_name_input, | 99 | community_name_input, |
| @@ -88,10 +107,92 @@ impl Chat { | |||
| 88 | .update(cx, |input, cx| input.focus(window, cx)); | 107 | .update(cx, |input, cx| input.focus(window, cx)); |
| 89 | } | 108 | } |
| 90 | 109 | ||
| 91 | - pub fn merge_messages(&mut self, messages: Vec<Message>) { | 110 | + pub fn apply_event(&mut self, event: Event) { |
| 92 | - self.messages.extend(messages); | 111 | + match event { |
| 112 | + Event::MessageCreated(message) | Event::MessageUpdated(message) => { | ||
| 113 | + if self.is_selected(&message.community_id) { | ||
| 114 | + self.insert_messages([message]); | ||
| 115 | + } | ||
| 116 | + } | ||
| 117 | + Event::MessageDeleted(message) => { | ||
| 118 | + if self.is_selected(&message.community_id) { | ||
| 119 | + self.messages.retain(|existing| existing.id != message.id); | ||
| 120 | + } | ||
| 121 | + } | ||
| 122 | + Event::MemberJoined { community_id, user } => { | ||
| 123 | + if self.is_selected(&community_id) { | ||
| 124 | + self.insert_member(user); | ||
| 125 | + } | ||
| 126 | + } | ||
| 127 | + Event::MemberLeft { | ||
| 128 | + community_id, | ||
| 129 | + user_id, | ||
| 130 | + } => { | ||
| 131 | + if self.is_selected(&community_id) { | ||
| 132 | + self.members.retain(|member| member.id != user_id); | ||
| 133 | + } | ||
| 134 | + } | ||
| 135 | + Event::CommunityUpdated(community) => self.insert_community(community), | ||
| 136 | + Event::CommunityDeleted { community_id } => self.remove_community(&community_id), | ||
| 137 | + } | ||
| 138 | + } | ||
| 139 | + | ||
| 140 | + fn is_selected(&self, community_id: &str) -> bool { | ||
| 141 | + self.selected_community_id.as_deref() == Some(community_id) | ||
| 142 | + } | ||
| 143 | + | ||
| 144 | + fn select(&mut self, community_id: Option<String>) { | ||
| 145 | + self.selected_community_id = community_id; | ||
| 146 | + self.members.clear(); | ||
| 147 | + self.messages.clear(); | ||
| 148 | + self.history = History::End; | ||
| 149 | + } | ||
| 150 | + | ||
| 151 | + fn insert_messages(&mut self, messages: impl IntoIterator<Item = Message>) { | ||
| 152 | + for message in messages { | ||
| 153 | + self.messages.retain(|existing| existing.id != message.id); | ||
| 154 | + self.messages.push(message); | ||
| 155 | + } | ||
| 93 | self.messages.sort_by(|left, right| left.id.cmp(&right.id)); | 156 | self.messages.sort_by(|left, right| left.id.cmp(&right.id)); |
| 94 | - self.messages.dedup_by(|left, right| left.id == right.id); | 157 | + } |
| 158 | + | ||
| 159 | + fn add_page(&mut self, page: Vec<Message>) { | ||
| 160 | + self.history = History::of_page(page.len()); | ||
| 161 | + self.insert_messages(page); | ||
| 162 | + } | ||
| 163 | + | ||
| 164 | + fn insert_member(&mut self, user: User) { | ||
| 165 | + self.members.retain(|member| member.id != user.id); | ||
| 166 | + self.members.push(user); | ||
| 167 | + self.members.sort_by(|left, right| left.id.cmp(&right.id)); | ||
| 168 | + } | ||
| 169 | + | ||
| 170 | + fn insert_community(&mut self, community: Community) { | ||
| 171 | + self.communities | ||
| 172 | + .retain(|existing| existing.id != community.id); | ||
| 173 | + self.communities.push(community); | ||
| 174 | + self.communities | ||
| 175 | + .sort_by(|left, right| left.id.cmp(&right.id)); | ||
| 176 | + } | ||
| 177 | + | ||
| 178 | + fn remove_community(&mut self, community_id: &str) { | ||
| 179 | + self.communities | ||
| 180 | + .retain(|community| community.id != community_id); | ||
| 181 | + if self.is_selected(community_id) { | ||
| 182 | + self.select(None); | ||
| 183 | + } | ||
| 184 | + } | ||
| 185 | + | ||
| 186 | + fn replace_communities(&mut self, communities: Vec<Community>) { | ||
| 187 | + self.communities = communities; | ||
| 188 | + | ||
| 189 | + let selected_present = self | ||
| 190 | + .communities | ||
| 191 | + .iter() | ||
| 192 | + .any(|community| self.is_selected(&community.id)); | ||
| 193 | + if !selected_present { | ||
| 194 | + self.select(None); | ||
| 195 | + } | ||
| 95 | } | 196 | } |
| 96 | 197 | ||
| 97 | fn set_panel(&mut self, panel: Panel) { | 198 | fn set_panel(&mut self, panel: Panel) { |
| @@ -103,9 +204,7 @@ impl Chat { | |||
| 103 | 204 | ||
| 104 | pub fn reset(&mut self) { | 205 | pub fn reset(&mut self) { |
| 105 | self.communities.clear(); | 206 | self.communities.clear(); |
| 106 | - self.selected_community_id = None; | 207 | + self.select(None); |
| 107 | - self.users.clear(); | ||
| 108 | - self.messages.clear(); | ||
| 109 | self.set_panel(Panel::None); | 208 | self.set_panel(Panel::None); |
| 110 | } | 209 | } |
| 111 | } | 210 | } |
| @@ -123,9 +222,6 @@ fn send_message( | |||
| 123 | return; | 222 | return; |
| 124 | } | 223 | } |
| 125 | 224 | ||
| 126 | - let Some(user_id) = this.user.as_ref().map(|user| user.id.clone()) else { | ||
| 127 | - return; | ||
| 128 | - }; | ||
| 129 | let Some(community_id) = this.chat.selected_community_id.clone() else { | 225 | let Some(community_id) = this.chat.selected_community_id.clone() else { |
| 130 | window.push_notification(Notification::error("No Community Selected"), cx); | 226 | window.push_notification(Notification::error("No Community Selected"), cx); |
| 131 | return; | 227 | return; |
| @@ -133,7 +229,7 @@ fn send_message( | |||
| 133 | let network = this.network.clone(); | 229 | let network = this.network.clone(); |
| 134 | 230 | ||
| 135 | cx.spawn_in(window, async move |this, cx| { | 231 | cx.spawn_in(window, async move |this, cx| { |
| 136 | - if let Err(error) = network.create_message(&user_id, &community_id, &body).await { | 232 | + if let Err(error) = network.create_message(&community_id, &body).await { |
| 137 | notify_error(&this, cx, error); | 233 | notify_error(&this, cx, error); |
| 138 | } | 234 | } |
| 139 | }) | 235 | }) |
| @@ -157,7 +253,6 @@ fn create_community( | |||
| 157 | 253 | ||
| 158 | let network = this.network.clone(); | 254 | let network = this.network.clone(); |
| 159 | input.update(cx, |state, cx| state.set_value("", window, cx)); | 255 | input.update(cx, |state, cx| state.set_value("", window, cx)); |
| 160 | - this.chat.set_panel(Panel::None); | ||
| 161 | 256 | ||
| 162 | cx.spawn_in(window, async move |this, cx| { | 257 | cx.spawn_in(window, async move |this, cx| { |
| 163 | let community = match network.create_community(&name).await { | 258 | let community = match network.create_community(&name).await { |
| @@ -169,8 +264,7 @@ fn create_community( | |||
| 169 | }; | 264 | }; |
| 170 | 265 | ||
| 171 | let _ = this.update_in(cx, |yumush, window, cx| { | 266 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 172 | - yumush.get_communities(window, cx); | 267 | + yumush.enter_community(community, window, cx); |
| 173 | - yumush.select_community(community.id, window, cx); | ||
| 174 | }); | 268 | }); |
| 175 | }) | 269 | }) |
| 176 | .detach(); | 270 | .detach(); |
| @@ -223,7 +317,7 @@ impl Yumush { | |||
| 223 | .flex_col() | 317 | .flex_col() |
| 224 | .flex_1() | 318 | .flex_1() |
| 225 | .min_w_0() | 319 | .min_w_0() |
| 226 | - .child(self.message_list()) | 320 | + .child(self.message_list(&entity)) |
| 227 | .child( | 321 | .child( |
| 228 | div() | 322 | div() |
| 229 | .p_2() | 323 | .p_2() |
| @@ -232,7 +326,7 @@ impl Yumush { | |||
| 232 | .child(Input::new(&self.chat.message_input)), | 326 | .child(Input::new(&self.chat.message_input)), |
| 233 | ), | 327 | ), |
| 234 | ) | 328 | ) |
| 235 | - .child(self.user_list()) | 329 | + .child(self.member_list(&entity)) |
| 236 | } | 330 | } |
| 237 | 331 | ||
| 238 | fn community_list(&self, entity: &Entity<Self>) -> impl IntoElement { | 332 | fn community_list(&self, entity: &Entity<Self>) -> impl IntoElement { |
| @@ -318,8 +412,7 @@ impl Yumush { | |||
| 318 | .enumerate() | 412 | .enumerate() |
| 319 | .map(|(index, community)| { | 413 | .map(|(index, community)| { |
| 320 | let community_id = community.id.clone(); | 414 | let community_id = community.id.clone(); |
| 321 | - let selected = self.chat.selected_community_id.as_deref() | 415 | + let selected = self.chat.is_selected(&community.id); |
| 322 | - == Some(community.id.as_str()); | ||
| 323 | let entity = entity.clone(); | 416 | let entity = entity.clone(); |
| 324 | 417 | ||
| 325 | div() | 418 | div() |
| @@ -341,7 +434,7 @@ impl Yumush { | |||
| 341 | ) | 434 | ) |
| 342 | } | 435 | } |
| 343 | 436 | ||
| 344 | - fn message_list(&self) -> impl IntoElement { | 437 | + fn message_list(&self, entity: &Entity<Self>) -> impl IntoElement { |
| 345 | div() | 438 | div() |
| 346 | .id("chat_messages") | 439 | .id("chat_messages") |
| 347 | .flex() | 440 | .flex() |
| @@ -351,20 +444,18 @@ impl Yumush { | |||
| 351 | .overflow_y_scroll() | 444 | .overflow_y_scroll() |
| 352 | .p_2() | 445 | .p_2() |
| 353 | .gap_1() | 446 | .gap_1() |
| 447 | + .children((self.chat.history == History::More).then(|| older_button(entity))) | ||
| 354 | .children( | 448 | .children( |
| 355 | self.chat | 449 | self.chat |
| 356 | .messages | 450 | .messages |
| 357 | .iter() | 451 | .iter() |
| 358 | - .filter(|message| { | 452 | + .map(|message| render_message(message, &self.chat.members)), |
| 359 | - Some(&message.community_id) == self.chat.selected_community_id.as_ref() | ||
| 360 | - }) | ||
| 361 | - .map(|message| render_message(message, &self.chat.users)), | ||
| 362 | ) | 453 | ) |
| 363 | } | 454 | } |
| 364 | 455 | ||
| 365 | - fn user_list(&self) -> impl IntoElement { | 456 | + fn member_list(&self, entity: &Entity<Self>) -> impl IntoElement { |
| 366 | div() | 457 | div() |
| 367 | - .id("user_list") | 458 | + .id("member_list") |
| 368 | .h_full() | 459 | .h_full() |
| 369 | .flex() | 460 | .flex() |
| 370 | .flex_col() | 461 | .flex_col() |
| @@ -377,13 +468,26 @@ impl Yumush { | |||
| 377 | .gap_1() | 468 | .gap_1() |
| 378 | .child( | 469 | .child( |
| 379 | div() | 470 | div() |
| 380 | - .text_color(rgb(0x949ba4)) | 471 | + .flex() |
| 381 | - .font_weight(FontWeight::SEMIBOLD) | 472 | + .flex_row() |
| 382 | - .child(format!("Online - {}", self.chat.users.len())), | 473 | + .items_center() |
| 474 | + .justify_between() | ||
| 475 | + .child( | ||
| 476 | + div() | ||
| 477 | + .text_color(rgb(0x949ba4)) | ||
| 478 | + .font_weight(FontWeight::SEMIBOLD) | ||
| 479 | + .child(format!("Members - {}", self.chat.members.len())), | ||
| 480 | + ) | ||
| 481 | + .children( | ||
| 482 | + self.chat | ||
| 483 | + .selected_community_id | ||
| 484 | + .is_some() | ||
| 485 | + .then(|| leave_button(entity)), | ||
| 486 | + ), | ||
| 383 | ) | 487 | ) |
| 384 | .children( | 488 | .children( |
| 385 | self.chat | 489 | self.chat |
| 386 | - .users | 490 | + .members |
| 387 | .iter() | 491 | .iter() |
| 388 | .map(|user| div().p_1().child(user.username.clone())), | 492 | .map(|user| div().p_1().child(user.username.clone())), |
| 389 | ) | 493 | ) |
| @@ -415,55 +519,73 @@ impl Yumush { | |||
| 415 | window: &mut Window, | 519 | window: &mut Window, |
| 416 | cx: &mut Context<Self>, | 520 | cx: &mut Context<Self>, |
| 417 | ) { | 521 | ) { |
| 418 | - self.chat.selected_community_id = Some(community_id); | 522 | + self.chat.select(Some(community_id)); |
| 419 | - self.chat.users.clear(); | 523 | + self.load_members(window, cx); |
| 420 | - self.get_chat_users(window, cx); | 524 | + self.load_latest_messages(window, cx); |
| 421 | - self.get_chat_messages(window, cx); | ||
| 422 | cx.notify(); | 525 | cx.notify(); |
| 423 | } | 526 | } |
| 424 | 527 | ||
| 425 | - pub(super) fn get_chat_users(&self, window: &mut Window, cx: &mut Context<Self>) { | 528 | + fn enter_community( |
| 426 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 529 | + &mut self, |
| 427 | - return; | 530 | + community: Community, |
| 428 | - }; | 531 | + window: &mut Window, |
| 532 | + cx: &mut Context<Self>, | ||
| 533 | + ) { | ||
| 534 | + self.chat.set_panel(Panel::None); | ||
| 535 | + let community_id = community.id.clone(); | ||
| 536 | + self.chat.insert_community(community); | ||
| 537 | + self.select_community(community_id, window, cx); | ||
| 538 | + } | ||
| 539 | + | ||
| 540 | + pub(super) fn reload(&self, window: &mut Window, cx: &mut Context<Self>) { | ||
| 541 | + self.load_communities(window, cx); | ||
| 542 | + | ||
| 543 | + if self.chat.selected_community_id.is_some() { | ||
| 544 | + self.load_members(window, cx); | ||
| 545 | + self.load_latest_messages(window, cx); | ||
| 546 | + } | ||
| 547 | + } | ||
| 548 | + | ||
| 549 | + pub(super) fn load_communities(&self, window: &mut Window, cx: &mut Context<Self>) { | ||
| 429 | let network = self.network.clone(); | 550 | let network = self.network.clone(); |
| 430 | 551 | ||
| 431 | cx.spawn_in(window, async move |this, cx| { | 552 | cx.spawn_in(window, async move |this, cx| { |
| 432 | - let user_ids = match network.users_in(&community_id).await { | 553 | + let communities = match network.communities().await { |
| 433 | - Ok(user_ids) => user_ids, | 554 | + Ok(communities) => communities, |
| 434 | Err(error) => { | 555 | Err(error) => { |
| 435 | notify_error(&this, cx, error); | 556 | notify_error(&this, cx, error); |
| 436 | return; | 557 | return; |
| 437 | } | 558 | } |
| 438 | }; | 559 | }; |
| 439 | 560 | ||
| 440 | - let mut users = Vec::with_capacity(user_ids.len()); | 561 | + let _ = this.update_in(cx, |yumush, window, cx| { |
| 441 | - for user_id in &user_ids { | 562 | + yumush.chat.replace_communities(communities); |
| 442 | - if let Ok(user) = network.read_user(user_id).await { | ||
| 443 | - users.push(user); | ||
| 444 | - } | ||
| 445 | - } | ||
| 446 | 563 | ||
| 447 | - let _ = this.update(cx, |yumush, cx| { | 564 | + if yumush.chat.selected_community_id.is_none() { |
| 448 | - yumush.chat.users = users; | 565 | + let first = yumush |
| 566 | + .chat | ||
| 567 | + .communities | ||
| 568 | + .first() | ||
| 569 | + .map(|community| community.id.clone()); | ||
| 570 | + if let Some(community_id) = first { | ||
| 571 | + yumush.select_community(community_id, window, cx); | ||
| 572 | + } | ||
| 573 | + } | ||
| 449 | cx.notify(); | 574 | cx.notify(); |
| 450 | }); | 575 | }); |
| 451 | }) | 576 | }) |
| 452 | .detach(); | 577 | .detach(); |
| 453 | } | 578 | } |
| 454 | 579 | ||
| 455 | - pub(super) fn get_chat_messages(&self, window: &mut Window, cx: &mut Context<Self>) { | 580 | + fn load_members(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 456 | let Some(community_id) = self.chat.selected_community_id.clone() else { | 581 | let Some(community_id) = self.chat.selected_community_id.clone() else { |
| 457 | return; | 582 | return; |
| 458 | }; | 583 | }; |
| 459 | let network = self.network.clone(); | 584 | let network = self.network.clone(); |
| 460 | 585 | ||
| 461 | cx.spawn_in(window, async move |this, cx| { | 586 | cx.spawn_in(window, async move |this, cx| { |
| 462 | - let messages = match network | 587 | + let members = match network.members(&community_id).await { |
| 463 | - .read_messages(&community_id, NEWEST_MESSAGE_MARKER) | 588 | + Ok(members) => members, |
| 464 | - .await | ||
| 465 | - { | ||
| 466 | - Ok(messages) => messages, | ||
| 467 | Err(error) => { | 589 | Err(error) => { |
| 468 | notify_error(&this, cx, error); | 590 | notify_error(&this, cx, error); |
| 469 | return; | 591 | return; |
| @@ -471,64 +593,86 @@ impl Yumush { | |||
| 471 | }; | 593 | }; |
| 472 | 594 | ||
| 473 | let _ = this.update(cx, |yumush, cx| { | 595 | let _ = this.update(cx, |yumush, cx| { |
| 474 | - yumush.chat.merge_messages(messages); | 596 | + if yumush.chat.is_selected(&community_id) { |
| 475 | - cx.notify(); | 597 | + yumush.chat.members = members; |
| 598 | + cx.notify(); | ||
| 599 | + } | ||
| 476 | }); | 600 | }); |
| 477 | }) | 601 | }) |
| 478 | .detach(); | 602 | .detach(); |
| 479 | } | 603 | } |
| 480 | 604 | ||
| 481 | - pub(super) fn get_communities(&self, window: &mut Window, cx: &mut Context<Self>) { | 605 | + fn load_latest_messages(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 482 | - let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { | 606 | + self.load_messages(None, window, cx); |
| 607 | + } | ||
| 608 | + | ||
| 609 | + fn load_older_messages(&self, window: &mut Window, cx: &mut Context<Self>) { | ||
| 610 | + let Some(oldest_id) = self.chat.messages.first().map(|message| message.id.clone()) else { | ||
| 611 | + return; | ||
| 612 | + }; | ||
| 613 | + self.load_messages(Some(oldest_id), window, cx); | ||
| 614 | + } | ||
| 615 | + | ||
| 616 | + fn load_messages(&self, before: Option<String>, window: &mut Window, cx: &mut Context<Self>) { | ||
| 617 | + let Some(community_id) = self.chat.selected_community_id.clone() else { | ||
| 483 | return; | 618 | return; |
| 484 | }; | 619 | }; |
| 485 | let network = self.network.clone(); | 620 | let network = self.network.clone(); |
| 486 | 621 | ||
| 487 | cx.spawn_in(window, async move |this, cx| { | 622 | cx.spawn_in(window, async move |this, cx| { |
| 488 | - let community_ids = match network.communities_of(&user_id).await { | 623 | + let page = match network |
| 489 | - Ok(community_ids) => community_ids, | 624 | + .read_messages(&community_id, before.as_deref()) |
| 625 | + .await | ||
| 626 | + { | ||
| 627 | + Ok(page) => page, | ||
| 490 | Err(error) => { | 628 | Err(error) => { |
| 491 | notify_error(&this, cx, error); | 629 | notify_error(&this, cx, error); |
| 492 | return; | 630 | return; |
| 493 | } | 631 | } |
| 494 | }; | 632 | }; |
| 495 | 633 | ||
| 496 | - let mut communities = Vec::with_capacity(community_ids.len()); | ||
| 497 | - for community_id in community_ids { | ||
| 498 | - if let Ok(community) = network.read_community(&community_id).await { | ||
| 499 | - communities.push(community); | ||
| 500 | - } | ||
| 501 | - } | ||
| 502 | - | ||
| 503 | let _ = this.update(cx, |yumush, cx| { | 634 | let _ = this.update(cx, |yumush, cx| { |
| 504 | - if yumush.chat.selected_community_id.is_none() { | 635 | + if yumush.chat.is_selected(&community_id) { |
| 505 | - yumush.chat.selected_community_id = | 636 | + yumush.chat.add_page(page); |
| 506 | - communities.first().map(|community| community.id.clone()); | 637 | + cx.notify(); |
| 507 | } | 638 | } |
| 508 | - yumush.chat.communities = communities; | ||
| 509 | - cx.notify(); | ||
| 510 | }); | 639 | }); |
| 511 | }) | 640 | }) |
| 512 | .detach(); | 641 | .detach(); |
| 513 | } | 642 | } |
| 514 | 643 | ||
| 515 | fn join_community(&self, community_id: &str, window: &mut Window, cx: &mut Context<Self>) { | 644 | fn join_community(&self, community_id: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 516 | - let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { | 645 | + let network = self.network.clone(); |
| 646 | + let community_id = community_id.to_string(); | ||
| 647 | + | ||
| 648 | + cx.spawn_in(window, async move |this, cx| { | ||
| 649 | + match network.join_community(&community_id).await { | ||
| 650 | + Ok(community) => { | ||
| 651 | + let _ = this.update_in(cx, |yumush, window, cx| { | ||
| 652 | + yumush.enter_community(community, window, cx); | ||
| 653 | + }); | ||
| 654 | + } | ||
| 655 | + Err(error) => notify_error(&this, cx, error), | ||
| 656 | + } | ||
| 657 | + }) | ||
| 658 | + .detach(); | ||
| 659 | + } | ||
| 660 | + | ||
| 661 | + fn leave_community(&self, window: &mut Window, cx: &mut Context<Self>) { | ||
| 662 | + let Some(community_id) = self.chat.selected_community_id.clone() else { | ||
| 517 | return; | 663 | return; |
| 518 | }; | 664 | }; |
| 519 | let network = self.network.clone(); | 665 | let network = self.network.clone(); |
| 520 | - let community_id = community_id.to_string(); | ||
| 521 | 666 | ||
| 522 | cx.spawn_in(window, async move |this, cx| { | 667 | cx.spawn_in(window, async move |this, cx| { |
| 523 | - if let Err(error) = network.join_community(&user_id, &community_id).await { | 668 | + if let Err(error) = network.leave_community(&community_id).await { |
| 524 | notify_error(&this, cx, error); | 669 | notify_error(&this, cx, error); |
| 525 | return; | 670 | return; |
| 526 | } | 671 | } |
| 527 | 672 | ||
| 528 | - let _ = this.update_in(cx, |yumush, window, cx| { | 673 | + let _ = this.update(cx, |yumush, cx| { |
| 529 | - yumush.chat.set_panel(Panel::None); | 674 | + yumush.chat.remove_community(&community_id); |
| 530 | - yumush.get_communities(window, cx); | 675 | + cx.notify(); |
| 531 | - yumush.select_community(community_id, window, cx); | ||
| 532 | }); | 676 | }); |
| 533 | }) | 677 | }) |
| 534 | .detach(); | 678 | .detach(); |
| @@ -548,8 +692,28 @@ fn panel_button( | |||
| 548 | }) | 692 | }) |
| 549 | } | 693 | } |
| 550 | 694 | ||
| 551 | -fn render_message(message: &Message, users: &[User]) -> impl IntoElement { | 695 | +fn leave_button(entity: &Entity<Yumush>) -> impl IntoElement { |
| 552 | - let username = users | 696 | + let entity = entity.clone(); |
| 697 | + | ||
| 698 | + Button::new("leave_community_button") | ||
| 699 | + .label("Leave") | ||
| 700 | + .on_click(move |_, window, cx| { | ||
| 701 | + entity.update(cx, |yumush, cx| yumush.leave_community(window, cx)); | ||
| 702 | + }) | ||
| 703 | +} | ||
| 704 | + | ||
| 705 | +fn older_button(entity: &Entity<Yumush>) -> impl IntoElement { | ||
| 706 | + let entity = entity.clone(); | ||
| 707 | + | ||
| 708 | + Button::new("load_older_button") | ||
| 709 | + .label("↑") | ||
| 710 | + .on_click(move |_, window, cx| { | ||
| 711 | + entity.update(cx, |yumush, cx| yumush.load_older_messages(window, cx)); | ||
| 712 | + }) | ||
| 713 | +} | ||
| 714 | + | ||
| 715 | +fn render_message(message: &Message, members: &[User]) -> impl IntoElement { | ||
| 716 | + let username = members | ||
| 553 | .iter() | 717 | .iter() |
| 554 | .find(|user| user.id == message.user_id) | 718 | .find(|user| user.id == message.user_id) |
| 555 | .map(|user| user.username.as_str()) | 719 | .map(|user| user.username.as_str()) |
crates/client/src/lib.rsmodified+8 -6
| @@ -1,4 +1,4 @@ | |||
| 1 | -use common::config::parse; | 1 | +use common::config::Config; |
| 2 | 2 | ||
| 3 | pub mod gui; | 3 | pub mod gui; |
| 4 | pub mod network; | 4 | pub mod network; |
| @@ -11,17 +11,19 @@ const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!( | |||
| 11 | )); | 11 | )); |
| 12 | 12 | ||
| 13 | pub struct ClientConfig { | 13 | pub struct ClientConfig { |
| 14 | - server_address: String, | 14 | + pub server_address: String, |
| 15 | - server_name: String, | 15 | + pub server_name: String, |
| 16 | + pub server_fingerprint: String, | ||
| 16 | } | 17 | } |
| 17 | 18 | ||
| 18 | impl Default for ClientConfig { | 19 | impl Default for ClientConfig { |
| 19 | fn default() -> Self { | 20 | fn default() -> Self { |
| 20 | - let fields = parse(CLIENT_CONFIG_FILE_CONTENT).expect("client config"); | 21 | + let config = Config::parse(CLIENT_CONFIG_FILE_CONTENT).expect("client config"); |
| 21 | 22 | ||
| 22 | Self { | 23 | Self { |
| 23 | - server_address: fields["server_address"].clone(), | 24 | + server_address: config.get("server_address").expect("server_address"), |
| 24 | - server_name: fields["server_name"].clone(), | 25 | + server_name: config.get("server_name").expect("server_name"), |
| 26 | + server_fingerprint: config.get("server_fingerprint").expect("server_fingerprint"), | ||
| 25 | } | 27 | } |
| 26 | } | 28 | } |
| 27 | } | 29 | } |
crates/client/src/main.rsmodified+2 -0
| @@ -5,6 +5,8 @@ use gpui_kit::{ | |||
| 5 | }; | 5 | }; |
| 6 | 6 | ||
| 7 | fn main() { | 7 | fn main() { |
| 8 | + tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init(); | ||
| 9 | + | ||
| 8 | let (network_handle, network_event_receiver) = network::start(ClientConfig::default()); | 10 | let (network_handle, network_event_receiver) = network::start(ClientConfig::default()); |
| 9 | 11 | ||
| 10 | application().run(|cx: &mut App| { | 12 | application().run(|cx: &mut App| { |
crates/client/src/network.rsmodified+134 -128
| @@ -2,13 +2,15 @@ use std::sync::Arc; | |||
| 2 | use std::time::Duration; | 2 | use std::time::Duration; |
| 3 | 3 | ||
| 4 | use common::{ | 4 | use common::{ |
| 5 | - constant::MESSAGE_PAGE_LIMIT, | ||
| 6 | error::Error, | 5 | error::Error, |
| 6 | + event::Event, | ||
| 7 | model::{Community, Message, User}, | 7 | model::{Community, Message, User}, |
| 8 | - network::{receive_message, send_request}, | 8 | + network::{receive_event, send_request}, |
| 9 | request::Request, | 9 | request::Request, |
| 10 | response::Response, | 10 | response::Response, |
| 11 | - validate::{validate_community_name, validate_message_body, validate_username}, | 11 | + validate::{ |
| 12 | + validate_community_name, validate_message_body, validate_password, validate_username, | ||
| 13 | + }, | ||
| 12 | }; | 14 | }; |
| 13 | use quinn::{ | 15 | use quinn::{ |
| 14 | Endpoint, | 16 | Endpoint, |
| @@ -19,6 +21,7 @@ use quinn::{ | |||
| 19 | }, | 21 | }, |
| 20 | }; | 22 | }; |
| 21 | use tokio::sync::{mpsc, oneshot}; | 23 | use tokio::sync::{mpsc, oneshot}; |
| 24 | +use tracing::{info, warn}; | ||
| 22 | 25 | ||
| 23 | use crate::ClientConfig; | 26 | use crate::ClientConfig; |
| 24 | 27 | ||
| @@ -30,10 +33,10 @@ const RECONNECT_DELAY: Duration = Duration::from_secs(1); | |||
| 30 | 33 | ||
| 31 | #[derive(Debug)] | 34 | #[derive(Debug)] |
| 32 | pub enum NetworkEvent { | 35 | pub enum NetworkEvent { |
| 33 | - Connected(Option<User>), | 36 | + Connected, |
| 34 | - ConnectionFailed(Error), | ||
| 35 | Disconnected(Error), | 37 | Disconnected(Error), |
| 36 | - MessageReceived(Message), | 38 | + SessionLost, |
| 39 | + Pushed(Event), | ||
| 37 | } | 40 | } |
| 38 | 41 | ||
| 39 | #[derive(Debug)] | 42 | #[derive(Debug)] |
| @@ -62,40 +65,38 @@ impl NetworkHandle { | |||
| 62 | } | 65 | } |
| 63 | } | 66 | } |
| 64 | 67 | ||
| 65 | - pub async fn authenticate(&self, token: &str) -> Result<User, Error> { | 68 | + async fn sign_in(&self, request: Request) -> Result<User, Error> { |
| 66 | - match self | 69 | + match self.request(request).await? { |
| 67 | - .request(Request::Authentication { | 70 | + Response::Session { user, .. } => Ok(user), |
| 68 | - token: token.to_string(), | ||
| 69 | - }) | ||
| 70 | - .await? | ||
| 71 | - { | ||
| 72 | - Response::Authentication(user) => Ok(user), | ||
| 73 | _ => Err(Error::Server), | 71 | _ => Err(Error::Server), |
| 74 | } | 72 | } |
| 75 | } | 73 | } |
| 76 | 74 | ||
| 77 | - pub async fn deauthenticate(&self, token: &str) -> Result<User, Error> { | 75 | + pub async fn register(&self, username: &str, password: &str) -> Result<User, Error> { |
| 78 | - match self | 76 | + validate_username(username)?; |
| 79 | - .request(Request::Deauthentication { | 77 | + validate_password(password)?; |
| 80 | - token: token.to_string(), | 78 | + |
| 81 | - }) | 79 | + self.sign_in(Request::Register { |
| 82 | - .await? | 80 | + username: username.to_string(), |
| 83 | - { | 81 | + password: password.to_string(), |
| 84 | - Response::Deauthentication(user) => Ok(user), | 82 | + }) |
| 85 | - _ => Err(Error::Server), | 83 | + .await |
| 86 | - } | ||
| 87 | } | 84 | } |
| 88 | 85 | ||
| 89 | - pub async fn create_user(&self, username: &str) -> Result<User, Error> { | 86 | + pub async fn login(&self, username: &str, password: &str) -> Result<User, Error> { |
| 90 | validate_username(username)?; | 87 | validate_username(username)?; |
| 88 | + validate_password(password)?; | ||
| 91 | 89 | ||
| 92 | - match self | 90 | + self.sign_in(Request::Login { |
| 93 | - .request(Request::CreateUser { | 91 | + username: username.to_string(), |
| 94 | - username: username.to_string(), | 92 | + password: password.to_string(), |
| 95 | - }) | 93 | + }) |
| 96 | - .await? | 94 | + .await |
| 97 | - { | 95 | + } |
| 98 | - Response::CreateUser(user) => Ok(user), | 96 | + |
| 97 | + pub async fn logout(&self) -> Result<(), Error> { | ||
| 98 | + match self.request(Request::Logout).await? { | ||
| 99 | + Response::Done => Ok(()), | ||
| 99 | _ => Err(Error::Server), | 100 | _ => Err(Error::Server), |
| 100 | } | 101 | } |
| 101 | } | 102 | } |
| @@ -107,7 +108,7 @@ impl NetworkHandle { | |||
| 107 | }) | 108 | }) |
| 108 | .await? | 109 | .await? |
| 109 | { | 110 | { |
| 110 | - Response::ReadUser(user) => Ok(user), | 111 | + Response::User(user) => Ok(user), |
| 111 | _ => Err(Error::Server), | 112 | _ => Err(Error::Server), |
| 112 | } | 113 | } |
| 113 | } | 114 | } |
| @@ -121,109 +122,96 @@ impl NetworkHandle { | |||
| 121 | }) | 122 | }) |
| 122 | .await? | 123 | .await? |
| 123 | { | 124 | { |
| 124 | - Response::CreateCommunity(community) => Ok(community), | 125 | + Response::Community(community) => Ok(community), |
| 125 | _ => Err(Error::Server), | 126 | _ => Err(Error::Server), |
| 126 | } | 127 | } |
| 127 | } | 128 | } |
| 128 | 129 | ||
| 129 | - pub async fn read_community(&self, community_id: &str) -> Result<Community, Error> { | 130 | + pub async fn join_community(&self, community_id: &str) -> Result<Community, Error> { |
| 130 | match self | 131 | match self |
| 131 | - .request(Request::ReadCommunity { | 132 | + .request(Request::JoinCommunity { |
| 132 | community_id: community_id.to_string(), | 133 | community_id: community_id.to_string(), |
| 133 | }) | 134 | }) |
| 134 | .await? | 135 | .await? |
| 135 | { | 136 | { |
| 136 | - Response::ReadCommunity(community) => Ok(community), | 137 | + Response::Community(community) => Ok(community), |
| 137 | _ => Err(Error::Server), | 138 | _ => Err(Error::Server), |
| 138 | } | 139 | } |
| 139 | } | 140 | } |
| 140 | 141 | ||
| 141 | - pub async fn create_message( | 142 | + pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> { |
| 142 | - &self, | ||
| 143 | - user_id: &str, | ||
| 144 | - community_id: &str, | ||
| 145 | - body: &str, | ||
| 146 | - ) -> Result<Message, Error> { | ||
| 147 | - validate_message_body(body)?; | ||
| 148 | - | ||
| 149 | match self | 143 | match self |
| 150 | - .request(Request::CreateMessage { | 144 | + .request(Request::LeaveCommunity { |
| 151 | - user_id: user_id.to_string(), | ||
| 152 | community_id: community_id.to_string(), | 145 | community_id: community_id.to_string(), |
| 153 | - body: body.to_string(), | ||
| 154 | }) | 146 | }) |
| 155 | .await? | 147 | .await? |
| 156 | { | 148 | { |
| 157 | - Response::CreateMessage(message) => Ok(message), | 149 | + Response::Done => Ok(()), |
| 158 | _ => Err(Error::Server), | 150 | _ => Err(Error::Server), |
| 159 | } | 151 | } |
| 160 | } | 152 | } |
| 161 | 153 | ||
| 162 | - pub async fn read_messages( | 154 | + pub async fn search_community(&self, name: &str) -> Result<Vec<Community>, Error> { |
| 163 | - &self, | 155 | + validate_community_name(name)?; |
| 164 | - community_id: &str, | 156 | + |
| 165 | - marker: &str, | ||
| 166 | - ) -> Result<Vec<Message>, Error> { | ||
| 167 | match self | 157 | match self |
| 168 | - .request(Request::ReadMessages { | 158 | + .request(Request::SearchCommunity { |
| 169 | - community_id: community_id.to_string(), | 159 | + name: name.to_string(), |
| 170 | - marker: marker.to_string(), | ||
| 171 | - limit: MESSAGE_PAGE_LIMIT, | ||
| 172 | }) | 160 | }) |
| 173 | .await? | 161 | .await? |
| 174 | { | 162 | { |
| 175 | - Response::ReadMessages(messages) => Ok(messages), | 163 | + Response::Communities(communities) => Ok(communities), |
| 176 | _ => Err(Error::Server), | 164 | _ => Err(Error::Server), |
| 177 | } | 165 | } |
| 178 | } | 166 | } |
| 179 | 167 | ||
| 180 | - pub async fn join_community(&self, user_id: &str, community_id: &str) -> Result<(), Error> { | 168 | + pub async fn communities(&self) -> Result<Vec<Community>, Error> { |
| 181 | - match self | 169 | + match self.request(Request::Communities).await? { |
| 182 | - .request(Request::JoinCommunity { | 170 | + Response::Communities(communities) => Ok(communities), |
| 183 | - user_id: user_id.to_string(), | ||
| 184 | - community_id: community_id.to_string(), | ||
| 185 | - }) | ||
| 186 | - .await? | ||
| 187 | - { | ||
| 188 | - Response::JoinCommunity => Ok(()), | ||
| 189 | _ => Err(Error::Server), | 171 | _ => Err(Error::Server), |
| 190 | } | 172 | } |
| 191 | } | 173 | } |
| 192 | 174 | ||
| 193 | - pub async fn users_in(&self, community_id: &str) -> Result<Vec<String>, Error> { | 175 | + pub async fn members(&self, community_id: &str) -> Result<Vec<User>, Error> { |
| 194 | match self | 176 | match self |
| 195 | - .request(Request::UsersIn { | 177 | + .request(Request::Members { |
| 196 | community_id: community_id.to_string(), | 178 | community_id: community_id.to_string(), |
| 197 | }) | 179 | }) |
| 198 | .await? | 180 | .await? |
| 199 | { | 181 | { |
| 200 | - Response::UsersIn(user_ids) => Ok(user_ids), | 182 | + Response::Members(users) => Ok(users), |
| 201 | _ => Err(Error::Server), | 183 | _ => Err(Error::Server), |
| 202 | } | 184 | } |
| 203 | } | 185 | } |
| 204 | 186 | ||
| 205 | - pub async fn communities_of(&self, user_id: &str) -> Result<Vec<String>, Error> { | 187 | + pub async fn create_message(&self, community_id: &str, body: &str) -> Result<Message, Error> { |
| 188 | + validate_message_body(body)?; | ||
| 189 | + | ||
| 206 | match self | 190 | match self |
| 207 | - .request(Request::CommunitiesOf { | 191 | + .request(Request::CreateMessage { |
| 208 | - user_id: user_id.to_string(), | 192 | + community_id: community_id.to_string(), |
| 193 | + body: body.to_string(), | ||
| 209 | }) | 194 | }) |
| 210 | .await? | 195 | .await? |
| 211 | { | 196 | { |
| 212 | - Response::CommunitiesOf(community_ids) => Ok(community_ids), | 197 | + Response::Message(message) => Ok(message), |
| 213 | _ => Err(Error::Server), | 198 | _ => Err(Error::Server), |
| 214 | } | 199 | } |
| 215 | } | 200 | } |
| 216 | 201 | ||
| 217 | - pub async fn search_community(&self, name: &str) -> Result<Vec<Community>, Error> { | 202 | + pub async fn read_messages( |
| 218 | - validate_community_name(name)?; | 203 | + &self, |
| 219 | - | 204 | + community_id: &str, |
| 205 | + before: Option<&str>, | ||
| 206 | + ) -> Result<Vec<Message>, Error> { | ||
| 220 | match self | 207 | match self |
| 221 | - .request(Request::SearchCommunity { | 208 | + .request(Request::ReadMessages { |
| 222 | - name: name.to_string(), | 209 | + community_id: community_id.to_string(), |
| 210 | + before: before.map(str::to_string), | ||
| 223 | }) | 211 | }) |
| 224 | .await? | 212 | .await? |
| 225 | { | 213 | { |
| 226 | - Response::SearchCommunity(communities) => Ok(communities), | 214 | + Response::Messages(messages) => Ok(messages), |
| 227 | _ => Err(Error::Server), | 215 | _ => Err(Error::Server), |
| 228 | } | 216 | } |
| 229 | } | 217 | } |
| @@ -247,24 +235,30 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<Netw | |||
| 247 | (NetworkHandle { command_sender }, event_receiver) | 235 | (NetworkHandle { command_sender }, event_receiver) |
| 248 | } | 236 | } |
| 249 | 237 | ||
| 250 | -async fn connect(server_address: &str, server_name: &str) -> Result<quinn::Connection, Error> { | 238 | +async fn connect(client_config: &ClientConfig) -> Result<quinn::Connection, Error> { |
| 251 | let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?; | 239 | let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?; |
| 252 | - endpoint.set_default_client_config(config()); | 240 | + endpoint.set_default_client_config(config(&client_config.server_fingerprint)); |
| 253 | 241 | ||
| 254 | let connection = endpoint | 242 | let connection = endpoint |
| 255 | - .connect(server_address.parse()?, server_name)? | 243 | + .connect( |
| 244 | + client_config.server_address.parse()?, | ||
| 245 | + &client_config.server_name, | ||
| 246 | + )? | ||
| 256 | .await?; | 247 | .await?; |
| 257 | 248 | ||
| 258 | Ok(connection) | 249 | Ok(connection) |
| 259 | } | 250 | } |
| 260 | 251 | ||
| 261 | -fn config() -> quinn::ClientConfig { | 252 | +fn config(fingerprint: &str) -> quinn::ClientConfig { |
| 262 | let crypto_provider = Arc::new(rustls::crypto::ring::default_provider()); | 253 | let crypto_provider = Arc::new(rustls::crypto::ring::default_provider()); |
| 263 | let tls_config = rustls::ClientConfig::builder_with_provider(crypto_provider.clone()) | 254 | let tls_config = rustls::ClientConfig::builder_with_provider(crypto_provider.clone()) |
| 264 | .with_protocol_versions(&[&rustls::version::TLS13]) | 255 | .with_protocol_versions(&[&rustls::version::TLS13]) |
| 265 | .unwrap() | 256 | .unwrap() |
| 266 | .dangerous() | 257 | .dangerous() |
| 267 | - .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate(crypto_provider))) | 258 | + .with_custom_certificate_verifier(Arc::new(PinnedCertificate { |
| 259 | + fingerprint: fingerprint.to_string(), | ||
| 260 | + provider: crypto_provider, | ||
| 261 | + })) | ||
| 268 | .with_no_client_auth(); | 262 | .with_no_client_auth(); |
| 269 | 263 | ||
| 270 | let mut client_config = | 264 | let mut client_config = |
| @@ -297,16 +291,18 @@ async fn actor( | |||
| 297 | mut command_receiver: mpsc::Receiver<Command>, | 291 | mut command_receiver: mpsc::Receiver<Command>, |
| 298 | event_sender: mpsc::Sender<NetworkEvent>, | 292 | event_sender: mpsc::Sender<NetworkEvent>, |
| 299 | ) { | 293 | ) { |
| 300 | - let mut authentication_token: Option<String> = None; | 294 | + let mut token: Option<String> = None; |
| 301 | - let mut authentication_epoch = 0; | 295 | + let mut token_epoch = 0; |
| 302 | let (token_sender, mut token_receiver) = mpsc::channel(CHANNEL_SIZE); | 296 | let (token_sender, mut token_receiver) = mpsc::channel(CHANNEL_SIZE); |
| 303 | 'session: loop { | 297 | 'session: loop { |
| 304 | let connection = loop { | 298 | let connection = loop { |
| 305 | - match connect(&client_config.server_address, &client_config.server_name).await { | 299 | + match connect(&client_config).await { |
| 306 | Ok(connection) => break connection, | 300 | Ok(connection) => break connection, |
| 307 | Err(error) => { | 301 | Err(error) => { |
| 302 | + warn!("connect failed: {error}"); | ||
| 303 | + | ||
| 308 | if event_sender | 304 | if event_sender |
| 309 | - .send(NetworkEvent::ConnectionFailed(error)) | 305 | + .send(NetworkEvent::Disconnected(error)) |
| 310 | .await | 306 | .await |
| 311 | .is_err() | 307 | .is_err() |
| 312 | { | 308 | { |
| @@ -318,52 +314,49 @@ async fn actor( | |||
| 318 | }; | 314 | }; |
| 319 | }; | 315 | }; |
| 320 | 316 | ||
| 321 | - let mut user = None; | 317 | + if let Some(stored) = token.clone() { |
| 322 | - if let Some(token) = &authentication_token { | 318 | + let request = Request::Resume { token: stored }; |
| 323 | - let request = Request::Authentication { | ||
| 324 | - token: token.clone(), | ||
| 325 | - }; | ||
| 326 | match send(&connection, &request).await { | 319 | match send(&connection, &request).await { |
| 327 | - Ok(Response::Authentication(user_)) => user = Some(user_), | 320 | + Ok(Response::Session { token: resumed, .. }) => token = Some(resumed), |
| 328 | - _ => authentication_token = None, | 321 | + _ => { |
| 322 | + warn!("session resume failed"); | ||
| 323 | + token = None; | ||
| 324 | + | ||
| 325 | + if event_sender.send(NetworkEvent::SessionLost).await.is_err() { | ||
| 326 | + return; | ||
| 327 | + } | ||
| 328 | + } | ||
| 329 | } | 329 | } |
| 330 | } | 330 | } |
| 331 | 331 | ||
| 332 | - if event_sender | 332 | + info!("connected"); |
| 333 | - .send(NetworkEvent::Connected(user)) | 333 | + if event_sender.send(NetworkEvent::Connected).await.is_err() { |
| 334 | - .await | ||
| 335 | - .is_err() | ||
| 336 | - { | ||
| 337 | return; | 334 | return; |
| 338 | } | 335 | } |
| 339 | 336 | ||
| 340 | - tokio::spawn(message_receive_loop( | 337 | + tokio::spawn(event_receive_loop(connection.clone(), event_sender.clone())); |
| 341 | - connection.clone(), | ||
| 342 | - event_sender.clone(), | ||
| 343 | - )); | ||
| 344 | 338 | ||
| 345 | loop { | 339 | loop { |
| 346 | tokio::select! { | 340 | tokio::select! { |
| 347 | command = command_receiver.recv() => match command { | 341 | command = command_receiver.recv() => match command { |
| 348 | Some(Command { request, reply }) => match &request { | 342 | Some(Command { request, reply }) => match &request { |
| 349 | - Request::Authentication { token } => { | 343 | + Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => { |
| 350 | - let token = token.clone(); | ||
| 351 | let token_sender = token_sender.clone(); | 344 | let token_sender = token_sender.clone(); |
| 352 | - let epoch = authentication_epoch; | 345 | + let epoch = token_epoch; |
| 353 | let connection = connection.clone(); | 346 | let connection = connection.clone(); |
| 354 | 347 | ||
| 355 | tokio::spawn(async move { | 348 | tokio::spawn(async move { |
| 356 | let response = send(&connection, &request).await; | 349 | let response = send(&connection, &request).await; |
| 357 | - if let Ok(Response::Authentication(_)) = &response { | 350 | + if let Ok(Response::Session { token: session_token, .. }) = &response { |
| 358 | - let _ = token_sender.send((epoch, token)).await; | 351 | + let _ = token_sender.send((epoch, session_token.clone())).await; |
| 359 | } | 352 | } |
| 360 | 353 | ||
| 361 | let _ = reply.send(response); | 354 | let _ = reply.send(response); |
| 362 | }); | 355 | }); |
| 363 | } | 356 | } |
| 364 | - Request::Deauthentication { .. } => { | 357 | + Request::Logout => { |
| 365 | - authentication_token = None; | 358 | + token = None; |
| 366 | - authentication_epoch += 1; | 359 | + token_epoch += 1; |
| 367 | 360 | ||
| 368 | tokio::spawn(dispatch(connection.clone(), request, reply)); | 361 | tokio::spawn(dispatch(connection.clone(), request, reply)); |
| 369 | } | 362 | } |
| @@ -373,13 +366,15 @@ async fn actor( | |||
| 373 | }, | 366 | }, |
| 374 | None => break 'session, | 367 | None => break 'session, |
| 375 | }, | 368 | }, |
| 376 | - Some((epoch, token)) = token_receiver.recv() => { | 369 | + Some((epoch, session_token)) = token_receiver.recv() => { |
| 377 | - if epoch == authentication_epoch { | 370 | + if epoch == token_epoch { |
| 378 | - authentication_token = Some(token); | 371 | + token = Some(session_token); |
| 379 | } | 372 | } |
| 380 | } | 373 | } |
| 381 | 374 | ||
| 382 | error = connection.closed() => { | 375 | error = connection.closed() => { |
| 376 | + warn!("disconnected: {error}"); | ||
| 377 | + | ||
| 383 | if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() { | 378 | if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() { |
| 384 | return; | 379 | return; |
| 385 | } | 380 | } |
| @@ -391,7 +386,7 @@ async fn actor( | |||
| 391 | } | 386 | } |
| 392 | } | 387 | } |
| 393 | 388 | ||
| 394 | -async fn message_receive_loop( | 389 | +async fn event_receive_loop( |
| 395 | connection: quinn::Connection, | 390 | connection: quinn::Connection, |
| 396 | event_sender: mpsc::Sender<NetworkEvent>, | 391 | event_sender: mpsc::Sender<NetworkEvent>, |
| 397 | ) { | 392 | ) { |
| @@ -399,9 +394,9 @@ async fn message_receive_loop( | |||
| 399 | return; | 394 | return; |
| 400 | }; | 395 | }; |
| 401 | 396 | ||
| 402 | - while let Ok(message) = receive_message(&mut receive_stream).await { | 397 | + while let Ok(event) = receive_event(&mut receive_stream).await { |
| 403 | if event_sender | 398 | if event_sender |
| 404 | - .send(NetworkEvent::MessageReceived(message)) | 399 | + .send(NetworkEvent::Pushed(event)) |
| 405 | .await | 400 | .await |
| 406 | .is_err() | 401 | .is_err() |
| 407 | { | 402 | { |
| @@ -411,18 +406,27 @@ async fn message_receive_loop( | |||
| 411 | } | 406 | } |
| 412 | 407 | ||
| 413 | #[derive(Debug)] | 408 | #[derive(Debug)] |
| 414 | -struct AcceptAnyCertificate(Arc<rustls::crypto::CryptoProvider>); | 409 | +struct PinnedCertificate { |
| 410 | + fingerprint: String, | ||
| 411 | + provider: Arc<rustls::crypto::CryptoProvider>, | ||
| 412 | +} | ||
| 415 | 413 | ||
| 416 | -impl ServerCertVerifier for AcceptAnyCertificate { | 414 | +impl ServerCertVerifier for PinnedCertificate { |
| 417 | fn verify_server_cert( | 415 | fn verify_server_cert( |
| 418 | &self, | 416 | &self, |
| 419 | - _end_entity: &rustls::pki_types::CertificateDer<'_>, | 417 | + end_entity: &rustls::pki_types::CertificateDer<'_>, |
| 420 | _intermediates: &[rustls::pki_types::CertificateDer<'_>], | 418 | _intermediates: &[rustls::pki_types::CertificateDer<'_>], |
| 421 | _server_name: &rustls::pki_types::ServerName<'_>, | 419 | _server_name: &rustls::pki_types::ServerName<'_>, |
| 422 | _ocsp_response: &[u8], | 420 | _ocsp_response: &[u8], |
| 423 | _now: rustls::pki_types::UnixTime, | 421 | _now: rustls::pki_types::UnixTime, |
| 424 | - ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> { | 422 | + ) -> Result<ServerCertVerified, rustls::Error> { |
| 425 | - Ok(ServerCertVerified::assertion()) | 423 | + if common::certificate::fingerprint(end_entity) == self.fingerprint { |
| 424 | + Ok(ServerCertVerified::assertion()) | ||
| 425 | + } else { | ||
| 426 | + Err(rustls::Error::General( | ||
| 427 | + "certificate fingerprint mismatch".to_string(), | ||
| 428 | + )) | ||
| 429 | + } | ||
| 426 | } | 430 | } |
| 427 | 431 | ||
| 428 | fn verify_tls12_signature( | 432 | fn verify_tls12_signature( |
| @@ -435,7 +439,7 @@ impl ServerCertVerifier for AcceptAnyCertificate { | |||
| 435 | message, | 439 | message, |
| 436 | cert, | 440 | cert, |
| 437 | dss, | 441 | dss, |
| 438 | - &self.0.signature_verification_algorithms, | 442 | + &self.provider.signature_verification_algorithms, |
| 439 | ) | 443 | ) |
| 440 | } | 444 | } |
| 441 | 445 | ||
| @@ -449,11 +453,13 @@ impl ServerCertVerifier for AcceptAnyCertificate { | |||
| 449 | message, | 453 | message, |
| 450 | cert, | 454 | cert, |
| 451 | dss, | 455 | dss, |
| 452 | - &self.0.signature_verification_algorithms, | 456 | + &self.provider.signature_verification_algorithms, |
| 453 | ) | 457 | ) |
| 454 | } | 458 | } |
| 455 | 459 | ||
| 456 | fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> { | 460 | fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> { |
| 457 | - self.0.signature_verification_algorithms.supported_schemes() | 461 | + self.provider |
| 462 | + .signature_verification_algorithms | ||
| 463 | + .supported_schemes() | ||
| 458 | } | 464 | } |
| 459 | } | 465 | } |
crates/common/Cargo.tomlmodified+2 -0
| @@ -6,6 +6,8 @@ edition = "2024" | |||
| 6 | [dependencies] | 6 | [dependencies] |
| 7 | bitcode.workspace = true | 7 | bitcode.workspace = true |
| 8 | quinn.workspace = true | 8 | quinn.workspace = true |
| 9 | +sha2 = "0.11.1" | ||
| 10 | +thiserror = "2.0.21" | ||
| 9 | 11 | ||
| 10 | [lints] | 12 | [lints] |
| 11 | workspace = true | 13 | workspace = true |
crates/common/src/certificate.rsadded+8 -0
| @@ -0,0 +1,8 @@ | |||
| 1 | +use sha2::{Digest, Sha256}; | ||
| 2 | + | ||
| 3 | +pub fn fingerprint(der: &[u8]) -> String { | ||
| 4 | + Sha256::digest(der) | ||
| 5 | + .iter() | ||
| 6 | + .map(|byte| format!("{byte:02x}")) | ||
| 7 | + .collect() | ||
| 8 | +} | ||
crates/common/src/config.rsmodified+28 -13
| @@ -2,19 +2,34 @@ use std::collections::HashMap; | |||
| 2 | 2 | ||
| 3 | use crate::error::Error; | 3 | use crate::error::Error; |
| 4 | 4 | ||
| 5 | -pub fn parse(content: &str) -> Result<HashMap<String, String>, Error> { | 5 | +pub struct Config(HashMap<String, String>); |
| 6 | - content | 6 | + |
| 7 | - .lines() | 7 | +impl Config { |
| 8 | - .map(str::trim) | 8 | + pub fn parse(content: &str) -> Result<Self, Error> { |
| 9 | - .filter(|line| !line.is_empty() && !line.starts_with('[') && !line.starts_with('#')) | 9 | + let mut fields = HashMap::new(); |
| 10 | - .map(|line| { | 10 | + |
| 11 | + for line in content.lines().map(str::trim) { | ||
| 12 | + if line.is_empty() || line.starts_with('[') || line.starts_with('#') { | ||
| 13 | + continue; | ||
| 14 | + } | ||
| 15 | + | ||
| 11 | let (key, value) = line | 16 | let (key, value) = line |
| 12 | .split_once('=') | 17 | .split_once('=') |
| 13 | - .ok_or_else(|| Error::Config(format!("Invalid line: {line}")))?; | 18 | + .ok_or_else(|| Error::Config(format!("invalid line: {line}")))?; |
| 14 | - Ok(( | 19 | + |
| 15 | - key.replace('"', "").trim().to_string(), | 20 | + fields.insert( |
| 16 | - value.replace('"', "").trim().to_string(), | 21 | + key.trim().to_string(), |
| 17 | - )) | 22 | + value.trim().trim_matches('"').to_string(), |
| 18 | - }) | 23 | + ); |
| 19 | - .collect() | 24 | + } |
| 25 | + | ||
| 26 | + Ok(Self(fields)) | ||
| 27 | + } | ||
| 28 | + | ||
| 29 | + pub fn get(&self, key: &str) -> Result<String, Error> { | ||
| 30 | + self.0 | ||
| 31 | + .get(key) | ||
| 32 | + .cloned() | ||
| 33 | + .ok_or_else(|| Error::Config(format!("missing key: {key}"))) | ||
| 34 | + } | ||
| 20 | } | 35 | } |
crates/common/src/constant.rsmodified+2 -1
| @@ -1,8 +1,9 @@ | |||
| 1 | pub const MAXIMUM_USERNAME_LENGTH: usize = 16; | 1 | pub const MAXIMUM_USERNAME_LENGTH: usize = 16; |
| 2 | pub const MINIMUM_USERNAME_LENGTH: usize = 3; | 2 | pub const MINIMUM_USERNAME_LENGTH: usize = 3; |
| 3 | +pub const MAXIMUM_PASSWORD_LENGTH: usize = 128; | ||
| 4 | +pub const MINIMUM_PASSWORD_LENGTH: usize = 8; | ||
| 3 | pub const MAXIMUM_MESSAGE_LENGTH: usize = 1024; | 5 | pub const MAXIMUM_MESSAGE_LENGTH: usize = 1024; |
| 4 | pub const MINIMUM_MESSAGE_LENGTH: usize = 1; | 6 | pub const MINIMUM_MESSAGE_LENGTH: usize = 1; |
| 5 | pub const MAXIMUM_COMMUNITY_NAME_LENGTH: usize = 16; | 7 | pub const MAXIMUM_COMMUNITY_NAME_LENGTH: usize = 16; |
| 6 | pub const MINIMUM_COMMUNITY_NAME_LENGTH: usize = 3; | 8 | pub const MINIMUM_COMMUNITY_NAME_LENGTH: usize = 3; |
| 7 | pub const MESSAGE_PAGE_LIMIT: usize = 50; | 9 | pub const MESSAGE_PAGE_LIMIT: usize = 50; |
| 8 | -pub const NEWEST_MESSAGE_MARKER: &str = "ZZZZZZZZZZZZZZZZZZZZZZZZZZ"; | ||
crates/common/src/error.rsmodified+24 -23
| @@ -62,39 +62,40 @@ impl Display for InvalidInput { | |||
| 62 | } | 62 | } |
| 63 | } | 63 | } |
| 64 | 64 | ||
| 65 | -#[derive(Debug, Clone, Encode, Decode)] | 65 | +#[derive(Debug, Clone, Encode, Decode, thiserror::Error)] |
| 66 | pub enum Error { | 66 | pub enum Error { |
| 67 | - Authenticate, | 67 | + #[error("unauthenticated")] |
| 68 | + Unauthenticated, | ||
| 69 | + #[error("forbidden")] | ||
| 70 | + Forbidden, | ||
| 71 | + #[error("not found")] | ||
| 72 | + NotFound, | ||
| 73 | + #[error("already taken")] | ||
| 74 | + Taken, | ||
| 75 | + #[error("wrong credentials")] | ||
| 76 | + WrongCredentials, | ||
| 77 | + #[error("server error")] | ||
| 68 | Server, | 78 | Server, |
| 79 | + #[error("channel closed")] | ||
| 69 | ChannelClosed, | 80 | ChannelClosed, |
| 81 | + #[error("config: {0}")] | ||
| 70 | Config(String), | 82 | Config(String), |
| 83 | + #[error("network: {0}")] | ||
| 71 | Network(String), | 84 | Network(String), |
| 85 | + #[error("decode: {0}")] | ||
| 72 | Decode(String), | 86 | Decode(String), |
| 87 | + #[error("read bound exceeded ({actual} > {maximum})")] | ||
| 73 | ReadBoundExceed { actual: usize, maximum: usize }, | 88 | ReadBoundExceed { actual: usize, maximum: usize }, |
| 89 | + #[error("username: {0}")] | ||
| 74 | User(InvalidInput), | 90 | User(InvalidInput), |
| 91 | + #[error("password: {0}")] | ||
| 92 | + Password(InvalidInput), | ||
| 93 | + #[error("community name: {0}")] | ||
| 75 | Community(InvalidInput), | 94 | Community(InvalidInput), |
| 95 | + #[error("message: {0}")] | ||
| 76 | Message(InvalidInput), | 96 | Message(InvalidInput), |
| 77 | -} | 97 | + #[error("certificate: {0}")] |
| 78 | - | 98 | + Certificate(String), |
| 79 | -impl std::error::Error for Error {} | ||
| 80 | - | ||
| 81 | -impl Display for Error { | ||
| 82 | - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 83 | - match self { | ||
| 84 | - Error::Authenticate => write!(f, "Authenticate"), | ||
| 85 | - Error::Server => write!(f, "Server"), | ||
| 86 | - Error::ChannelClosed => write!(f, "Channel closed"), | ||
| 87 | - Error::Config(message) => write!(f, "Config: {message}"), | ||
| 88 | - Error::Network(message) => write!(f, "Network: {message}"), | ||
| 89 | - Error::Decode(message) => write!(f, "Decode: {message}"), | ||
| 90 | - Error::ReadBoundExceed { actual, maximum } => { | ||
| 91 | - write!(f, "Read bound exceeded ({actual} > {maximum})") | ||
| 92 | - } | ||
| 93 | - Error::User(e) => write!(f, "Username: {e}"), | ||
| 94 | - Error::Community(e) => write!(f, "Community name: {e}"), | ||
| 95 | - Error::Message(e) => write!(f, "Message: {e}"), | ||
| 96 | - } | ||
| 97 | - } | ||
| 98 | } | 99 | } |
| 99 | 100 | ||
| 100 | from_display! { Error { | 101 | from_display! { Error { |
crates/common/src/event.rsadded+14 -0
| @@ -0,0 +1,14 @@ | |||
| 1 | +use bitcode::{Decode, Encode}; | ||
| 2 | + | ||
| 3 | +use crate::model::{Community, Message, User}; | ||
| 4 | + | ||
| 5 | +#[derive(Debug, Clone, Encode, Decode)] | ||
| 6 | +pub enum Event { | ||
| 7 | + MessageCreated(Message), | ||
| 8 | + MessageUpdated(Message), | ||
| 9 | + MessageDeleted(Message), | ||
| 10 | + MemberJoined { community_id: String, user: User }, | ||
| 11 | + MemberLeft { community_id: String, user_id: String }, | ||
| 12 | + CommunityUpdated(Community), | ||
| 13 | + CommunityDeleted { community_id: String }, | ||
| 14 | +} | ||
crates/common/src/lib.rsmodified+2 -0
| @@ -1,6 +1,8 @@ | |||
| 1 | +pub mod certificate; | ||
| 1 | pub mod config; | 2 | pub mod config; |
| 2 | pub mod constant; | 3 | pub mod constant; |
| 3 | pub mod error; | 4 | pub mod error; |
| 5 | +pub mod event; | ||
| 4 | pub mod model; | 6 | pub mod model; |
| 5 | pub mod network; | 7 | pub mod network; |
| 6 | pub mod request; | 8 | pub mod request; |
crates/common/src/model.rsmodified+1 -0
| @@ -10,6 +10,7 @@ pub struct User { | |||
| 10 | pub struct Community { | 10 | pub struct Community { |
| 11 | pub id: String, | 11 | pub id: String, |
| 12 | pub name: String, | 12 | pub name: String, |
| 13 | + pub owner_id: String, | ||
| 13 | } | 14 | } |
| 14 | 15 | ||
| 15 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 16 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
crates/common/src/network.rsmodified+8 -9
| @@ -3,15 +3,14 @@ use quinn::{RecvStream, SendStream}; | |||
| 3 | use crate::{ | 3 | use crate::{ |
| 4 | constant::{MAXIMUM_MESSAGE_LENGTH, MESSAGE_PAGE_LIMIT}, | 4 | constant::{MAXIMUM_MESSAGE_LENGTH, MESSAGE_PAGE_LIMIT}, |
| 5 | error::Error, | 5 | error::Error, |
| 6 | - model::Message, | 6 | + event::Event, |
| 7 | request::Request, | 7 | request::Request, |
| 8 | response::Response, | 8 | response::Response, |
| 9 | }; | 9 | }; |
| 10 | 10 | ||
| 11 | -pub const AUTHENTICATION_MAX_READ_LENGTH: usize = 64; | ||
| 12 | pub const REQUEST_MAX_READ_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2; | 11 | pub const REQUEST_MAX_READ_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2; |
| 13 | -pub const MESSAGE_MAX_ENCODED_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2; | 12 | +pub const EVENT_MAX_ENCODED_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2; |
| 14 | -pub const RESPONSE_MAX_READ_LENGTH: usize = MESSAGE_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT; | 13 | +pub const RESPONSE_MAX_READ_LENGTH: usize = EVENT_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT; |
| 15 | 14 | ||
| 16 | pub async fn send_response(response: &Response, mut send_stream: SendStream) -> Result<(), Error> { | 15 | pub async fn send_response(response: &Response, mut send_stream: SendStream) -> Result<(), Error> { |
| 17 | send_stream.write_all(&bitcode::encode(response)).await?; | 16 | send_stream.write_all(&bitcode::encode(response)).await?; |
| @@ -39,8 +38,8 @@ pub async fn send_request( | |||
| 39 | Ok(bitcode::decode(&bytes)?) | 38 | Ok(bitcode::decode(&bytes)?) |
| 40 | } | 39 | } |
| 41 | 40 | ||
| 42 | -pub async fn send_message(message: &Message, send_stream: &mut SendStream) -> Result<(), Error> { | 41 | +pub async fn send_event(event: &Event, send_stream: &mut SendStream) -> Result<(), Error> { |
| 43 | - let payload = bitcode::encode(message); | 42 | + let payload = bitcode::encode(event); |
| 44 | send_stream | 43 | send_stream |
| 45 | .write_all(&(payload.len() as u32).to_le_bytes()) | 44 | .write_all(&(payload.len() as u32).to_le_bytes()) |
| 46 | .await?; | 45 | .await?; |
| @@ -48,15 +47,15 @@ pub async fn send_message(message: &Message, send_stream: &mut SendStream) -> Re | |||
| 48 | Ok(()) | 47 | Ok(()) |
| 49 | } | 48 | } |
| 50 | 49 | ||
| 51 | -pub async fn receive_message(receive_stream: &mut RecvStream) -> Result<Message, Error> { | 50 | +pub async fn receive_event(receive_stream: &mut RecvStream) -> Result<Event, Error> { |
| 52 | let mut length_bytes = [0u8; 4]; | 51 | let mut length_bytes = [0u8; 4]; |
| 53 | receive_stream.read_exact(&mut length_bytes).await?; | 52 | receive_stream.read_exact(&mut length_bytes).await?; |
| 54 | 53 | ||
| 55 | let length = u32::from_le_bytes(length_bytes) as usize; | 54 | let length = u32::from_le_bytes(length_bytes) as usize; |
| 56 | - if length > MESSAGE_MAX_ENCODED_LENGTH { | 55 | + if length > EVENT_MAX_ENCODED_LENGTH { |
| 57 | return Err(Error::ReadBoundExceed { | 56 | return Err(Error::ReadBoundExceed { |
| 58 | actual: length, | 57 | actual: length, |
| 59 | - maximum: MESSAGE_MAX_ENCODED_LENGTH, | 58 | + maximum: EVENT_MAX_ENCODED_LENGTH, |
| 60 | }); | 59 | }); |
| 61 | } | 60 | } |
| 62 | 61 | ||
crates/common/src/request.rsmodified+13 -14
| @@ -2,25 +2,24 @@ use bitcode::{Decode, Encode}; | |||
| 2 | 2 | ||
| 3 | #[derive(Debug, Clone, Encode, Decode)] | 3 | #[derive(Debug, Clone, Encode, Decode)] |
| 4 | pub enum Request { | 4 | pub enum Request { |
| 5 | - Authentication { token: String }, | 5 | + Register { username: String, password: String }, |
| 6 | - Deauthentication { token: String }, | 6 | + Login { username: String, password: String }, |
| 7 | - CreateUser { username: String }, | 7 | + Resume { token: String }, |
| 8 | + Logout, | ||
| 8 | ReadUser { user_id: String }, | 9 | ReadUser { user_id: String }, |
| 9 | - UpdateUser { user_id: String, username: String }, | 10 | + UpdateUser { username: String }, |
| 10 | - DeleteUser { user_id: String }, | 11 | + DeleteUser, |
| 11 | CreateCommunity { name: String }, | 12 | CreateCommunity { name: String }, |
| 12 | ReadCommunity { community_id: String }, | 13 | ReadCommunity { community_id: String }, |
| 13 | UpdateCommunity { community_id: String, name: String }, | 14 | UpdateCommunity { community_id: String, name: String }, |
| 14 | DeleteCommunity { community_id: String }, | 15 | DeleteCommunity { community_id: String }, |
| 15 | - CreateMessage { user_id: String, community_id: String, body: String }, | 16 | + SearchCommunity { name: String }, |
| 16 | - ReadMessage { message_id: String }, | 17 | + JoinCommunity { community_id: String }, |
| 18 | + LeaveCommunity { community_id: String }, | ||
| 19 | + Communities, | ||
| 20 | + Members { community_id: String }, | ||
| 21 | + CreateMessage { community_id: String, body: String }, | ||
| 17 | UpdateMessage { message_id: String, body: String }, | 22 | UpdateMessage { message_id: String, body: String }, |
| 18 | DeleteMessage { message_id: String }, | 23 | DeleteMessage { message_id: String }, |
| 19 | - ReadMessages { community_id: String, marker: String, limit: usize }, | 24 | + ReadMessages { community_id: String, before: Option<String> }, |
| 20 | - JoinCommunity { user_id: String, community_id: String }, | ||
| 21 | - LeaveCommunity { user_id: String, community_id: String }, | ||
| 22 | - IsUserIn { user_id: String, community_id: String }, | ||
| 23 | - UsersIn { community_id: String }, | ||
| 24 | - CommunitiesOf { user_id: String }, | ||
| 25 | - SearchCommunity { name: String }, | ||
| 26 | } | 25 | } |
crates/common/src/response.rsmodified+8 -21
| @@ -7,26 +7,13 @@ use crate::{ | |||
| 7 | 7 | ||
| 8 | #[derive(Debug, Clone, Encode, Decode)] | 8 | #[derive(Debug, Clone, Encode, Decode)] |
| 9 | pub enum Response { | 9 | pub enum Response { |
| 10 | - Authentication(User), | 10 | + Session { user: User, token: String }, |
| 11 | - Deauthentication(User), | 11 | + User(User), |
| 12 | - CreateUser(User), | 12 | + Community(Community), |
| 13 | - ReadUser(User), | 13 | + Communities(Vec<Community>), |
| 14 | - UpdateUser(User), | 14 | + Members(Vec<User>), |
| 15 | - DeleteUser(User), | 15 | + Message(Message), |
| 16 | - CreateCommunity(Community), | 16 | + Messages(Vec<Message>), |
| 17 | - ReadCommunity(Community), | 17 | + Done, |
| 18 | - UpdateCommunity(Community), | ||
| 19 | - DeleteCommunity(Community), | ||
| 20 | - CreateMessage(Message), | ||
| 21 | - ReadMessage(Message), | ||
| 22 | - UpdateMessage(Message), | ||
| 23 | - DeleteMessage(Message), | ||
| 24 | - ReadMessages(Vec<Message>), | ||
| 25 | - JoinCommunity, | ||
| 26 | - LeaveCommunity, | ||
| 27 | - IsUserIn(bool), | ||
| 28 | - UsersIn(Vec<String>), | ||
| 29 | - CommunitiesOf(Vec<String>), | ||
| 30 | - SearchCommunity(Vec<Community>), | ||
| 31 | Error(Error), | 18 | Error(Error), |
| 32 | } | 19 | } |
crates/common/src/validate.rsmodified+13 -2
| @@ -1,7 +1,8 @@ | |||
| 1 | use crate::{ | 1 | use crate::{ |
| 2 | constant::{ | 2 | constant::{ |
| 3 | - MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_USERNAME_LENGTH, | 3 | + MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_PASSWORD_LENGTH, |
| 4 | - MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH, MINIMUM_USERNAME_LENGTH, | 4 | + MAXIMUM_USERNAME_LENGTH, MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH, |
| 5 | + MINIMUM_PASSWORD_LENGTH, MINIMUM_USERNAME_LENGTH, | ||
| 5 | }, | 6 | }, |
| 6 | error::{Error, InvalidInput}, | 7 | error::{Error, InvalidInput}, |
| 7 | }; | 8 | }; |
| @@ -43,6 +44,16 @@ pub fn validate_username(username: &str) -> Result<(), Error> { | |||
| 43 | .map_err(Error::User) | 44 | .map_err(Error::User) |
| 44 | } | 45 | } |
| 45 | 46 | ||
| 47 | +pub fn validate_password(password: &str) -> Result<(), Error> { | ||
| 48 | + check( | ||
| 49 | + password, | ||
| 50 | + MINIMUM_PASSWORD_LENGTH, | ||
| 51 | + MAXIMUM_PASSWORD_LENGTH, | ||
| 52 | + false, | ||
| 53 | + ) | ||
| 54 | + .map_err(Error::Password) | ||
| 55 | +} | ||
| 56 | + | ||
| 46 | pub fn validate_community_name(name: &str) -> Result<(), Error> { | 57 | pub fn validate_community_name(name: &str) -> Result<(), Error> { |
| 47 | check( | 58 | check( |
| 48 | name, | 59 | name, |
crates/server/Cargo.tomlmodified+6 -5
| @@ -3,19 +3,20 @@ name = "server" | |||
| 3 | version = "0.1.0" | 3 | version = "0.1.0" |
| 4 | edition = "2024" | 4 | edition = "2024" |
| 5 | 5 | ||
| 6 | -[features] | ||
| 7 | -default = ["rcgen"] | ||
| 8 | -rcgen = ["dep:rcgen"] | ||
| 9 | - | ||
| 10 | [dependencies] | 6 | [dependencies] |
| 11 | common.workspace = true | 7 | common.workspace = true |
| 12 | -rcgen = { version = "0.14.10", optional = true } | 8 | +rcgen = "0.14.10" |
| 13 | tokio.workspace = true | 9 | tokio.workspace = true |
| 14 | quinn = { workspace = true, features = ["rustls-aws-lc-rs"] } | 10 | quinn = { workspace = true, features = ["rustls-aws-lc-rs"] } |
| 15 | bitcode.workspace = true | 11 | bitcode.workspace = true |
| 16 | rustls.workspace = true | 12 | rustls.workspace = true |
| 17 | turso = "0.9.0-pre.6" | 13 | turso = "0.9.0-pre.6" |
| 18 | ulid = "3.0.0" | 14 | ulid = "3.0.0" |
| 15 | +argon2 = "0.6.0" | ||
| 16 | +getrandom = "0.4.3" | ||
| 17 | +thiserror = "2.0.21" | ||
| 18 | +tracing = "0.1.44" | ||
| 19 | +tracing-subscriber = "0.3.23" | ||
| 19 | 20 | ||
| 20 | [lints] | 21 | [lints] |
| 21 | workspace = true | 22 | workspace = true |
crates/server/src/authentication.rsmodified+124 -7
| @@ -1,11 +1,128 @@ | |||
| 1 | -use common::{error::Error as CommonError, model::User}; | 1 | +use argon2::{Argon2, PasswordHasher, PasswordVerifier}; |
| 2 | +use common::{ | ||
| 3 | + error::Error as CommonError, | ||
| 4 | + model::User, | ||
| 5 | + validate::{validate_password, validate_username}, | ||
| 6 | +}; | ||
| 7 | +use turso::Connection; | ||
| 2 | 8 | ||
| 3 | -use crate::{database::DB, error::Error, user}; | 9 | +use crate::{error::Error, user}; |
| 4 | 10 | ||
| 5 | -pub async fn authenticate(token: &str, db: &DB) -> Result<User, Error> { | 11 | +const SALT_LENGTH: usize = 16; |
| 6 | - user::read_by_username(token, db) | 12 | +const TOKEN_LENGTH: usize = 32; |
| 13 | + | ||
| 14 | +fn random_bytes<const N: usize>() -> Result<[u8; N], Error> { | ||
| 15 | + let mut bytes = [0u8; N]; | ||
| 16 | + getrandom::fill(&mut bytes).map_err(|error| Error::Hash(format!("random: {error}")))?; | ||
| 17 | + | ||
| 18 | + Ok(bytes) | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +fn hash(password: &str) -> Result<String, Error> { | ||
| 22 | + let salt = random_bytes::<SALT_LENGTH>()?; | ||
| 23 | + let hash = Argon2::default() | ||
| 24 | + .hash_password_with_salt(password.as_bytes(), &salt) | ||
| 25 | + .map_err(|error| Error::Hash(error.to_string()))?; | ||
| 26 | + | ||
| 27 | + Ok(hash.to_string()) | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +fn verify(password: &str, password_hash: &str) -> Result<(), Error> { | ||
| 31 | + Argon2::default() | ||
| 32 | + .verify_password(password.as_bytes(), password_hash) | ||
| 33 | + .map_err(|_| Error::from(CommonError::WrongCredentials)) | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +async fn open_session(user_id: &str, conn: &Connection) -> Result<String, Error> { | ||
| 37 | + let token: String = random_bytes::<TOKEN_LENGTH>()? | ||
| 38 | + .iter() | ||
| 39 | + .map(|byte| format!("{byte:02x}")) | ||
| 40 | + .collect(); | ||
| 41 | + | ||
| 42 | + conn.execute( | ||
| 43 | + "INSERT INTO session (token, user_id) VALUES (?1, ?2)", | ||
| 44 | + (token.as_str(), user_id), | ||
| 45 | + ) | ||
| 46 | + .await?; | ||
| 47 | + | ||
| 48 | + Ok(token) | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +pub async fn register( | ||
| 52 | + username: &str, | ||
| 53 | + password: &str, | ||
| 54 | + conn: &mut Connection, | ||
| 55 | +) -> Result<(User, String), Error> { | ||
| 56 | + validate_username(username)?; | ||
| 57 | + validate_password(password)?; | ||
| 58 | + | ||
| 59 | + let tx = conn.transaction().await?; | ||
| 60 | + if user::by_username(username, &tx).await?.is_some() { | ||
| 61 | + return Err(CommonError::Taken.into()); | ||
| 62 | + } | ||
| 63 | + let user = user::create(username, &hash(password)?, &tx).await?; | ||
| 64 | + let token = open_session(&user.id, &tx).await?; | ||
| 65 | + tx.commit().await?; | ||
| 66 | + | ||
| 67 | + Ok((user, token)) | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +pub async fn login( | ||
| 71 | + username: &str, | ||
| 72 | + password: &str, | ||
| 73 | + conn: &Connection, | ||
| 74 | +) -> Result<(User, String), Error> { | ||
| 75 | + let (user, password_hash) = user::credentials(username, conn) | ||
| 7 | .await? | 76 | .await? |
| 8 | - .into_iter() | 77 | + .ok_or(CommonError::WrongCredentials)?; |
| 9 | - .next() | 78 | + verify(password, &password_hash)?; |
| 10 | - .ok_or(Error::Common(CommonError::Authenticate)) | 79 | + let token = open_session(&user.id, conn).await?; |
| 80 | + | ||
| 81 | + Ok((user, token)) | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +pub async fn resume(token: &str, conn: &Connection) -> Result<User, Error> { | ||
| 85 | + let mut rows = conn | ||
| 86 | + .query( | ||
| 87 | + "SELECT user.id, user.username FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", | ||
| 88 | + (token,), | ||
| 89 | + ) | ||
| 90 | + .await?; | ||
| 91 | + let row = rows.next().await?.ok_or(CommonError::WrongCredentials)?; | ||
| 92 | + | ||
| 93 | + user::from_row(&row) | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +pub async fn logout(token: &str, conn: &Connection) -> Result<(), Error> { | ||
| 97 | + conn.execute("DELETE FROM session WHERE token = ?1", (token,)) | ||
| 98 | + .await?; | ||
| 99 | + | ||
| 100 | + Ok(()) | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +#[cfg(test)] | ||
| 104 | +mod tests { | ||
| 105 | + use common::error::Error as CommonError; | ||
| 106 | + | ||
| 107 | + use crate::{authentication, database, error::Error, test}; | ||
| 108 | + | ||
| 109 | + #[tokio::test] | ||
| 110 | + async fn register_and_login() { | ||
| 111 | + let db = test::get_database().await; | ||
| 112 | + let mut conn = database::connect(&db).await.unwrap(); | ||
| 113 | + | ||
| 114 | + let (registered_user, _) = authentication::register("Tahinli", "correct horse", &mut conn) | ||
| 115 | + .await | ||
| 116 | + .unwrap(); | ||
| 117 | + let (logged_in_user, _) = authentication::login("Tahinli", "correct horse", &conn) | ||
| 118 | + .await | ||
| 119 | + .unwrap(); | ||
| 120 | + let wrong_password = authentication::login("Tahinli", "wrong password", &conn).await; | ||
| 121 | + | ||
| 122 | + assert_eq!(registered_user, logged_in_user); | ||
| 123 | + assert!(matches!( | ||
| 124 | + wrong_password, | ||
| 125 | + Err(Error::Common(CommonError::WrongCredentials)) | ||
| 126 | + )); | ||
| 127 | + } | ||
| 11 | } | 128 | } |
crates/server/src/certificate.rsadded+42 -0
| @@ -0,0 +1,42 @@ | |||
| 1 | +use std::{fs, path::Path}; | ||
| 2 | + | ||
| 3 | +use common::certificate::fingerprint; | ||
| 4 | +use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer}; | ||
| 5 | +use tracing::info; | ||
| 6 | + | ||
| 7 | +use crate::error::Error; | ||
| 8 | + | ||
| 9 | +const SUBJECT_ALT_NAME: &str = "localhost"; | ||
| 10 | + | ||
| 11 | +fn certificate_error(error: impl std::fmt::Display) -> Error { | ||
| 12 | + Error::Common(common::error::Error::Certificate(error.to_string())) | ||
| 13 | +} | ||
| 14 | + | ||
| 15 | +fn generate(certificate_path: &str, key_path: &str) -> Result<(Vec<u8>, Vec<u8>), Error> { | ||
| 16 | + let certified = rcgen::generate_simple_self_signed(vec![SUBJECT_ALT_NAME.to_string()]) | ||
| 17 | + .map_err(certificate_error)?; | ||
| 18 | + let certificate = certified.cert.der().to_vec(); | ||
| 19 | + let key = certified.signing_key.serialize_der(); | ||
| 20 | + | ||
| 21 | + fs::write(certificate_path, &certificate)?; | ||
| 22 | + fs::write(key_path, &key)?; | ||
| 23 | + | ||
| 24 | + Ok((certificate, key)) | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfig, Error> { | ||
| 28 | + let (certificate, key) = if Path::new(certificate_path).exists() && Path::new(key_path).exists() | ||
| 29 | + { | ||
| 30 | + (fs::read(certificate_path)?, fs::read(key_path)?) | ||
| 31 | + } else { | ||
| 32 | + generate(certificate_path, key_path)? | ||
| 33 | + }; | ||
| 34 | + | ||
| 35 | + info!("certificate fingerprint {}", fingerprint(&certificate)); | ||
| 36 | + | ||
| 37 | + quinn::ServerConfig::with_single_cert( | ||
| 38 | + vec![CertificateDer::from(certificate)], | ||
| 39 | + PrivatePkcs8KeyDer::from(key).into(), | ||
| 40 | + ) | ||
| 41 | + .map_err(certificate_error) | ||
| 42 | +} | ||
crates/server/src/community.rsmodified+88 -41
| @@ -1,48 +1,46 @@ | |||
| 1 | -use common::{model::Community, validate::validate_community_name}; | 1 | +use common::{error::Error as CommonError, model::Community, validate::validate_community_name}; |
| 2 | -use turso::Row; | 2 | +use turso::{Connection, Row}; |
| 3 | 3 | ||
| 4 | -use crate::{ | 4 | +use crate::{database::new_id, error::Error}; |
| 5 | - database::{DB, new_id}, | ||
| 6 | - error::Error, | ||
| 7 | -}; | ||
| 8 | 5 | ||
| 9 | fn from_row(row: &Row) -> Result<Community, Error> { | 6 | fn from_row(row: &Row) -> Result<Community, Error> { |
| 10 | Ok(Community { | 7 | Ok(Community { |
| 11 | id: row.get(0)?, | 8 | id: row.get(0)?, |
| 12 | name: row.get(1)?, | 9 | name: row.get(1)?, |
| 10 | + owner_id: row.get(2)?, | ||
| 13 | }) | 11 | }) |
| 14 | } | 12 | } |
| 15 | 13 | ||
| 16 | -pub async fn create(name: &str, db: &DB) -> Result<Community, Error> { | 14 | +pub async fn create(name: &str, owner_id: &str, conn: &Connection) -> Result<Community, Error> { |
| 17 | validate_community_name(name)?; | 15 | validate_community_name(name)?; |
| 18 | 16 | ||
| 19 | - let mut rows = db | 17 | + let mut rows = conn |
| 20 | .query( | 18 | .query( |
| 21 | - "INSERT INTO community (id, name) VALUES (?1, ?2) RETURNING id, name", | 19 | + "INSERT INTO community (id, name, owner_id) VALUES (?1, ?2, ?3) RETURNING id, name, owner_id", |
| 22 | - (new_id(), name), | 20 | + (new_id(), name, owner_id), |
| 23 | ) | 21 | ) |
| 24 | .await?; | 22 | .await?; |
| 25 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 23 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 26 | 24 | ||
| 27 | from_row(&row) | 25 | from_row(&row) |
| 28 | } | 26 | } |
| 29 | 27 | ||
| 30 | -pub async fn read(community_id: &str, db: &DB) -> Result<Community, Error> { | 28 | +pub async fn read(community_id: &str, conn: &Connection) -> Result<Community, Error> { |
| 31 | - let mut rows = db | 29 | + let mut rows = conn |
| 32 | .query( | 30 | .query( |
| 33 | - "SELECT id, name FROM community WHERE id = ?1", | 31 | + "SELECT id, name, owner_id FROM community WHERE id = ?1", |
| 34 | (community_id,), | 32 | (community_id,), |
| 35 | ) | 33 | ) |
| 36 | .await?; | 34 | .await?; |
| 37 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 35 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 38 | 36 | ||
| 39 | from_row(&row) | 37 | from_row(&row) |
| 40 | } | 38 | } |
| 41 | 39 | ||
| 42 | -pub async fn read_by_name(name: &str, db: &DB) -> Result<Vec<Community>, Error> { | 40 | +pub async fn read_by_name(name: &str, conn: &Connection) -> Result<Vec<Community>, Error> { |
| 43 | - let mut rows = db | 41 | + let mut rows = conn |
| 44 | .query( | 42 | .query( |
| 45 | - "SELECT id, name FROM community WHERE name = ?1 ORDER BY id", | 43 | + "SELECT id, name, owner_id FROM community WHERE name = ?1 ORDER BY id", |
| 46 | (name,), | 44 | (name,), |
| 47 | ) | 45 | ) |
| 48 | .await?; | 46 | .await?; |
| @@ -55,51 +53,78 @@ pub async fn read_by_name(name: &str, db: &DB) -> Result<Vec<Community>, Error> | |||
| 55 | Ok(communities) | 53 | Ok(communities) |
| 56 | } | 54 | } |
| 57 | 55 | ||
| 58 | -pub async fn update(community_id: &str, name: &str, db: &DB) -> Result<Community, Error> { | 56 | +pub async fn communities_of(user_id: &str, conn: &Connection) -> Result<Vec<Community>, Error> { |
| 57 | + let mut rows = conn | ||
| 58 | + .query( | ||
| 59 | + "SELECT community.id, community.name, community.owner_id FROM community JOIN user_community ON user_community.community_id = community.id WHERE user_community.user_id = ?1 ORDER BY community.id", | ||
| 60 | + (user_id,), | ||
| 61 | + ) | ||
| 62 | + .await?; | ||
| 63 | + | ||
| 64 | + let mut communities = Vec::new(); | ||
| 65 | + while let Some(row) = rows.next().await? { | ||
| 66 | + communities.push(from_row(&row)?); | ||
| 67 | + } | ||
| 68 | + | ||
| 69 | + Ok(communities) | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +pub async fn update(community_id: &str, name: &str, conn: &Connection) -> Result<Community, Error> { | ||
| 59 | validate_community_name(name)?; | 73 | validate_community_name(name)?; |
| 60 | 74 | ||
| 61 | - let mut rows = db | 75 | + let mut rows = conn |
| 62 | .query( | 76 | .query( |
| 63 | - "UPDATE community SET name = ?2 WHERE id = ?1 RETURNING id, name", | 77 | + "UPDATE community SET name = ?2 WHERE id = ?1 RETURNING id, name, owner_id", |
| 64 | (community_id, name), | 78 | (community_id, name), |
| 65 | ) | 79 | ) |
| 66 | .await?; | 80 | .await?; |
| 67 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 81 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 68 | 82 | ||
| 69 | from_row(&row) | 83 | from_row(&row) |
| 70 | } | 84 | } |
| 71 | 85 | ||
| 72 | -pub async fn delete(community_id: &str, db: &DB) -> Result<Community, Error> { | 86 | +pub async fn delete(community_id: &str, conn: &Connection) -> Result<Community, Error> { |
| 73 | - let mut rows = db | 87 | + let mut rows = conn |
| 74 | .query( | 88 | .query( |
| 75 | - "DELETE FROM community WHERE id = ?1 RETURNING id, name", | 89 | + "DELETE FROM community WHERE id = ?1 RETURNING id, name, owner_id", |
| 76 | (community_id,), | 90 | (community_id,), |
| 77 | ) | 91 | ) |
| 78 | .await?; | 92 | .await?; |
| 79 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 93 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 80 | 94 | ||
| 81 | from_row(&row) | 95 | from_row(&row) |
| 82 | } | 96 | } |
| 83 | 97 | ||
| 84 | #[cfg(test)] | 98 | #[cfg(test)] |
| 85 | mod tests { | 99 | mod tests { |
| 86 | - use crate::{community, error::Error, test}; | 100 | + use common::error::Error as CommonError; |
| 101 | + | ||
| 102 | + use crate::{community, database, error::Error, test, user}; | ||
| 87 | 103 | ||
| 88 | #[tokio::test] | 104 | #[tokio::test] |
| 89 | async fn create() { | 105 | async fn create() { |
| 90 | let db = test::get_database().await; | 106 | let db = test::get_database().await; |
| 107 | + let conn = database::connect(&db).await.unwrap(); | ||
| 108 | + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 91 | 109 | ||
| 92 | - let community = community::create("Tahinli", &db).await.unwrap(); | 110 | + let community = community::create("Tahinli", &owner.id, &conn) |
| 111 | + .await | ||
| 112 | + .unwrap(); | ||
| 93 | 113 | ||
| 94 | assert_eq!("Tahinli", community.name); | 114 | assert_eq!("Tahinli", community.name); |
| 115 | + assert_eq!(owner.id, community.owner_id); | ||
| 95 | } | 116 | } |
| 96 | 117 | ||
| 97 | #[tokio::test] | 118 | #[tokio::test] |
| 98 | async fn read() { | 119 | async fn read() { |
| 99 | let db = test::get_database().await; | 120 | let db = test::get_database().await; |
| 121 | + let conn = database::connect(&db).await.unwrap(); | ||
| 122 | + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 100 | 123 | ||
| 101 | - let created_community = community::create("Tahinli", &db).await.unwrap(); | 124 | + let created_community = community::create("Tahinli", &owner.id, &conn) |
| 102 | - let searched_community = community::read(&created_community.id, &db).await.unwrap(); | 125 | + .await |
| 126 | + .unwrap(); | ||
| 127 | + let searched_community = community::read(&created_community.id, &conn).await.unwrap(); | ||
| 103 | 128 | ||
| 104 | assert_eq!(created_community, searched_community); | 129 | assert_eq!(created_community, searched_community); |
| 105 | } | 130 | } |
| @@ -107,12 +132,20 @@ mod tests { | |||
| 107 | #[tokio::test] | 132 | #[tokio::test] |
| 108 | async fn read_by_name() { | 133 | async fn read_by_name() { |
| 109 | let db = test::get_database().await; | 134 | let db = test::get_database().await; |
| 135 | + let conn = database::connect(&db).await.unwrap(); | ||
| 136 | + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 110 | 137 | ||
| 111 | - let community_1 = community::create("Tahinli", &db).await.unwrap(); | 138 | + let community_1 = community::create("Tahinli", &owner.id, &conn) |
| 112 | - let community_2 = community::create("Tahinli", &db).await.unwrap(); | 139 | + .await |
| 113 | - let _community_3 = community::create("Not Tahinli", &db).await.unwrap(); | 140 | + .unwrap(); |
| 141 | + let community_2 = community::create("Tahinli", &owner.id, &conn) | ||
| 142 | + .await | ||
| 143 | + .unwrap(); | ||
| 144 | + let _community_3 = community::create("Not Tahinli", &owner.id, &conn) | ||
| 145 | + .await | ||
| 146 | + .unwrap(); | ||
| 114 | 147 | ||
| 115 | - let searched_communities = community::read_by_name("Tahinli", &db).await.unwrap(); | 148 | + let searched_communities = community::read_by_name("Tahinli", &conn).await.unwrap(); |
| 116 | 149 | ||
| 117 | assert_eq!(vec![community_1, community_2], searched_communities); | 150 | assert_eq!(vec![community_1, community_2], searched_communities); |
| 118 | } | 151 | } |
| @@ -120,12 +153,16 @@ mod tests { | |||
| 120 | #[tokio::test] | 153 | #[tokio::test] |
| 121 | async fn update() { | 154 | async fn update() { |
| 122 | let db = test::get_database().await; | 155 | let db = test::get_database().await; |
| 156 | + let conn = database::connect(&db).await.unwrap(); | ||
| 157 | + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 123 | 158 | ||
| 124 | - let created_community = community::create("Tahinli", &db).await.unwrap(); | 159 | + let created_community = community::create("Tahinli", &owner.id, &conn) |
| 125 | - let updated_community = community::update(&created_community.id, "Not Tahinli", &db) | 160 | + .await |
| 161 | + .unwrap(); | ||
| 162 | + let updated_community = community::update(&created_community.id, "Not Tahinli", &conn) | ||
| 126 | .await | 163 | .await |
| 127 | .unwrap(); | 164 | .unwrap(); |
| 128 | - let searched_community = community::read(&created_community.id, &db).await.unwrap(); | 165 | + let searched_community = community::read(&created_community.id, &conn).await.unwrap(); |
| 129 | 166 | ||
| 130 | assert_eq!(created_community.id, searched_community.id); | 167 | assert_eq!(created_community.id, searched_community.id); |
| 131 | assert_eq!(updated_community, searched_community); | 168 | assert_eq!(updated_community, searched_community); |
| @@ -135,18 +172,28 @@ mod tests { | |||
| 135 | #[tokio::test] | 172 | #[tokio::test] |
| 136 | async fn update_on_missing_community() { | 173 | async fn update_on_missing_community() { |
| 137 | let db = test::get_database().await; | 174 | let db = test::get_database().await; |
| 175 | + let conn = database::connect(&db).await.unwrap(); | ||
| 138 | 176 | ||
| 139 | - let updated_community = community::update("missing", "Not Tahinli", &db).await; | 177 | + let updated_community = community::update("missing", "Not Tahinli", &conn).await; |
| 140 | 178 | ||
| 141 | - assert!(matches!(updated_community, Err(Error::NotFound))); | 179 | + assert!(matches!( |
| 180 | + updated_community, | ||
| 181 | + Err(Error::Common(CommonError::NotFound)) | ||
| 182 | + )); | ||
| 142 | } | 183 | } |
| 143 | 184 | ||
| 144 | #[tokio::test] | 185 | #[tokio::test] |
| 145 | async fn delete() { | 186 | async fn delete() { |
| 146 | let db = test::get_database().await; | 187 | let db = test::get_database().await; |
| 188 | + let conn = database::connect(&db).await.unwrap(); | ||
| 189 | + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 147 | 190 | ||
| 148 | - let created_community = community::create("Tahinli", &db).await.unwrap(); | 191 | + let created_community = community::create("Tahinli", &owner.id, &conn) |
| 149 | - let deleted_community = community::delete(&created_community.id, &db).await.unwrap(); | 192 | + .await |
| 193 | + .unwrap(); | ||
| 194 | + let deleted_community = community::delete(&created_community.id, &conn) | ||
| 195 | + .await | ||
| 196 | + .unwrap(); | ||
| 150 | 197 | ||
| 151 | assert_eq!(created_community, deleted_community); | 198 | assert_eq!(created_community, deleted_community); |
| 152 | } | 199 | } |
crates/server/src/database.rsmodified+75 -34
| @@ -1,52 +1,93 @@ | |||
| 1 | -use std::sync::{LazyLock, Mutex}; | 1 | +use std::{ |
| 2 | + sync::{LazyLock, Mutex}, | ||
| 3 | + time::Duration, | ||
| 4 | +}; | ||
| 2 | 5 | ||
| 6 | +use turso::Connection; | ||
| 3 | use ulid::Generator; | 7 | use ulid::Generator; |
| 4 | 8 | ||
| 5 | use crate::error::Error; | 9 | use crate::error::Error; |
| 6 | 10 | ||
| 7 | -pub type DB = turso::Connection; | 11 | +pub type DB = turso::Database; |
| 8 | 12 | ||
| 9 | static ULID: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new())); | 13 | static ULID: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new())); |
| 10 | 14 | ||
| 11 | -pub async fn connect(path: &str) -> Result<DB, Error> { | 15 | +const BUSY_TIMEOUT: Duration = Duration::from_secs(5); |
| 12 | - let database = turso::Builder::new_local(path).build().await?; | ||
| 13 | 16 | ||
| 14 | - Ok(database.connect()?) | 17 | +const MIGRATIONS: &[&str] = &[" |
| 18 | + CREATE TABLE user ( | ||
| 19 | + id TEXT PRIMARY KEY, | ||
| 20 | + username TEXT NOT NULL UNIQUE, | ||
| 21 | + password_hash TEXT NOT NULL | ||
| 22 | + ); | ||
| 23 | + | ||
| 24 | + CREATE TABLE session ( | ||
| 25 | + token TEXT PRIMARY KEY, | ||
| 26 | + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE | ||
| 27 | + ); | ||
| 28 | + | ||
| 29 | + CREATE TABLE community ( | ||
| 30 | + id TEXT PRIMARY KEY, | ||
| 31 | + name TEXT NOT NULL, | ||
| 32 | + owner_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE | ||
| 33 | + ); | ||
| 34 | + | ||
| 35 | + CREATE TABLE message ( | ||
| 36 | + id TEXT PRIMARY KEY, | ||
| 37 | + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 38 | + community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 39 | + body TEXT NOT NULL | ||
| 40 | + ); | ||
| 41 | + | ||
| 42 | + CREATE INDEX message_community_id_id ON message (community_id, id); | ||
| 43 | + | ||
| 44 | + CREATE TABLE user_community ( | ||
| 45 | + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 46 | + community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 47 | + PRIMARY KEY (user_id, community_id) | ||
| 48 | + ); | ||
| 49 | +"]; | ||
| 50 | + | ||
| 51 | +pub async fn open(path: &str) -> Result<DB, Error> { | ||
| 52 | + let db = turso::Builder::new_local(path).build().await?; | ||
| 53 | + migrate(&db).await?; | ||
| 54 | + | ||
| 55 | + Ok(db) | ||
| 15 | } | 56 | } |
| 16 | 57 | ||
| 17 | -pub async fn migrate(db: &DB) -> Result<(), Error> { | 58 | +pub async fn connect(db: &DB) -> Result<Connection, Error> { |
| 18 | - db.execute_batch( | 59 | + let conn = db.connect()?; |
| 19 | - " | 60 | + conn.busy_timeout(BUSY_TIMEOUT)?; |
| 20 | - CREATE TABLE IF NOT EXISTS user ( | 61 | + conn.execute_batch("PRAGMA foreign_keys = ON;").await?; |
| 21 | - id TEXT PRIMARY KEY, | 62 | + |
| 22 | - username TEXT NOT NULL | 63 | + Ok(conn) |
| 23 | - ); | 64 | +} |
| 24 | - | 65 | + |
| 25 | - CREATE TABLE IF NOT EXISTS community ( | 66 | +async fn migrate(db: &DB) -> Result<(), Error> { |
| 26 | - id TEXT PRIMARY KEY, | 67 | + let mut conn = connect(db).await?; |
| 27 | - name TEXT NOT NULL | 68 | + let applied = user_version(&conn).await?; |
| 28 | - ); | 69 | + |
| 29 | - | 70 | + for (index, migration) in MIGRATIONS.iter().enumerate().skip(applied) { |
| 30 | - CREATE TABLE IF NOT EXISTS message ( | 71 | + let tx = conn.transaction().await?; |
| 31 | - id TEXT PRIMARY KEY, | 72 | + tx.execute_batch(migration).await?; |
| 32 | - user_id TEXT NOT NULL, | 73 | + tx.pragma_update("user_version", index + 1).await?; |
| 33 | - community_id TEXT NOT NULL, | 74 | + tx.commit().await?; |
| 34 | - body TEXT NOT NULL | 75 | + } |
| 35 | - ); | ||
| 36 | - CREATE INDEX IF NOT EXISTS message_community_id ON message (community_id); | ||
| 37 | - | ||
| 38 | - CREATE TABLE IF NOT EXISTS user_community ( | ||
| 39 | - user_id TEXT NOT NULL, | ||
| 40 | - community_id TEXT NOT NULL, | ||
| 41 | - PRIMARY KEY (user_id, community_id) | ||
| 42 | - ); | ||
| 43 | - ", | ||
| 44 | - ) | ||
| 45 | - .await?; | ||
| 46 | 76 | ||
| 47 | Ok(()) | 77 | Ok(()) |
| 48 | } | 78 | } |
| 49 | 79 | ||
| 80 | +async fn user_version(conn: &Connection) -> Result<usize, Error> { | ||
| 81 | + let mut rows = conn.query("PRAGMA user_version", ()).await?; | ||
| 82 | + let row = rows | ||
| 83 | + .next() | ||
| 84 | + .await? | ||
| 85 | + .ok_or(turso::Error::QueryReturnedNoRows)?; | ||
| 86 | + let version: i64 = row.get(0)?; | ||
| 87 | + | ||
| 88 | + Ok(version as usize) | ||
| 89 | +} | ||
| 90 | + | ||
| 50 | pub fn new_id() -> String { | 91 | pub fn new_id() -> String { |
| 51 | loop { | 92 | loop { |
| 52 | match ULID.lock().unwrap().generate() { | 93 | match ULID.lock().unwrap().generate() { |
crates/server/src/error.rsmodified+9 -22
| @@ -1,24 +1,14 @@ | |||
| 1 | -use std::fmt::Display; | ||
| 2 | - | ||
| 3 | use common::error_from; | 1 | use common::error_from; |
| 2 | +use tracing::error; | ||
| 4 | 3 | ||
| 5 | -#[derive(Debug)] | 4 | +#[derive(Debug, thiserror::Error)] |
| 6 | pub enum Error { | 5 | pub enum Error { |
| 7 | - Common(common::error::Error), | 6 | + #[error(transparent)] |
| 8 | - Database(turso::Error), | 7 | + Common(#[from] common::error::Error), |
| 9 | - NotFound, | 8 | + #[error(transparent)] |
| 10 | -} | 9 | + Database(#[from] turso::Error), |
| 11 | - | 10 | + #[error("password hash: {0}")] |
| 12 | -impl std::error::Error for Error {} | 11 | + Hash(String), |
| 13 | - | ||
| 14 | -impl Display for Error { | ||
| 15 | - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 16 | - match self { | ||
| 17 | - Error::Common(error) => write!(f, "{error}"), | ||
| 18 | - Error::Database(error) => write!(f, "Database: {error}"), | ||
| 19 | - Error::NotFound => write!(f, "Not found"), | ||
| 20 | - } | ||
| 21 | - } | ||
| 22 | } | 12 | } |
| 23 | 13 | ||
| 24 | impl From<Error> for common::error::Error { | 14 | impl From<Error> for common::error::Error { |
| @@ -26,7 +16,7 @@ impl From<Error> for common::error::Error { | |||
| 26 | match value { | 16 | match value { |
| 27 | Error::Common(error) => error, | 17 | Error::Common(error) => error, |
| 28 | error => { | 18 | error => { |
| 29 | - eprintln!("Error: {error}"); | 19 | + error!("{error}"); |
| 30 | 20 | ||
| 31 | common::error::Error::Server | 21 | common::error::Error::Server |
| 32 | } | 22 | } |
| @@ -35,9 +25,6 @@ impl From<Error> for common::error::Error { | |||
| 35 | } | 25 | } |
| 36 | 26 | ||
| 37 | error_from! { Error { | 27 | error_from! { Error { |
| 38 | - common::error::Error => Error::Common, | ||
| 39 | - turso::Error => Error::Database, | ||
| 40 | - | ||
| 41 | std::net::AddrParseError => Error::Common as common::error::Error, | 28 | std::net::AddrParseError => Error::Common as common::error::Error, |
| 42 | std::io::Error => Error::Common as common::error::Error, | 29 | std::io::Error => Error::Common as common::error::Error, |
| 43 | quinn::ConnectionError => Error::Common as common::error::Error, | 30 | quinn::ConnectionError => Error::Common as common::error::Error, |
crates/server/src/lib.rsmodified+24 -20
| @@ -1,4 +1,5 @@ | |||
| 1 | pub mod authentication; | 1 | pub mod authentication; |
| 2 | +pub mod certificate; | ||
| 2 | pub mod community; | 3 | pub mod community; |
| 3 | pub mod database; | 4 | pub mod database; |
| 4 | pub mod error; | 5 | pub mod error; |
| @@ -11,6 +12,10 @@ pub mod user_community; | |||
| 11 | #[cfg(test)] | 12 | #[cfg(test)] |
| 12 | mod test; | 13 | mod test; |
| 13 | 14 | ||
| 15 | +use common::config::Config; | ||
| 16 | + | ||
| 17 | +use crate::error::Error; | ||
| 18 | + | ||
| 14 | const SERVER_CONFIG_FILE_PATH: &str = concat!( | 19 | const SERVER_CONFIG_FILE_PATH: &str = concat!( |
| 15 | env!("CARGO_MANIFEST_DIR"), | 20 | env!("CARGO_MANIFEST_DIR"), |
| 16 | "/../../configs/server_config.toml" | 21 | "/../../configs/server_config.toml" |
| @@ -19,32 +24,31 @@ const SERVER_CONFIG_FILE_PATH: &str = concat!( | |||
| 19 | pub struct ServerConfig { | 24 | pub struct ServerConfig { |
| 20 | pub database_path: String, | 25 | pub database_path: String, |
| 21 | pub server_address: String, | 26 | pub server_address: String, |
| 27 | + pub certificate_path: String, | ||
| 28 | + pub key_path: String, | ||
| 22 | } | 29 | } |
| 23 | 30 | ||
| 24 | -impl Default for ServerConfig { | 31 | +impl ServerConfig { |
| 25 | - fn default() -> Self { | 32 | + fn parse(content: &str) -> Result<Self, Error> { |
| 26 | - let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH).unwrap(); | 33 | + let config = Config::parse(content)?; |
| 27 | - let mut fields = common::config::parse(&content).unwrap(); | ||
| 28 | 34 | ||
| 29 | - Self { | 35 | + Ok(Self { |
| 30 | - database_path: fields.remove("database_path").unwrap(), | 36 | + database_path: config.get("database_path")?, |
| 31 | - server_address: fields.remove("server_address").unwrap(), | 37 | + server_address: config.get("server_address")?, |
| 32 | - } | 38 | + certificate_path: config.get("certificate_path")?, |
| 39 | + key_path: config.get("key_path")?, | ||
| 40 | + }) | ||
| 33 | } | 41 | } |
| 34 | } | 42 | } |
| 35 | 43 | ||
| 36 | -pub async fn showtime() { | 44 | +pub async fn showtime() -> Result<(), Error> { |
| 37 | - rustls::crypto::aws_lc_rs::default_provider() | 45 | + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); |
| 38 | - .install_default() | 46 | + |
| 39 | - .unwrap(); | 47 | + let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH)?; |
| 40 | - let server_config = ServerConfig::default(); | 48 | + let config = ServerConfig::parse(&content)?; |
| 41 | 49 | ||
| 42 | - let database = database::connect(&server_config.database_path) | 50 | + let database = database::open(&config.database_path).await?; |
| 43 | - .await | 51 | + let certificate = certificate::load(&config.certificate_path, &config.key_path)?; |
| 44 | - .unwrap(); | ||
| 45 | - database::migrate(&database).await.unwrap(); | ||
| 46 | 52 | ||
| 47 | - network::serve(&server_config.server_address, &database) | 53 | + network::serve(&config.server_address, certificate, database).await |
| 48 | - .await | ||
| 49 | - .unwrap(); | ||
| 50 | } | 54 | } |
crates/server/src/main.rsmodified+4 -2
| @@ -1,6 +1,8 @@ | |||
| 1 | use server::showtime; | 1 | use server::showtime; |
| 2 | 2 | ||
| 3 | #[tokio::main] | 3 | #[tokio::main] |
| 4 | -async fn main() { | 4 | +async fn main() -> Result<(), server::error::Error> { |
| 5 | - showtime().await; | 5 | + tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init(); |
| 6 | + | ||
| 7 | + showtime().await | ||
| 6 | } | 8 | } |
crates/server/src/message.rsmodified+68 -62
| @@ -1,10 +1,10 @@ | |||
| 1 | -use common::{model::Message, validate::validate_message_body}; | 1 | +use common::{ |
| 2 | -use turso::Row; | 2 | + constant::MESSAGE_PAGE_LIMIT, error::Error as CommonError, model::Message, |
| 3 | - | 3 | + validate::validate_message_body, |
| 4 | -use crate::{ | ||
| 5 | - database::{DB, new_id}, | ||
| 6 | - error::Error, | ||
| 7 | }; | 4 | }; |
| 5 | +use turso::{Connection, Row}; | ||
| 6 | + | ||
| 7 | +use crate::{database::new_id, error::Error}; | ||
| 8 | 8 | ||
| 9 | fn from_row(row: &Row) -> Result<Message, Error> { | 9 | fn from_row(row: &Row) -> Result<Message, Error> { |
| 10 | Ok(Message { | 10 | Ok(Message { |
| @@ -19,43 +19,42 @@ pub async fn create( | |||
| 19 | user_id: &str, | 19 | user_id: &str, |
| 20 | community_id: &str, | 20 | community_id: &str, |
| 21 | body: &str, | 21 | body: &str, |
| 22 | - db: &DB, | 22 | + conn: &Connection, |
| 23 | ) -> Result<Message, Error> { | 23 | ) -> Result<Message, Error> { |
| 24 | validate_message_body(body)?; | 24 | validate_message_body(body)?; |
| 25 | 25 | ||
| 26 | - let mut rows = db | 26 | + let mut rows = conn |
| 27 | .query( | 27 | .query( |
| 28 | "INSERT INTO message (id, user_id, community_id, body) VALUES (?1, ?2, ?3, ?4) RETURNING id, user_id, community_id, body", | 28 | "INSERT INTO message (id, user_id, community_id, body) VALUES (?1, ?2, ?3, ?4) RETURNING id, user_id, community_id, body", |
| 29 | (new_id(), user_id, community_id, body), | 29 | (new_id(), user_id, community_id, body), |
| 30 | ) | 30 | ) |
| 31 | .await?; | 31 | .await?; |
| 32 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 32 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 33 | 33 | ||
| 34 | from_row(&row) | 34 | from_row(&row) |
| 35 | } | 35 | } |
| 36 | 36 | ||
| 37 | -pub async fn read(message_id: &str, db: &DB) -> Result<Message, Error> { | 37 | +pub async fn read(message_id: &str, conn: &Connection) -> Result<Message, Error> { |
| 38 | - let mut rows = db | 38 | + let mut rows = conn |
| 39 | .query( | 39 | .query( |
| 40 | "SELECT id, user_id, community_id, body FROM message WHERE id = ?1", | 40 | "SELECT id, user_id, community_id, body FROM message WHERE id = ?1", |
| 41 | (message_id,), | 41 | (message_id,), |
| 42 | ) | 42 | ) |
| 43 | .await?; | 43 | .await?; |
| 44 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 44 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 45 | 45 | ||
| 46 | from_row(&row) | 46 | from_row(&row) |
| 47 | } | 47 | } |
| 48 | 48 | ||
| 49 | pub async fn read_page( | 49 | pub async fn read_page( |
| 50 | community_id: &str, | 50 | community_id: &str, |
| 51 | - marker: &str, | 51 | + before: Option<&str>, |
| 52 | - limit: usize, | 52 | + conn: &Connection, |
| 53 | - db: &DB, | ||
| 54 | ) -> Result<Vec<Message>, Error> { | 53 | ) -> Result<Vec<Message>, Error> { |
| 55 | - let mut rows = db | 54 | + let mut rows = conn |
| 56 | .query( | 55 | .query( |
| 57 | - "SELECT id, user_id, community_id, body FROM message WHERE community_id = ?1 AND id <= ?2 ORDER BY id DESC LIMIT ?3", | 56 | + "SELECT id, user_id, community_id, body FROM message WHERE community_id = ?1 AND (?2 IS NULL OR id < ?2) ORDER BY id DESC LIMIT ?3", |
| 58 | - (community_id, marker, limit as i64), | 57 | + (community_id, before, MESSAGE_PAGE_LIMIT as i64), |
| 59 | ) | 58 | ) |
| 60 | .await?; | 59 | .await?; |
| 61 | 60 | ||
| @@ -68,43 +67,46 @@ pub async fn read_page( | |||
| 68 | Ok(messages) | 67 | Ok(messages) |
| 69 | } | 68 | } |
| 70 | 69 | ||
| 71 | -pub async fn update(message_id: &str, body: &str, db: &DB) -> Result<Message, Error> { | 70 | +pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<Message, Error> { |
| 72 | validate_message_body(body)?; | 71 | validate_message_body(body)?; |
| 73 | 72 | ||
| 74 | - let mut rows = db | 73 | + let mut rows = conn |
| 75 | .query( | 74 | .query( |
| 76 | "UPDATE message SET body = ?2 WHERE id = ?1 RETURNING id, user_id, community_id, body", | 75 | "UPDATE message SET body = ?2 WHERE id = ?1 RETURNING id, user_id, community_id, body", |
| 77 | (message_id, body), | 76 | (message_id, body), |
| 78 | ) | 77 | ) |
| 79 | .await?; | 78 | .await?; |
| 80 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 79 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 81 | 80 | ||
| 82 | from_row(&row) | 81 | from_row(&row) |
| 83 | } | 82 | } |
| 84 | 83 | ||
| 85 | -pub async fn delete(message_id: &str, db: &DB) -> Result<Message, Error> { | 84 | +pub async fn delete(message_id: &str, conn: &Connection) -> Result<Message, Error> { |
| 86 | - let mut rows = db | 85 | + let mut rows = conn |
| 87 | .query( | 86 | .query( |
| 88 | "DELETE FROM message WHERE id = ?1 RETURNING id, user_id, community_id, body", | 87 | "DELETE FROM message WHERE id = ?1 RETURNING id, user_id, community_id, body", |
| 89 | (message_id,), | 88 | (message_id,), |
| 90 | ) | 89 | ) |
| 91 | .await?; | 90 | .await?; |
| 92 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 91 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 93 | 92 | ||
| 94 | from_row(&row) | 93 | from_row(&row) |
| 95 | } | 94 | } |
| 96 | 95 | ||
| 97 | #[cfg(test)] | 96 | #[cfg(test)] |
| 98 | mod tests { | 97 | mod tests { |
| 99 | - use crate::{community, error::Error, message, test, user}; | 98 | + use common::error::Error as CommonError; |
| 99 | + | ||
| 100 | + use crate::{community, database, error::Error, message, test, user}; | ||
| 100 | 101 | ||
| 101 | #[tokio::test] | 102 | #[tokio::test] |
| 102 | async fn create() { | 103 | async fn create() { |
| 103 | let db = test::get_database().await; | 104 | let db = test::get_database().await; |
| 105 | + let conn = database::connect(&db).await.unwrap(); | ||
| 106 | + let user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 107 | + let community = community::create("Tahinli", &user.id, &conn).await.unwrap(); | ||
| 104 | 108 | ||
| 105 | - let user = user::create("Tahinli", &db).await.unwrap(); | 109 | + let message = message::create(&user.id, &community.id, "Tahinli", &conn) |
| 106 | - let community = community::create("Tahinli", &db).await.unwrap(); | ||
| 107 | - let message = message::create(&user.id, &community.id, "Tahinli", &db) | ||
| 108 | .await | 110 | .await |
| 109 | .unwrap(); | 111 | .unwrap(); |
| 110 | 112 | ||
| @@ -116,14 +118,14 @@ mod tests { | |||
| 116 | #[tokio::test] | 118 | #[tokio::test] |
| 117 | async fn read() { | 119 | async fn read() { |
| 118 | let db = test::get_database().await; | 120 | let db = test::get_database().await; |
| 119 | - | 121 | + let conn = database::connect(&db).await.unwrap(); |
| 120 | - let user = user::create("Tahinli", &db).await.unwrap(); | 122 | + let user = user::create("Tahinli", "hash", &conn).await.unwrap(); |
| 121 | - let community = community::create("Tahinli", &db).await.unwrap(); | 123 | + let community = community::create("Tahinli", &user.id, &conn).await.unwrap(); |
| 122 | - let created_message = message::create(&user.id, &community.id, "Tahinli", &db) | 124 | + let created_message = message::create(&user.id, &community.id, "Tahinli", &conn) |
| 123 | .await | 125 | .await |
| 124 | .unwrap(); | 126 | .unwrap(); |
| 125 | 127 | ||
| 126 | - let searched_message = message::read(&created_message.id, &db).await.unwrap(); | 128 | + let searched_message = message::read(&created_message.id, &conn).await.unwrap(); |
| 127 | 129 | ||
| 128 | assert_eq!(created_message, searched_message); | 130 | assert_eq!(created_message, searched_message); |
| 129 | } | 131 | } |
| @@ -131,51 +133,51 @@ mod tests { | |||
| 131 | #[tokio::test] | 133 | #[tokio::test] |
| 132 | async fn read_page() { | 134 | async fn read_page() { |
| 133 | let db = test::get_database().await; | 135 | let db = test::get_database().await; |
| 136 | + let conn = database::connect(&db).await.unwrap(); | ||
| 137 | + let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 138 | + let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap(); | ||
| 139 | + let community = community::create("Tahinli", &user_1.id, &conn) | ||
| 140 | + .await | ||
| 141 | + .unwrap(); | ||
| 134 | 142 | ||
| 135 | - let user_1 = user::create("Tahinli", &db).await.unwrap(); | 143 | + let message_1 = message::create(&user_1.id, &community.id, "Tahinli", &conn) |
| 136 | - let user_2 = user::create("Not Tahinli", &db).await.unwrap(); | ||
| 137 | - let community = community::create("Tahinli", &db).await.unwrap(); | ||
| 138 | - | ||
| 139 | - let message_1 = message::create(&user_1.id, &community.id, "Tahinli", &db) | ||
| 140 | .await | 144 | .await |
| 141 | .unwrap(); | 145 | .unwrap(); |
| 142 | - let message_2 = message::create(&user_2.id, &community.id, "Tahinli", &db) | 146 | + let message_2 = message::create(&user_2.id, &community.id, "Tahinli", &conn) |
| 143 | .await | 147 | .await |
| 144 | .unwrap(); | 148 | .unwrap(); |
| 145 | - let message_3 = message::create(&user_2.id, &community.id, "Tahinli", &db) | 149 | + let message_3 = message::create(&user_2.id, &community.id, "Tahinli", &conn) |
| 146 | .await | 150 | .await |
| 147 | .unwrap(); | 151 | .unwrap(); |
| 148 | 152 | ||
| 149 | - let searched_messages = message::read_page(&community.id, &message_3.id, 3, &db) | 153 | + let newest = message::read_page(&community.id, None, &conn) |
| 150 | .await | 154 | .await |
| 151 | .unwrap(); | 155 | .unwrap(); |
| 152 | - | 156 | + let older = message::read_page(&community.id, Some(&message_3.id), &conn) |
| 153 | - assert_eq!( | ||
| 154 | - vec![message_1, message_2, message_3.clone()], | ||
| 155 | - searched_messages | ||
| 156 | - ); | ||
| 157 | - | ||
| 158 | - let searched_messages = message::read_page(&community.id, &message_3.id, 1, &db) | ||
| 159 | .await | 157 | .await |
| 160 | .unwrap(); | 158 | .unwrap(); |
| 161 | 159 | ||
| 162 | - assert_eq!(vec![message_3], searched_messages); | 160 | + assert_eq!( |
| 161 | + vec![message_1.clone(), message_2.clone(), message_3], | ||
| 162 | + newest | ||
| 163 | + ); | ||
| 164 | + assert_eq!(vec![message_1, message_2], older); | ||
| 163 | } | 165 | } |
| 164 | 166 | ||
| 165 | #[tokio::test] | 167 | #[tokio::test] |
| 166 | async fn update() { | 168 | async fn update() { |
| 167 | let db = test::get_database().await; | 169 | let db = test::get_database().await; |
| 168 | - | 170 | + let conn = database::connect(&db).await.unwrap(); |
| 169 | - let user = user::create("Tahinli", &db).await.unwrap(); | 171 | + let user = user::create("Tahinli", "hash", &conn).await.unwrap(); |
| 170 | - let community = community::create("Tahinli", &db).await.unwrap(); | 172 | + let community = community::create("Tahinli", &user.id, &conn).await.unwrap(); |
| 171 | - let created_message = message::create(&user.id, &community.id, "Tahinli", &db) | 173 | + let created_message = message::create(&user.id, &community.id, "Tahinli", &conn) |
| 172 | .await | 174 | .await |
| 173 | .unwrap(); | 175 | .unwrap(); |
| 174 | 176 | ||
| 175 | - let updated_message = message::update(&created_message.id, "Not Tahinli", &db) | 177 | + let updated_message = message::update(&created_message.id, "Not Tahinli", &conn) |
| 176 | .await | 178 | .await |
| 177 | .unwrap(); | 179 | .unwrap(); |
| 178 | - let searched_message = message::read(&created_message.id, &db).await.unwrap(); | 180 | + let searched_message = message::read(&created_message.id, &conn).await.unwrap(); |
| 179 | 181 | ||
| 180 | assert_eq!(created_message.user_id, updated_message.user_id); | 182 | assert_eq!(created_message.user_id, updated_message.user_id); |
| 181 | assert_eq!(created_message.community_id, updated_message.community_id); | 183 | assert_eq!(created_message.community_id, updated_message.community_id); |
| @@ -186,23 +188,27 @@ mod tests { | |||
| 186 | #[tokio::test] | 188 | #[tokio::test] |
| 187 | async fn update_on_missing_message() { | 189 | async fn update_on_missing_message() { |
| 188 | let db = test::get_database().await; | 190 | let db = test::get_database().await; |
| 191 | + let conn = database::connect(&db).await.unwrap(); | ||
| 189 | 192 | ||
| 190 | - let updated_message = message::update("missing", "Tahinli", &db).await; | 193 | + let updated_message = message::update("missing", "Tahinli", &conn).await; |
| 191 | 194 | ||
| 192 | - assert!(matches!(updated_message, Err(Error::NotFound))); | 195 | + assert!(matches!( |
| 196 | + updated_message, | ||
| 197 | + Err(Error::Common(CommonError::NotFound)) | ||
| 198 | + )); | ||
| 193 | } | 199 | } |
| 194 | 200 | ||
| 195 | #[tokio::test] | 201 | #[tokio::test] |
| 196 | async fn delete() { | 202 | async fn delete() { |
| 197 | let db = test::get_database().await; | 203 | let db = test::get_database().await; |
| 198 | - | 204 | + let conn = database::connect(&db).await.unwrap(); |
| 199 | - let user = user::create("Tahinli", &db).await.unwrap(); | 205 | + let user = user::create("Tahinli", "hash", &conn).await.unwrap(); |
| 200 | - let community = community::create("Tahinli", &db).await.unwrap(); | 206 | + let community = community::create("Tahinli", &user.id, &conn).await.unwrap(); |
| 201 | - let created_message = message::create(&user.id, &community.id, "Tahinli", &db) | 207 | + let created_message = message::create(&user.id, &community.id, "Tahinli", &conn) |
| 202 | .await | 208 | .await |
| 203 | .unwrap(); | 209 | .unwrap(); |
| 204 | 210 | ||
| 205 | - let deleted_message = message::delete(&created_message.id, &db).await.unwrap(); | 211 | + let deleted_message = message::delete(&created_message.id, &conn).await.unwrap(); |
| 206 | 212 | ||
| 207 | assert_eq!(created_message, deleted_message); | 213 | assert_eq!(created_message, deleted_message); |
| 208 | } | 214 | } |
crates/server/src/network.rsmodified+128 -119
| @@ -1,40 +1,63 @@ | |||
| 1 | -use std::sync::Arc; | 1 | +use std::sync::{Arc, Mutex}; |
| 2 | 2 | ||
| 3 | use common::{ | 3 | use common::{ |
| 4 | - model::Message, | 4 | + event::Event as Push, |
| 5 | - network::{ | 5 | + model::User, |
| 6 | - AUTHENTICATION_MAX_READ_LENGTH, REQUEST_MAX_READ_LENGTH, receive_request, send_message, | 6 | + network::{REQUEST_MAX_READ_LENGTH, receive_request, send_event, send_response}, |
| 7 | - send_response, | ||
| 8 | - }, | ||
| 9 | - request::Request, | ||
| 10 | - response::Response, | ||
| 11 | }; | 7 | }; |
| 12 | use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; | 8 | use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; |
| 13 | use tokio::{sync::mpsc, task::JoinHandle}; | 9 | use tokio::{sync::mpsc, task::JoinHandle}; |
| 10 | +use tracing::{info, warn}; | ||
| 14 | 11 | ||
| 15 | use crate::{ | 12 | use crate::{ |
| 16 | - authentication::authenticate, database::DB, error::Error, request::handle_request, | 13 | + database::DB, |
| 17 | - user_community, | 14 | + error::Error, |
| 15 | + request::{self, Broadcast}, | ||
| 18 | }; | 16 | }; |
| 19 | 17 | ||
| 20 | const CHANNEL_LENGTH: usize = 2048; | 18 | const CHANNEL_LENGTH: usize = 2048; |
| 21 | const SESSION_LENGTH: usize = 64; | 19 | const SESSION_LENGTH: usize = 64; |
| 22 | 20 | ||
| 23 | -#[cfg(feature = "rcgen")] | 21 | +#[derive(Clone)] |
| 24 | -fn config() -> quinn::ServerConfig { | 22 | +pub enum State { |
| 25 | - use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer}; | 23 | + Anonymous, |
| 24 | + Authenticated { user: User, token: String }, | ||
| 25 | +} | ||
| 26 | 26 | ||
| 27 | - let certificate = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap(); | 27 | +enum Event { |
| 28 | - let certificate_der = CertificateDer::from(certificate.cert); | 28 | + Connected { |
| 29 | - let certificate_key = PrivatePkcs8KeyDer::from(certificate.signing_key.serialize_der()); | 29 | + connection_id: usize, |
| 30 | - quinn::ServerConfig::with_single_cert(vec![certificate_der], certificate_key.into()).unwrap() | 30 | + connection: Connection, |
| 31 | + send_stream: SendStream, | ||
| 32 | + }, | ||
| 33 | + SignedIn { | ||
| 34 | + connection_id: usize, | ||
| 35 | + user_id: String, | ||
| 36 | + }, | ||
| 37 | + SignedOut { | ||
| 38 | + connection_id: usize, | ||
| 39 | + }, | ||
| 40 | + Broadcast(Broadcast), | ||
| 31 | } | 41 | } |
| 32 | 42 | ||
| 33 | -pub async fn serve(server_address: &str, db: &DB) -> Result<(), Error> { | 43 | +struct Session { |
| 34 | - let endpoint = Endpoint::server(config(), server_address.parse()?)?; | 44 | + connection_id: usize, |
| 45 | + user_id: Option<String>, | ||
| 46 | + connection: Connection, | ||
| 47 | + event_sender: mpsc::Sender<Arc<Push>>, | ||
| 48 | + writer: JoinHandle<()>, | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +pub async fn serve( | ||
| 52 | + server_address: &str, | ||
| 53 | + server_config: quinn::ServerConfig, | ||
| 54 | + db: DB, | ||
| 55 | +) -> Result<(), Error> { | ||
| 56 | + let endpoint = Endpoint::server(server_config, server_address.parse()?)?; | ||
| 57 | + info!("listening on {server_address}"); | ||
| 35 | 58 | ||
| 36 | let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH); | 59 | let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH); |
| 37 | - tokio::spawn(the_actor(event_receiver, db.clone())); | 60 | + tokio::spawn(the_actor(event_receiver)); |
| 38 | 61 | ||
| 39 | while let Some(incoming) = endpoint.accept().await { | 62 | while let Some(incoming) = endpoint.accept().await { |
| 40 | tokio::spawn(handle_connection( | 63 | tokio::spawn(handle_connection( |
| @@ -48,83 +71,69 @@ pub async fn serve(server_address: &str, db: &DB) -> Result<(), Error> { | |||
| 48 | } | 71 | } |
| 49 | 72 | ||
| 50 | async fn handle_connection(incoming: Incoming, event_sender: mpsc::Sender<Event>, db: DB) { | 73 | async fn handle_connection(incoming: Incoming, event_sender: mpsc::Sender<Event>, db: DB) { |
| 51 | - match incoming.await { | 74 | + if let Err(error) = serve_connection(incoming, event_sender, db).await { |
| 52 | - Ok(connection) => { | 75 | + warn!("connection: {error}"); |
| 53 | - if let Err(error) = establish_connection(&connection, event_sender, &db).await { | ||
| 54 | - eprintln!("Error = Endpoint Accept | {error}"); | ||
| 55 | - connection.close(0u8.into(), b"kendine iyi bak"); | ||
| 56 | - } | ||
| 57 | - } | ||
| 58 | - Err(error) => eprintln!("Error = Connection | {error}"), | ||
| 59 | } | 76 | } |
| 60 | } | 77 | } |
| 61 | 78 | ||
| 62 | -async fn establish_connection( | 79 | +async fn serve_connection( |
| 63 | - connection: &Connection, | 80 | + incoming: Incoming, |
| 64 | event_sender: mpsc::Sender<Event>, | 81 | event_sender: mpsc::Sender<Event>, |
| 65 | - db: &DB, | 82 | + db: DB, |
| 66 | ) -> Result<(), Error> { | 83 | ) -> Result<(), Error> { |
| 67 | - let (send_stream, receive_stream) = connection.accept_bi().await?; | 84 | + let connection = incoming.await?; |
| 68 | - | 85 | + let send_stream = connection.open_uni().await?; |
| 69 | - let first_request = receive_request(receive_stream, AUTHENTICATION_MAX_READ_LENGTH).await?; | 86 | + let _ = event_sender |
| 70 | - | 87 | + .send(Event::Connected { |
| 71 | - if let Request::Authentication { token } = first_request { | 88 | + connection_id: connection.stable_id(), |
| 72 | - let user = authenticate(&token, db).await?; | 89 | + connection: connection.clone(), |
| 73 | - let response = Response::Authentication(user.clone()); | 90 | + send_stream, |
| 74 | - | 91 | + }) |
| 75 | - tokio::spawn(listen( | 92 | + .await; |
| 76 | - user.id.clone(), | ||
| 77 | - connection.clone(), | ||
| 78 | - event_sender.clone(), | ||
| 79 | - db.clone(), | ||
| 80 | - )); | ||
| 81 | - | ||
| 82 | - send_response(&response, send_stream).await?; | ||
| 83 | - | ||
| 84 | - let send_stream = connection.open_uni().await?; | ||
| 85 | - let _ = event_sender | ||
| 86 | - .send(Event::Joined { | ||
| 87 | - user_id: user.id, | ||
| 88 | - send_stream, | ||
| 89 | - connection: connection.clone(), | ||
| 90 | - }) | ||
| 91 | - .await; | ||
| 92 | 93 | ||
| 93 | - Ok(()) | 94 | + let state = Arc::new(Mutex::new(State::Anonymous)); |
| 94 | - } else { | ||
| 95 | - Err(Error::Common(common::error::Error::Authenticate)) | ||
| 96 | - } | ||
| 97 | -} | ||
| 98 | 95 | ||
| 99 | -async fn listen( | ||
| 100 | - user_id: String, | ||
| 101 | - connection: Connection, | ||
| 102 | - event_sender: mpsc::Sender<Event>, | ||
| 103 | - db: DB, | ||
| 104 | -) { | ||
| 105 | while let Ok((send_stream, receive_stream)) = connection.accept_bi().await { | 96 | while let Ok((send_stream, receive_stream)) = connection.accept_bi().await { |
| 106 | - tokio::spawn(read_and_answer( | 97 | + tokio::spawn(answer( |
| 107 | - user_id.clone(), | 98 | + connection.stable_id(), |
| 99 | + Arc::clone(&state), | ||
| 108 | send_stream, | 100 | send_stream, |
| 109 | receive_stream, | 101 | receive_stream, |
| 110 | event_sender.clone(), | 102 | event_sender.clone(), |
| 111 | db.clone(), | 103 | db.clone(), |
| 112 | )); | 104 | )); |
| 113 | } | 105 | } |
| 106 | + | ||
| 107 | + Ok(()) | ||
| 114 | } | 108 | } |
| 115 | 109 | ||
| 116 | -async fn read_and_answer( | 110 | +async fn answer( |
| 117 | - user_id: String, | 111 | + connection_id: usize, |
| 112 | + state: Arc<Mutex<State>>, | ||
| 118 | send_stream: SendStream, | 113 | send_stream: SendStream, |
| 119 | receive_stream: RecvStream, | 114 | receive_stream: RecvStream, |
| 120 | event_sender: mpsc::Sender<Event>, | 115 | event_sender: mpsc::Sender<Event>, |
| 121 | db: DB, | 116 | db: DB, |
| 122 | ) -> Result<(), Error> { | 117 | ) -> Result<(), Error> { |
| 123 | let request = receive_request(receive_stream, REQUEST_MAX_READ_LENGTH).await?; | 118 | let request = receive_request(receive_stream, REQUEST_MAX_READ_LENGTH).await?; |
| 124 | - let response = handle_request(&user_id, request, &db).await; | ||
| 125 | 119 | ||
| 126 | - if let Response::CreateMessage(message) = &response { | 120 | + let before = signed_user_id(&state); |
| 127 | - let _ = event_sender.send(Event::Sent(message.clone())).await; | 121 | + let (response, broadcast) = request::handle(request, &state, &db).await; |
| 122 | + let after = signed_user_id(&state); | ||
| 123 | + | ||
| 124 | + if before != after { | ||
| 125 | + let event = match after { | ||
| 126 | + Some(user_id) => Event::SignedIn { | ||
| 127 | + connection_id, | ||
| 128 | + user_id, | ||
| 129 | + }, | ||
| 130 | + None => Event::SignedOut { connection_id }, | ||
| 131 | + }; | ||
| 132 | + let _ = event_sender.send(event).await; | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + if let Some(broadcast) = broadcast { | ||
| 136 | + let _ = event_sender.send(Event::Broadcast(broadcast)).await; | ||
| 128 | } | 137 | } |
| 129 | 138 | ||
| 130 | send_response(&response, send_stream).await?; | 139 | send_response(&response, send_stream).await?; |
| @@ -132,35 +141,23 @@ async fn read_and_answer( | |||
| 132 | Ok(()) | 141 | Ok(()) |
| 133 | } | 142 | } |
| 134 | 143 | ||
| 135 | -enum Event { | 144 | +fn signed_user_id(state: &Mutex<State>) -> Option<String> { |
| 136 | - Joined { | 145 | + match &*state.lock().unwrap() { |
| 137 | - user_id: String, | 146 | + State::Anonymous => None, |
| 138 | - send_stream: SendStream, | 147 | + State::Authenticated { user, .. } => Some(user.id.clone()), |
| 139 | - connection: Connection, | 148 | + } |
| 140 | - }, | ||
| 141 | - Sent(Message), | ||
| 142 | -} | ||
| 143 | - | ||
| 144 | -struct Session { | ||
| 145 | - pub user_id: String, | ||
| 146 | - pub connection: Connection, | ||
| 147 | - pub message_sender: mpsc::Sender<Arc<Message>>, | ||
| 148 | - pub writer: JoinHandle<()>, | ||
| 149 | } | 149 | } |
| 150 | 150 | ||
| 151 | -async fn write_session( | 151 | +async fn write_session(mut event_receiver: mpsc::Receiver<Arc<Push>>, mut send_stream: SendStream) { |
| 152 | - mut message_receiver: mpsc::Receiver<Arc<Message>>, | 152 | + while let Some(event) = event_receiver.recv().await { |
| 153 | - mut send_stream: SendStream, | 153 | + if let Err(error) = send_event(&event, &mut send_stream).await { |
| 154 | -) { | 154 | + warn!("session write: {error}"); |
| 155 | - while let Some(message) = message_receiver.recv().await { | ||
| 156 | - if let Err(error) = send_message(&message, &mut send_stream).await { | ||
| 157 | - eprintln!("Error = Message | Session Write | {error}"); | ||
| 158 | break; | 155 | break; |
| 159 | } | 156 | } |
| 160 | } | 157 | } |
| 161 | } | 158 | } |
| 162 | 159 | ||
| 163 | -async fn the_actor(mut event_receiver: mpsc::Receiver<Event>, db: DB) { | 160 | +async fn the_actor(mut event_receiver: mpsc::Receiver<Event>) { |
| 164 | let mut sessions: Vec<Session> = Vec::new(); | 161 | let mut sessions: Vec<Session> = Vec::new(); |
| 165 | 162 | ||
| 166 | while let Some(event) = event_receiver.recv().await { | 163 | while let Some(event) = event_receiver.recv().await { |
| @@ -169,44 +166,56 @@ async fn the_actor(mut event_receiver: mpsc::Receiver<Event>, db: DB) { | |||
| 169 | }); | 166 | }); |
| 170 | 167 | ||
| 171 | match event { | 168 | match event { |
| 172 | - Event::Joined { | 169 | + Event::Connected { |
| 173 | - user_id, | 170 | + connection_id, |
| 174 | - send_stream, | ||
| 175 | connection, | 171 | connection, |
| 172 | + send_stream, | ||
| 176 | } => { | 173 | } => { |
| 177 | - let (message_sender, message_receiver) = mpsc::channel(SESSION_LENGTH); | 174 | + let (event_sender, event_receiver) = mpsc::channel(SESSION_LENGTH); |
| 178 | - let writer = tokio::spawn(write_session(message_receiver, send_stream)); | 175 | + let writer = tokio::spawn(write_session(event_receiver, send_stream)); |
| 179 | 176 | ||
| 180 | sessions.push(Session { | 177 | sessions.push(Session { |
| 181 | - user_id, | 178 | + connection_id, |
| 179 | + user_id: None, | ||
| 182 | connection, | 180 | connection, |
| 183 | - message_sender, | 181 | + event_sender, |
| 184 | writer, | 182 | writer, |
| 185 | }); | 183 | }); |
| 186 | } | 184 | } |
| 187 | - Event::Sent(message) => { | 185 | + Event::SignedIn { |
| 188 | - let Ok(users) = user_community::users_in(&message.community_id, &db).await else { | 186 | + connection_id, |
| 189 | - eprintln!( | 187 | + user_id, |
| 190 | - "Error = Message | Community Member Read | {}", | 188 | + } => { |
| 191 | - message.community_id | 189 | + if let Some(session) = sessions |
| 192 | - ); | 190 | + .iter_mut() |
| 193 | - continue; | 191 | + .find(|session| session.connection_id == connection_id) |
| 194 | - }; | 192 | + { |
| 195 | - | 193 | + session.user_id = Some(user_id); |
| 196 | - let message = Arc::new(message); | 194 | + } |
| 195 | + } | ||
| 196 | + Event::SignedOut { connection_id } => { | ||
| 197 | + if let Some(session) = sessions | ||
| 198 | + .iter_mut() | ||
| 199 | + .find(|session| session.connection_id == connection_id) | ||
| 200 | + { | ||
| 201 | + session.user_id = None; | ||
| 202 | + } | ||
| 203 | + } | ||
| 204 | + Event::Broadcast(broadcast) => { | ||
| 205 | + let event = Arc::new(broadcast.event); | ||
| 197 | 206 | ||
| 198 | sessions.retain(|session| { | 207 | sessions.retain(|session| { |
| 199 | - if !users.contains(&session.user_id) { | 208 | + let Some(user_id) = &session.user_id else { |
| 209 | + return true; | ||
| 210 | + }; | ||
| 211 | + if !broadcast.user_ids.contains(user_id) { | ||
| 200 | return true; | 212 | return true; |
| 201 | } | 213 | } |
| 202 | 214 | ||
| 203 | - match session.message_sender.try_send(Arc::clone(&message)) { | 215 | + match session.event_sender.try_send(Arc::clone(&event)) { |
| 204 | Ok(()) => true, | 216 | Ok(()) => true, |
| 205 | Err(mpsc::error::TrySendError::Full(_)) => { | 217 | Err(mpsc::error::TrySendError::Full(_)) => { |
| 206 | - eprintln!( | 218 | + warn!("session buffer is full {user_id}"); |
| 207 | - "Error = Message | Session Buffer is Full | {}", | ||
| 208 | - session.user_id | ||
| 209 | - ); | ||
| 210 | session.writer.abort(); | 219 | session.writer.abort(); |
| 211 | false | 220 | false |
| 212 | } | 221 | } |
crates/server/src/request.rsmodified+322 -78
| @@ -1,110 +1,354 @@ | |||
| 1 | -use common::{request::Request, response::Response}; | 1 | +use std::sync::Mutex; |
| 2 | + | ||
| 3 | +use common::{ | ||
| 4 | + error::Error as CommonError, | ||
| 5 | + event::Event, | ||
| 6 | + model::{Community, Message, User}, | ||
| 7 | + request::Request, | ||
| 8 | + response::Response, | ||
| 9 | +}; | ||
| 2 | 10 | ||
| 3 | use crate::{ | 11 | use crate::{ |
| 4 | - authentication::authenticate, community, database::DB, error::Error, message, user, | 12 | + authentication, community, |
| 5 | - user_community, | 13 | + database::{self, DB}, |
| 14 | + error::Error, | ||
| 15 | + message, | ||
| 16 | + network::State, | ||
| 17 | + user, user_community, | ||
| 6 | }; | 18 | }; |
| 7 | 19 | ||
| 8 | -pub async fn handle_request(session_user_id: &str, request: Request, db: &DB) -> Response { | 20 | +pub struct Broadcast { |
| 9 | - match handle(session_user_id, request, db).await { | 21 | + pub event: Event, |
| 10 | - Ok(response) => response, | 22 | + pub user_ids: Vec<String>, |
| 11 | - Err(error) => Response::Error(error.into()), | 23 | +} |
| 24 | + | ||
| 25 | +type Outcome = (Response, Option<Broadcast>); | ||
| 26 | + | ||
| 27 | +pub async fn handle(request: Request, state: &Mutex<State>, db: &DB) -> Outcome { | ||
| 28 | + match dispatch(request, state, db).await { | ||
| 29 | + Ok(outcome) => outcome, | ||
| 30 | + Err(error) => (Response::Error(error.into()), None), | ||
| 12 | } | 31 | } |
| 13 | } | 32 | } |
| 14 | 33 | ||
| 15 | -async fn handle(session_user_id: &str, request: Request, db: &DB) -> Result<Response, Error> { | 34 | +async fn dispatch(request: Request, state: &Mutex<State>, db: &DB) -> Result<Outcome, Error> { |
| 16 | - let response = match request { | 35 | + let mut conn = database::connect(db).await?; |
| 17 | - Request::Authentication { token } => { | 36 | + |
| 18 | - Response::Authentication(authenticate(&token, db).await?) | 37 | + let outcome = match request { |
| 38 | + Request::Register { username, password } => { | ||
| 39 | + let (user, token) = authentication::register(&username, &password, &mut conn).await?; | ||
| 40 | + sign_in(state, user, token) | ||
| 41 | + } | ||
| 42 | + Request::Login { username, password } => { | ||
| 43 | + let (user, token) = authentication::login(&username, &password, &conn).await?; | ||
| 44 | + sign_in(state, user, token) | ||
| 45 | + } | ||
| 46 | + Request::Resume { token } => { | ||
| 47 | + let user = authentication::resume(&token, &conn).await?; | ||
| 48 | + sign_in(state, user, token) | ||
| 49 | + } | ||
| 50 | + Request::Logout => { | ||
| 51 | + let (_, token) = authenticated(state)?; | ||
| 52 | + authentication::logout(&token, &conn).await?; | ||
| 53 | + set_state(state, State::Anonymous); | ||
| 54 | + (Response::Done, None) | ||
| 19 | } | 55 | } |
| 20 | - Request::Deauthentication { token } => { | 56 | + Request::ReadUser { user_id } => { |
| 21 | - Response::Deauthentication(authenticate(&token, db).await?) | 57 | + authenticated(state)?; |
| 58 | + (Response::User(user::read(&user_id, &conn).await?), None) | ||
| 22 | } | 59 | } |
| 23 | - Request::CreateUser { username } => { | 60 | + Request::UpdateUser { username } => { |
| 24 | - Response::CreateUser(user::create(&username, db).await?) | 61 | + let (me, token) = authenticated(state)?; |
| 62 | + let user = user::update(&me.id, &username, &conn).await?; | ||
| 63 | + set_state( | ||
| 64 | + state, | ||
| 65 | + State::Authenticated { | ||
| 66 | + user: user.clone(), | ||
| 67 | + token, | ||
| 68 | + }, | ||
| 69 | + ); | ||
| 70 | + (Response::User(user), None) | ||
| 25 | } | 71 | } |
| 26 | - Request::ReadUser { user_id } => Response::ReadUser(user::read(&user_id, db).await?), | 72 | + Request::DeleteUser => { |
| 27 | - Request::UpdateUser { user_id, username } => { | 73 | + let (me, _) = authenticated(state)?; |
| 28 | - Response::UpdateUser(user::update(&user_id, &username, db).await?) | 74 | + let user = user::delete(&me.id, &conn).await?; |
| 75 | + set_state(state, State::Anonymous); | ||
| 76 | + (Response::User(user), None) | ||
| 29 | } | 77 | } |
| 30 | - Request::DeleteUser { user_id } => Response::DeleteUser(user::delete(&user_id, db).await?), | ||
| 31 | Request::CreateCommunity { name } => { | 78 | Request::CreateCommunity { name } => { |
| 32 | - let community = community::create(&name, db).await?; | 79 | + let (me, _) = authenticated(state)?; |
| 33 | - user_community::join(session_user_id, &community.id, db).await?; | 80 | + let tx = conn.transaction().await?; |
| 34 | - Response::CreateCommunity(community) | 81 | + let community = community::create(&name, &me.id, &tx).await?; |
| 82 | + user_community::join(&me.id, &community.id, &tx).await?; | ||
| 83 | + tx.commit().await?; | ||
| 84 | + (Response::Community(community), None) | ||
| 35 | } | 85 | } |
| 36 | Request::ReadCommunity { community_id } => { | 86 | Request::ReadCommunity { community_id } => { |
| 37 | - Response::ReadCommunity(community::read(&community_id, db).await?) | 87 | + authenticated(state)?; |
| 88 | + ( | ||
| 89 | + Response::Community(community::read(&community_id, &conn).await?), | ||
| 90 | + None, | ||
| 91 | + ) | ||
| 38 | } | 92 | } |
| 39 | Request::UpdateCommunity { community_id, name } => { | 93 | Request::UpdateCommunity { community_id, name } => { |
| 40 | - Response::UpdateCommunity(community::update(&community_id, &name, db).await?) | 94 | + let (me, _) = authenticated(state)?; |
| 95 | + let existing = community::read(&community_id, &conn).await?; | ||
| 96 | + ensure_owner(&existing, &me)?; | ||
| 97 | + let updated = community::update(&community_id, &name, &conn).await?; | ||
| 98 | + let members = user_community::members(&community_id, &conn).await?; | ||
| 99 | + let event = Event::CommunityUpdated(updated.clone()); | ||
| 100 | + (Response::Community(updated), broadcast(event, &members)) | ||
| 41 | } | 101 | } |
| 42 | Request::DeleteCommunity { community_id } => { | 102 | Request::DeleteCommunity { community_id } => { |
| 43 | - Response::DeleteCommunity(community::delete(&community_id, db).await?) | 103 | + let (me, _) = authenticated(state)?; |
| 104 | + let existing = community::read(&community_id, &conn).await?; | ||
| 105 | + ensure_owner(&existing, &me)?; | ||
| 106 | + let tx = conn.transaction().await?; | ||
| 107 | + let members = user_community::members(&community_id, &tx).await?; | ||
| 108 | + let deleted = community::delete(&community_id, &tx).await?; | ||
| 109 | + tx.commit().await?; | ||
| 110 | + let event = Event::CommunityDeleted { | ||
| 111 | + community_id: deleted.id.clone(), | ||
| 112 | + }; | ||
| 113 | + (Response::Community(deleted), broadcast(event, &members)) | ||
| 44 | } | 114 | } |
| 45 | - Request::CreateMessage { | 115 | + Request::SearchCommunity { name } => { |
| 46 | - user_id, | 116 | + authenticated(state)?; |
| 47 | - community_id, | 117 | + ( |
| 48 | - body, | 118 | + Response::Communities(community::read_by_name(&name, &conn).await?), |
| 49 | - } => { | 119 | + None, |
| 50 | - user::read(&user_id, db).await?; | 120 | + ) |
| 51 | - community::read(&community_id, db).await?; | 121 | + } |
| 52 | - Response::CreateMessage(message::create(&user_id, &community_id, &body, db).await?) | 122 | + Request::JoinCommunity { community_id } => { |
| 123 | + let (me, _) = authenticated(state)?; | ||
| 124 | + let existing = community::read(&community_id, &conn).await?; | ||
| 125 | + let tx = conn.transaction().await?; | ||
| 126 | + if user_community::is_member(&me.id, &community_id, &tx).await? { | ||
| 127 | + return Err(CommonError::Taken.into()); | ||
| 128 | + } | ||
| 129 | + user_community::join(&me.id, &community_id, &tx).await?; | ||
| 130 | + let members = user_community::members(&community_id, &tx).await?; | ||
| 131 | + tx.commit().await?; | ||
| 132 | + let event = Event::MemberJoined { | ||
| 133 | + community_id, | ||
| 134 | + user: me, | ||
| 135 | + }; | ||
| 136 | + (Response::Community(existing), broadcast(event, &members)) | ||
| 137 | + } | ||
| 138 | + Request::LeaveCommunity { community_id } => { | ||
| 139 | + let (me, _) = authenticated(state)?; | ||
| 140 | + let tx = conn.transaction().await?; | ||
| 141 | + user_community::leave(&me.id, &community_id, &tx).await?; | ||
| 142 | + let members = user_community::members(&community_id, &tx).await?; | ||
| 143 | + if members.is_empty() { | ||
| 144 | + community::delete(&community_id, &tx).await?; | ||
| 145 | + } | ||
| 146 | + tx.commit().await?; | ||
| 147 | + let event = Event::MemberLeft { | ||
| 148 | + community_id, | ||
| 149 | + user_id: me.id, | ||
| 150 | + }; | ||
| 151 | + (Response::Done, broadcast(event, &members)) | ||
| 152 | + } | ||
| 153 | + Request::Communities => { | ||
| 154 | + let (me, _) = authenticated(state)?; | ||
| 155 | + ( | ||
| 156 | + Response::Communities(community::communities_of(&me.id, &conn).await?), | ||
| 157 | + None, | ||
| 158 | + ) | ||
| 53 | } | 159 | } |
| 54 | - Request::ReadMessage { message_id } => { | 160 | + Request::Members { community_id } => { |
| 55 | - Response::ReadMessage(message::read(&message_id, db).await?) | 161 | + let (me, _) = authenticated(state)?; |
| 162 | + user_community::ensure_member(&me.id, &community_id, &conn).await?; | ||
| 163 | + ( | ||
| 164 | + Response::Members(user_community::members(&community_id, &conn).await?), | ||
| 165 | + None, | ||
| 166 | + ) | ||
| 167 | + } | ||
| 168 | + Request::CreateMessage { community_id, body } => { | ||
| 169 | + let (me, _) = authenticated(state)?; | ||
| 170 | + user_community::ensure_member(&me.id, &community_id, &conn).await?; | ||
| 171 | + let created = message::create(&me.id, &community_id, &body, &conn).await?; | ||
| 172 | + let members = user_community::members(&community_id, &conn).await?; | ||
| 173 | + let event = Event::MessageCreated(created.clone()); | ||
| 174 | + (Response::Message(created), broadcast(event, &members)) | ||
| 56 | } | 175 | } |
| 57 | Request::UpdateMessage { message_id, body } => { | 176 | Request::UpdateMessage { message_id, body } => { |
| 58 | - Response::UpdateMessage(message::update(&message_id, &body, db).await?) | 177 | + let (me, _) = authenticated(state)?; |
| 178 | + let existing = message::read(&message_id, &conn).await?; | ||
| 179 | + ensure_author(&existing, &me)?; | ||
| 180 | + let updated = message::update(&message_id, &body, &conn).await?; | ||
| 181 | + let members = user_community::members(&updated.community_id, &conn).await?; | ||
| 182 | + let event = Event::MessageUpdated(updated.clone()); | ||
| 183 | + (Response::Message(updated), broadcast(event, &members)) | ||
| 59 | } | 184 | } |
| 60 | Request::DeleteMessage { message_id } => { | 185 | Request::DeleteMessage { message_id } => { |
| 61 | - Response::DeleteMessage(message::delete(&message_id, db).await?) | 186 | + let (me, _) = authenticated(state)?; |
| 187 | + let existing = message::read(&message_id, &conn).await?; | ||
| 188 | + ensure_author(&existing, &me)?; | ||
| 189 | + let deleted = message::delete(&message_id, &conn).await?; | ||
| 190 | + let members = user_community::members(&deleted.community_id, &conn).await?; | ||
| 191 | + let event = Event::MessageDeleted(deleted.clone()); | ||
| 192 | + (Response::Message(deleted), broadcast(event, &members)) | ||
| 62 | } | 193 | } |
| 63 | Request::ReadMessages { | 194 | Request::ReadMessages { |
| 64 | community_id, | 195 | community_id, |
| 65 | - marker, | 196 | + before, |
| 66 | - limit, | ||
| 67 | - } => Response::ReadMessages(message::read_page(&community_id, &marker, limit, db).await?), | ||
| 68 | - Request::JoinCommunity { | ||
| 69 | - user_id, | ||
| 70 | - community_id, | ||
| 71 | - } => { | ||
| 72 | - user_community::join(&user_id, &community_id, db).await?; | ||
| 73 | - Response::JoinCommunity | ||
| 74 | - } | ||
| 75 | - Request::LeaveCommunity { | ||
| 76 | - user_id, | ||
| 77 | - community_id, | ||
| 78 | - } => { | ||
| 79 | - user_community::leave(&user_id, &community_id, db).await?; | ||
| 80 | - if user_community::users_in(&community_id, db) | ||
| 81 | - .await? | ||
| 82 | - .is_empty() | ||
| 83 | - { | ||
| 84 | - community::delete(&community_id, db).await?; | ||
| 85 | - } | ||
| 86 | - Response::LeaveCommunity | ||
| 87 | - } | ||
| 88 | - Request::IsUserIn { | ||
| 89 | - user_id, | ||
| 90 | - community_id, | ||
| 91 | } => { | 197 | } => { |
| 92 | - user::read(&user_id, db).await?; | 198 | + let (me, _) = authenticated(state)?; |
| 93 | - community::read(&community_id, db).await?; | 199 | + user_community::ensure_member(&me.id, &community_id, &conn).await?; |
| 94 | - Response::IsUserIn(user_community::is_user_in(&user_id, &community_id, db).await?) | 200 | + let messages = message::read_page(&community_id, before.as_deref(), &conn).await?; |
| 95 | - } | 201 | + (Response::Messages(messages), None) |
| 96 | - Request::UsersIn { community_id } => { | ||
| 97 | - community::read(&community_id, db).await?; | ||
| 98 | - Response::UsersIn(user_community::users_in(&community_id, db).await?) | ||
| 99 | - } | ||
| 100 | - Request::CommunitiesOf { user_id } => { | ||
| 101 | - user::read(&user_id, db).await?; | ||
| 102 | - Response::CommunitiesOf(user_community::communities_of(&user_id, db).await?) | ||
| 103 | - } | ||
| 104 | - Request::SearchCommunity { name } => { | ||
| 105 | - Response::SearchCommunity(community::read_by_name(&name, db).await?) | ||
| 106 | } | 202 | } |
| 107 | }; | 203 | }; |
| 108 | 204 | ||
| 109 | - Ok(response) | 205 | + Ok(outcome) |
| 206 | +} | ||
| 207 | + | ||
| 208 | +fn sign_in(state: &Mutex<State>, user: User, token: String) -> Outcome { | ||
| 209 | + set_state( | ||
| 210 | + state, | ||
| 211 | + State::Authenticated { | ||
| 212 | + user: user.clone(), | ||
| 213 | + token: token.clone(), | ||
| 214 | + }, | ||
| 215 | + ); | ||
| 216 | + | ||
| 217 | + (Response::Session { user, token }, None) | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +fn set_state(state: &Mutex<State>, new_state: State) { | ||
| 221 | + *state.lock().unwrap() = new_state; | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +fn authenticated(state: &Mutex<State>) -> Result<(User, String), Error> { | ||
| 225 | + match state.lock().unwrap().clone() { | ||
| 226 | + State::Anonymous => Err(CommonError::Unauthenticated.into()), | ||
| 227 | + State::Authenticated { user, token } => Ok((user, token)), | ||
| 228 | + } | ||
| 229 | +} | ||
| 230 | + | ||
| 231 | +fn ensure_owner(community: &Community, me: &User) -> Result<(), Error> { | ||
| 232 | + if community.owner_id != me.id { | ||
| 233 | + return Err(CommonError::Forbidden.into()); | ||
| 234 | + } | ||
| 235 | + | ||
| 236 | + Ok(()) | ||
| 237 | +} | ||
| 238 | + | ||
| 239 | +fn ensure_author(message: &Message, me: &User) -> Result<(), Error> { | ||
| 240 | + if message.user_id != me.id { | ||
| 241 | + return Err(CommonError::Forbidden.into()); | ||
| 242 | + } | ||
| 243 | + | ||
| 244 | + Ok(()) | ||
| 245 | +} | ||
| 246 | + | ||
| 247 | +fn broadcast(event: Event, members: &[User]) -> Option<Broadcast> { | ||
| 248 | + Some(Broadcast { | ||
| 249 | + event, | ||
| 250 | + user_ids: members.iter().map(|user| user.id.clone()).collect(), | ||
| 251 | + }) | ||
| 252 | +} | ||
| 253 | + | ||
| 254 | +#[cfg(test)] | ||
| 255 | +mod tests { | ||
| 256 | + use std::sync::Mutex; | ||
| 257 | + | ||
| 258 | + use common::{error::Error as CommonError, request::Request, response::Response}; | ||
| 259 | + | ||
| 260 | + use crate::{ | ||
| 261 | + database::{self, DB}, | ||
| 262 | + message, | ||
| 263 | + network::State, | ||
| 264 | + request::handle, | ||
| 265 | + test, | ||
| 266 | + }; | ||
| 267 | + | ||
| 268 | + async fn signed_in(username: &str, db: &DB) -> Mutex<State> { | ||
| 269 | + let state = Mutex::new(State::Anonymous); | ||
| 270 | + handle( | ||
| 271 | + Request::Register { | ||
| 272 | + username: username.to_string(), | ||
| 273 | + password: "password".to_string(), | ||
| 274 | + }, | ||
| 275 | + &state, | ||
| 276 | + db, | ||
| 277 | + ) | ||
| 278 | + .await; | ||
| 279 | + | ||
| 280 | + state | ||
| 281 | + } | ||
| 282 | + | ||
| 283 | + #[tokio::test] | ||
| 284 | + async fn forbidden_community_update() { | ||
| 285 | + let db = test::get_database().await; | ||
| 286 | + let owner = signed_in("Owner", &db).await; | ||
| 287 | + let other = signed_in("Other", &db).await; | ||
| 288 | + let (Response::Community(community), _) = handle( | ||
| 289 | + Request::CreateCommunity { | ||
| 290 | + name: "The Community".to_string(), | ||
| 291 | + }, | ||
| 292 | + &owner, | ||
| 293 | + &db, | ||
| 294 | + ) | ||
| 295 | + .await | ||
| 296 | + else { | ||
| 297 | + panic!("community not created"); | ||
| 298 | + }; | ||
| 299 | + | ||
| 300 | + let (response, _) = handle( | ||
| 301 | + Request::UpdateCommunity { | ||
| 302 | + community_id: community.id, | ||
| 303 | + name: "Renamed".to_string(), | ||
| 304 | + }, | ||
| 305 | + &other, | ||
| 306 | + &db, | ||
| 307 | + ) | ||
| 308 | + .await; | ||
| 309 | + | ||
| 310 | + assert!(matches!(response, Response::Error(CommonError::Forbidden))); | ||
| 311 | + } | ||
| 312 | + | ||
| 313 | + #[tokio::test] | ||
| 314 | + async fn delete_community_removes_messages() { | ||
| 315 | + let db = test::get_database().await; | ||
| 316 | + let owner = signed_in("Owner", &db).await; | ||
| 317 | + let (Response::Community(community), _) = handle( | ||
| 318 | + Request::CreateCommunity { | ||
| 319 | + name: "The Community".to_string(), | ||
| 320 | + }, | ||
| 321 | + &owner, | ||
| 322 | + &db, | ||
| 323 | + ) | ||
| 324 | + .await | ||
| 325 | + else { | ||
| 326 | + panic!("community not created"); | ||
| 327 | + }; | ||
| 328 | + handle( | ||
| 329 | + Request::CreateMessage { | ||
| 330 | + community_id: community.id.clone(), | ||
| 331 | + body: "Tahinli".to_string(), | ||
| 332 | + }, | ||
| 333 | + &owner, | ||
| 334 | + &db, | ||
| 335 | + ) | ||
| 336 | + .await; | ||
| 337 | + | ||
| 338 | + handle( | ||
| 339 | + Request::DeleteCommunity { | ||
| 340 | + community_id: community.id.clone(), | ||
| 341 | + }, | ||
| 342 | + &owner, | ||
| 343 | + &db, | ||
| 344 | + ) | ||
| 345 | + .await; | ||
| 346 | + | ||
| 347 | + let conn = database::connect(&db).await.unwrap(); | ||
| 348 | + let remaining = message::read_page(&community.id, None, &conn) | ||
| 349 | + .await | ||
| 350 | + .unwrap(); | ||
| 351 | + | ||
| 352 | + assert!(remaining.is_empty()); | ||
| 353 | + } | ||
| 110 | } | 354 | } |
crates/server/src/test.rsmodified+1 -4
| @@ -1,8 +1,5 @@ | |||
| 1 | use crate::database::{self, DB}; | 1 | use crate::database::{self, DB}; |
| 2 | 2 | ||
| 3 | pub async fn get_database() -> DB { | 3 | pub async fn get_database() -> DB { |
| 4 | - let database = database::connect(":memory:").await.unwrap(); | 4 | + database::open(":memory:").await.unwrap() |
| 5 | - database::migrate(&database).await.unwrap(); | ||
| 6 | - | ||
| 7 | - database | ||
| 8 | } | 5 | } |
crates/server/src/user.rsmodified+71 -47
| @@ -1,92 +1,109 @@ | |||
| 1 | -use common::{model::User, validate::validate_username}; | 1 | +use common::{error::Error as CommonError, model::User, validate::validate_username}; |
| 2 | -use turso::Row; | 2 | +use turso::{Connection, Row}; |
| 3 | 3 | ||
| 4 | -use crate::{ | 4 | +use crate::{database::new_id, error::Error}; |
| 5 | - database::{DB, new_id}, | ||
| 6 | - error::Error, | ||
| 7 | -}; | ||
| 8 | 5 | ||
| 9 | -fn from_row(row: &Row) -> Result<User, Error> { | 6 | +pub fn from_row(row: &Row) -> Result<User, Error> { |
| 10 | Ok(User { | 7 | Ok(User { |
| 11 | id: row.get(0)?, | 8 | id: row.get(0)?, |
| 12 | username: row.get(1)?, | 9 | username: row.get(1)?, |
| 13 | }) | 10 | }) |
| 14 | } | 11 | } |
| 15 | 12 | ||
| 16 | -pub async fn create(username: &str, db: &DB) -> Result<User, Error> { | 13 | +pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result<User, Error> { |
| 17 | - validate_username(username)?; | 14 | + let mut rows = conn |
| 18 | - | ||
| 19 | - let mut rows = db | ||
| 20 | .query( | 15 | .query( |
| 21 | - "INSERT INTO user (id, username) VALUES (?1, ?2) RETURNING id, username", | 16 | + "INSERT INTO user (id, username, password_hash) VALUES (?1, ?2, ?3) RETURNING id, username", |
| 22 | - (new_id(), username), | 17 | + (new_id(), username, password_hash), |
| 23 | ) | 18 | ) |
| 24 | .await?; | 19 | .await?; |
| 25 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 20 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 26 | 21 | ||
| 27 | from_row(&row) | 22 | from_row(&row) |
| 28 | } | 23 | } |
| 29 | 24 | ||
| 30 | -pub async fn read(user_id: &str, db: &DB) -> Result<User, Error> { | 25 | +pub async fn read(user_id: &str, conn: &Connection) -> Result<User, Error> { |
| 31 | - let mut rows = db | 26 | + let mut rows = conn |
| 32 | .query("SELECT id, username FROM user WHERE id = ?1", (user_id,)) | 27 | .query("SELECT id, username FROM user WHERE id = ?1", (user_id,)) |
| 33 | .await?; | 28 | .await?; |
| 34 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 29 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 35 | 30 | ||
| 36 | from_row(&row) | 31 | from_row(&row) |
| 37 | } | 32 | } |
| 38 | 33 | ||
| 39 | -pub async fn read_by_username(username: &str, db: &DB) -> Result<Vec<User>, Error> { | 34 | +pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> { |
| 40 | - let mut rows = db | 35 | + let mut rows = conn |
| 41 | .query( | 36 | .query( |
| 42 | - "SELECT id, username FROM user WHERE username = ?1 ORDER BY id", | 37 | + "SELECT id, username FROM user WHERE username = ?1", |
| 43 | (username,), | 38 | (username,), |
| 44 | ) | 39 | ) |
| 45 | .await?; | 40 | .await?; |
| 46 | 41 | ||
| 47 | - let mut users = Vec::new(); | 42 | + rows.next().await?.as_ref().map(from_row).transpose() |
| 48 | - while let Some(row) = rows.next().await? { | 43 | +} |
| 49 | - users.push(from_row(&row)?); | 44 | + |
| 50 | - } | 45 | +pub async fn credentials( |
| 46 | + username: &str, | ||
| 47 | + conn: &Connection, | ||
| 48 | +) -> Result<Option<(User, String)>, Error> { | ||
| 49 | + let mut rows = conn | ||
| 50 | + .query( | ||
| 51 | + "SELECT id, username, password_hash FROM user WHERE username = ?1", | ||
| 52 | + (username,), | ||
| 53 | + ) | ||
| 54 | + .await?; | ||
| 55 | + let Some(row) = rows.next().await? else { | ||
| 56 | + return Ok(None); | ||
| 57 | + }; | ||
| 51 | 58 | ||
| 52 | - Ok(users) | 59 | + Ok(Some((from_row(&row)?, row.get(2)?))) |
| 53 | } | 60 | } |
| 54 | 61 | ||
| 55 | -pub async fn update(user_id: &str, username: &str, db: &DB) -> Result<User, Error> { | 62 | +pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<User, Error> { |
| 56 | validate_username(username)?; | 63 | validate_username(username)?; |
| 57 | 64 | ||
| 58 | - let mut rows = db | 65 | + if by_username(username, conn) |
| 66 | + .await? | ||
| 67 | + .is_some_and(|existing| existing.id != user_id) | ||
| 68 | + { | ||
| 69 | + return Err(CommonError::Taken.into()); | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + let mut rows = conn | ||
| 59 | .query( | 73 | .query( |
| 60 | "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING id, username", | 74 | "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING id, username", |
| 61 | (user_id, username), | 75 | (user_id, username), |
| 62 | ) | 76 | ) |
| 63 | .await?; | 77 | .await?; |
| 64 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 78 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 65 | 79 | ||
| 66 | from_row(&row) | 80 | from_row(&row) |
| 67 | } | 81 | } |
| 68 | 82 | ||
| 69 | -pub async fn delete(user_id: &str, db: &DB) -> Result<User, Error> { | 83 | +pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> { |
| 70 | - let mut rows = db | 84 | + let mut rows = conn |
| 71 | .query( | 85 | .query( |
| 72 | "DELETE FROM user WHERE id = ?1 RETURNING id, username", | 86 | "DELETE FROM user WHERE id = ?1 RETURNING id, username", |
| 73 | (user_id,), | 87 | (user_id,), |
| 74 | ) | 88 | ) |
| 75 | .await?; | 89 | .await?; |
| 76 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 90 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 77 | 91 | ||
| 78 | from_row(&row) | 92 | from_row(&row) |
| 79 | } | 93 | } |
| 80 | 94 | ||
| 81 | #[cfg(test)] | 95 | #[cfg(test)] |
| 82 | mod tests { | 96 | mod tests { |
| 83 | - use crate::{error::Error, test, user}; | 97 | + use common::error::Error as CommonError; |
| 98 | + | ||
| 99 | + use crate::{database, error::Error, test, user}; | ||
| 84 | 100 | ||
| 85 | #[tokio::test] | 101 | #[tokio::test] |
| 86 | async fn create() { | 102 | async fn create() { |
| 87 | let db = test::get_database().await; | 103 | let db = test::get_database().await; |
| 104 | + let conn = database::connect(&db).await.unwrap(); | ||
| 88 | 105 | ||
| 89 | - let user = user::create("Tahinli", &db).await.unwrap(); | 106 | + let user = user::create("Tahinli", "hash", &conn).await.unwrap(); |
| 90 | 107 | ||
| 91 | assert_eq!("Tahinli", user.username); | 108 | assert_eq!("Tahinli", user.username); |
| 92 | } | 109 | } |
| @@ -94,9 +111,10 @@ mod tests { | |||
| 94 | #[tokio::test] | 111 | #[tokio::test] |
| 95 | async fn read() { | 112 | async fn read() { |
| 96 | let db = test::get_database().await; | 113 | let db = test::get_database().await; |
| 114 | + let conn = database::connect(&db).await.unwrap(); | ||
| 97 | 115 | ||
| 98 | - let created_user = user::create("Tahinli", &db).await.unwrap(); | 116 | + let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); |
| 99 | - let searched_user = user::read(&created_user.id, &db).await.unwrap(); | 117 | + let searched_user = user::read(&created_user.id, &conn).await.unwrap(); |
| 100 | 118 | ||
| 101 | assert_eq!(created_user, searched_user); | 119 | assert_eq!(created_user, searched_user); |
| 102 | } | 120 | } |
| @@ -104,25 +122,26 @@ mod tests { | |||
| 104 | #[tokio::test] | 122 | #[tokio::test] |
| 105 | async fn read_by_username() { | 123 | async fn read_by_username() { |
| 106 | let db = test::get_database().await; | 124 | let db = test::get_database().await; |
| 125 | + let conn = database::connect(&db).await.unwrap(); | ||
| 107 | 126 | ||
| 108 | - let user_1 = user::create("Tahinli", &db).await.unwrap(); | 127 | + let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); |
| 109 | - let user_2 = user::create("Tahinli", &db).await.unwrap(); | 128 | + let _other_user = user::create("Not Tahinli", "hash", &conn).await.unwrap(); |
| 110 | - let _user_3 = user::create("Not Tahinli", &db).await.unwrap(); | ||
| 111 | 129 | ||
| 112 | - let searched_users = user::read_by_username("Tahinli", &db).await.unwrap(); | 130 | + let searched_user = user::by_username("Tahinli", &conn).await.unwrap(); |
| 113 | 131 | ||
| 114 | - assert_eq!(vec![user_1, user_2], searched_users); | 132 | + assert_eq!(Some(created_user), searched_user); |
| 115 | } | 133 | } |
| 116 | 134 | ||
| 117 | #[tokio::test] | 135 | #[tokio::test] |
| 118 | async fn update() { | 136 | async fn update() { |
| 119 | let db = test::get_database().await; | 137 | let db = test::get_database().await; |
| 138 | + let conn = database::connect(&db).await.unwrap(); | ||
| 120 | 139 | ||
| 121 | - let created_user = user::create("Tahinli", &db).await.unwrap(); | 140 | + let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); |
| 122 | - let updated_user = user::update(&created_user.id, "Not Tahinli", &db) | 141 | + let updated_user = user::update(&created_user.id, "Not Tahinli", &conn) |
| 123 | .await | 142 | .await |
| 124 | .unwrap(); | 143 | .unwrap(); |
| 125 | - let searched_user = user::read(&created_user.id, &db).await.unwrap(); | 144 | + let searched_user = user::read(&created_user.id, &conn).await.unwrap(); |
| 126 | 145 | ||
| 127 | assert_eq!(created_user.id, searched_user.id); | 146 | assert_eq!(created_user.id, searched_user.id); |
| 128 | assert_eq!(updated_user, searched_user); | 147 | assert_eq!(updated_user, searched_user); |
| @@ -132,18 +151,23 @@ mod tests { | |||
| 132 | #[tokio::test] | 151 | #[tokio::test] |
| 133 | async fn update_on_missing_user() { | 152 | async fn update_on_missing_user() { |
| 134 | let db = test::get_database().await; | 153 | let db = test::get_database().await; |
| 154 | + let conn = database::connect(&db).await.unwrap(); | ||
| 135 | 155 | ||
| 136 | - let updated_user = user::update("missing", "Not Tahinli", &db).await; | 156 | + let updated_user = user::update("missing", "Not Tahinli", &conn).await; |
| 137 | 157 | ||
| 138 | - assert!(matches!(updated_user, Err(Error::NotFound))); | 158 | + assert!(matches!( |
| 159 | + updated_user, | ||
| 160 | + Err(Error::Common(CommonError::NotFound)) | ||
| 161 | + )); | ||
| 139 | } | 162 | } |
| 140 | 163 | ||
| 141 | #[tokio::test] | 164 | #[tokio::test] |
| 142 | async fn delete() { | 165 | async fn delete() { |
| 143 | let db = test::get_database().await; | 166 | let db = test::get_database().await; |
| 167 | + let conn = database::connect(&db).await.unwrap(); | ||
| 144 | 168 | ||
| 145 | - let created_user = user::create("Tahinli", &db).await.unwrap(); | 169 | + let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); |
| 146 | - let deleted_user = user::delete(&created_user.id, &db).await.unwrap(); | 170 | + let deleted_user = user::delete(&created_user.id, &conn).await.unwrap(); |
| 147 | 171 | ||
| 148 | assert_eq!(created_user, deleted_user); | 172 | assert_eq!(created_user, deleted_user); |
| 149 | } | 173 | } |
crates/server/src/user_community.rsmodified+90 -71
| @@ -1,7 +1,10 @@ | |||
| 1 | -use crate::{database::DB, error::Error}; | 1 | +use common::{error::Error as CommonError, model::User}; |
| 2 | +use turso::Connection; | ||
| 2 | 3 | ||
| 3 | -pub async fn join(user_id: &str, community_id: &str, db: &DB) -> Result<(), Error> { | 4 | +use crate::{error::Error, user}; |
| 4 | - db.execute( | 5 | + |
| 6 | +pub async fn join(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> { | ||
| 7 | + conn.execute( | ||
| 5 | "INSERT INTO user_community (user_id, community_id) VALUES (?1, ?2)", | 8 | "INSERT INTO user_community (user_id, community_id) VALUES (?1, ?2)", |
| 6 | (user_id, community_id), | 9 | (user_id, community_id), |
| 7 | ) | 10 | ) |
| @@ -10,8 +13,8 @@ pub async fn join(user_id: &str, community_id: &str, db: &DB) -> Result<(), Erro | |||
| 10 | Ok(()) | 13 | Ok(()) |
| 11 | } | 14 | } |
| 12 | 15 | ||
| 13 | -pub async fn leave(user_id: &str, community_id: &str, db: &DB) -> Result<(), Error> { | 16 | +pub async fn leave(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> { |
| 14 | - let deleted = db | 17 | + let deleted = conn |
| 15 | .execute( | 18 | .execute( |
| 16 | "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2", | 19 | "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2", |
| 17 | (user_id, community_id), | 20 | (user_id, community_id), |
| @@ -19,74 +22,79 @@ pub async fn leave(user_id: &str, community_id: &str, db: &DB) -> Result<(), Err | |||
| 19 | .await?; | 22 | .await?; |
| 20 | 23 | ||
| 21 | if deleted == 0 { | 24 | if deleted == 0 { |
| 22 | - return Err(Error::NotFound); | 25 | + return Err(CommonError::NotFound.into()); |
| 23 | } | 26 | } |
| 24 | 27 | ||
| 25 | Ok(()) | 28 | Ok(()) |
| 26 | } | 29 | } |
| 27 | 30 | ||
| 28 | -pub async fn is_user_in(user_id: &str, community_id: &str, db: &DB) -> Result<bool, Error> { | 31 | +pub async fn is_member( |
| 29 | - let mut rows = db | 32 | + user_id: &str, |
| 33 | + community_id: &str, | ||
| 34 | + conn: &Connection, | ||
| 35 | +) -> Result<bool, Error> { | ||
| 36 | + let mut rows = conn | ||
| 30 | .query( | 37 | .query( |
| 31 | "SELECT COUNT(*) FROM user_community WHERE user_id = ?1 AND community_id = ?2", | 38 | "SELECT COUNT(*) FROM user_community WHERE user_id = ?1 AND community_id = ?2", |
| 32 | (user_id, community_id), | 39 | (user_id, community_id), |
| 33 | ) | 40 | ) |
| 34 | .await?; | 41 | .await?; |
| 35 | - let row = rows.next().await?.ok_or(Error::NotFound)?; | 42 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 36 | let count: i64 = row.get(0)?; | 43 | let count: i64 = row.get(0)?; |
| 37 | 44 | ||
| 38 | Ok(count > 0) | 45 | Ok(count > 0) |
| 39 | } | 46 | } |
| 40 | 47 | ||
| 41 | -pub async fn users_in(community_id: &str, db: &DB) -> Result<Vec<String>, Error> { | 48 | +pub async fn ensure_member( |
| 42 | - let mut rows = db | 49 | + user_id: &str, |
| 43 | - .query( | 50 | + community_id: &str, |
| 44 | - "SELECT user_id FROM user_community WHERE community_id = ?1 ORDER BY user_id", | 51 | + conn: &Connection, |
| 45 | - (community_id,), | 52 | +) -> Result<(), Error> { |
| 46 | - ) | 53 | + if !is_member(user_id, community_id, conn).await? { |
| 47 | - .await?; | 54 | + return Err(CommonError::Forbidden.into()); |
| 48 | - | ||
| 49 | - let mut user_ids = Vec::new(); | ||
| 50 | - while let Some(row) = rows.next().await? { | ||
| 51 | - user_ids.push(row.get(0)?); | ||
| 52 | } | 55 | } |
| 53 | 56 | ||
| 54 | - Ok(user_ids) | 57 | + Ok(()) |
| 55 | } | 58 | } |
| 56 | 59 | ||
| 57 | -pub async fn communities_of(user_id: &str, db: &DB) -> Result<Vec<String>, Error> { | 60 | +pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<User>, Error> { |
| 58 | - let mut rows = db | 61 | + let mut rows = conn |
| 59 | .query( | 62 | .query( |
| 60 | - "SELECT community_id FROM user_community WHERE user_id = ?1 ORDER BY community_id", | 63 | + "SELECT user.id, user.username FROM user JOIN user_community ON user_community.user_id = user.id WHERE user_community.community_id = ?1 ORDER BY user.id", |
| 61 | - (user_id,), | 64 | + (community_id,), |
| 62 | ) | 65 | ) |
| 63 | .await?; | 66 | .await?; |
| 64 | 67 | ||
| 65 | - let mut community_ids = Vec::new(); | 68 | + let mut members = Vec::new(); |
| 66 | while let Some(row) = rows.next().await? { | 69 | while let Some(row) = rows.next().await? { |
| 67 | - community_ids.push(row.get(0)?); | 70 | + members.push(user::from_row(&row)?); |
| 68 | } | 71 | } |
| 69 | 72 | ||
| 70 | - Ok(community_ids) | 73 | + Ok(members) |
| 71 | } | 74 | } |
| 72 | 75 | ||
| 73 | #[cfg(test)] | 76 | #[cfg(test)] |
| 74 | mod tests { | 77 | mod tests { |
| 75 | - use crate::{community, error::Error, test, user, user_community}; | 78 | + use common::error::Error as CommonError; |
| 79 | + | ||
| 80 | + use crate::{community, database, error::Error, test, user, user_community}; | ||
| 76 | 81 | ||
| 77 | #[tokio::test] | 82 | #[tokio::test] |
| 78 | async fn join() { | 83 | async fn join() { |
| 79 | let db = test::get_database().await; | 84 | let db = test::get_database().await; |
| 85 | + let conn = database::connect(&db).await.unwrap(); | ||
| 86 | + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 87 | + let member = user::create("Not Tahinli", "hash", &conn).await.unwrap(); | ||
| 88 | + let community = community::create("The Community", &owner.id, &conn) | ||
| 89 | + .await | ||
| 90 | + .unwrap(); | ||
| 80 | 91 | ||
| 81 | - let user = user::create("Tahinli", &db).await.unwrap(); | 92 | + user_community::join(&member.id, &community.id, &conn) |
| 82 | - let community = community::create("The Community", &db).await.unwrap(); | ||
| 83 | - | ||
| 84 | - user_community::join(&user.id, &community.id, &db) | ||
| 85 | .await | 93 | .await |
| 86 | .unwrap(); | 94 | .unwrap(); |
| 87 | 95 | ||
| 88 | assert!( | 96 | assert!( |
| 89 | - user_community::is_user_in(&user.id, &community.id, &db) | 97 | + user_community::is_member(&member.id, &community.id, &conn) |
| 90 | .await | 98 | .await |
| 91 | .unwrap() | 99 | .unwrap() |
| 92 | ); | 100 | ); |
| @@ -95,16 +103,18 @@ mod tests { | |||
| 95 | #[tokio::test] | 103 | #[tokio::test] |
| 96 | async fn join_again() { | 104 | async fn join_again() { |
| 97 | let db = test::get_database().await; | 105 | let db = test::get_database().await; |
| 106 | + let conn = database::connect(&db).await.unwrap(); | ||
| 107 | + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 108 | + let community = community::create("The Community", &owner.id, &conn) | ||
| 109 | + .await | ||
| 110 | + .unwrap(); | ||
| 98 | 111 | ||
| 99 | - let user = user::create("Tahinli", &db).await.unwrap(); | 112 | + user_community::join(&owner.id, &community.id, &conn) |
| 100 | - let community = community::create("The Community", &db).await.unwrap(); | ||
| 101 | - | ||
| 102 | - user_community::join(&user.id, &community.id, &db) | ||
| 103 | .await | 113 | .await |
| 104 | .unwrap(); | 114 | .unwrap(); |
| 105 | 115 | ||
| 106 | assert!( | 116 | assert!( |
| 107 | - user_community::join(&user.id, &community.id, &db) | 117 | + user_community::join(&owner.id, &community.id, &conn) |
| 108 | .await | 118 | .await |
| 109 | .is_err() | 119 | .is_err() |
| 110 | ); | 120 | ); |
| @@ -113,19 +123,21 @@ mod tests { | |||
| 113 | #[tokio::test] | 123 | #[tokio::test] |
| 114 | async fn leave() { | 124 | async fn leave() { |
| 115 | let db = test::get_database().await; | 125 | let db = test::get_database().await; |
| 116 | - | 126 | + let conn = database::connect(&db).await.unwrap(); |
| 117 | - let user = user::create("Tahinli", &db).await.unwrap(); | 127 | + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); |
| 118 | - let community = community::create("The Community", &db).await.unwrap(); | 128 | + let community = community::create("The Community", &owner.id, &conn) |
| 119 | - user_community::join(&user.id, &community.id, &db) | 129 | + .await |
| 130 | + .unwrap(); | ||
| 131 | + user_community::join(&owner.id, &community.id, &conn) | ||
| 120 | .await | 132 | .await |
| 121 | .unwrap(); | 133 | .unwrap(); |
| 122 | 134 | ||
| 123 | - user_community::leave(&user.id, &community.id, &db) | 135 | + user_community::leave(&owner.id, &community.id, &conn) |
| 124 | .await | 136 | .await |
| 125 | .unwrap(); | 137 | .unwrap(); |
| 126 | 138 | ||
| 127 | assert!( | 139 | assert!( |
| 128 | - !user_community::is_user_in(&user.id, &community.id, &db) | 140 | + !user_community::is_member(&owner.id, &community.id, &conn) |
| 129 | .await | 141 | .await |
| 130 | .unwrap() | 142 | .unwrap() |
| 131 | ); | 143 | ); |
| @@ -134,60 +146,67 @@ mod tests { | |||
| 134 | #[tokio::test] | 146 | #[tokio::test] |
| 135 | async fn leave_again() { | 147 | async fn leave_again() { |
| 136 | let db = test::get_database().await; | 148 | let db = test::get_database().await; |
| 137 | - | 149 | + let conn = database::connect(&db).await.unwrap(); |
| 138 | - let user = user::create("Tahinli", &db).await.unwrap(); | 150 | + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); |
| 139 | - let community = community::create("The Community", &db).await.unwrap(); | 151 | + let community = community::create("The Community", &owner.id, &conn) |
| 140 | - user_community::join(&user.id, &community.id, &db) | 152 | + .await |
| 153 | + .unwrap(); | ||
| 154 | + user_community::join(&owner.id, &community.id, &conn) | ||
| 141 | .await | 155 | .await |
| 142 | .unwrap(); | 156 | .unwrap(); |
| 143 | - user_community::leave(&user.id, &community.id, &db) | 157 | + user_community::leave(&owner.id, &community.id, &conn) |
| 144 | .await | 158 | .await |
| 145 | .unwrap(); | 159 | .unwrap(); |
| 146 | 160 | ||
| 147 | - let leave = user_community::leave(&user.id, &community.id, &db).await; | 161 | + let leave = user_community::leave(&owner.id, &community.id, &conn).await; |
| 148 | 162 | ||
| 149 | - assert!(matches!(leave, Err(Error::NotFound))); | 163 | + assert!(matches!(leave, Err(Error::Common(CommonError::NotFound)))); |
| 150 | } | 164 | } |
| 151 | 165 | ||
| 152 | #[tokio::test] | 166 | #[tokio::test] |
| 153 | - async fn users_in() { | 167 | + async fn members() { |
| 154 | let db = test::get_database().await; | 168 | let db = test::get_database().await; |
| 169 | + let conn = database::connect(&db).await.unwrap(); | ||
| 170 | + let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 171 | + let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap(); | ||
| 172 | + let _user_3 = user::create("Third Tahinli", "hash", &conn).await.unwrap(); | ||
| 173 | + let community = community::create("The Community", &user_1.id, &conn) | ||
| 174 | + .await | ||
| 175 | + .unwrap(); | ||
| 155 | 176 | ||
| 156 | - let user_1 = user::create("Tahinli", &db).await.unwrap(); | 177 | + user_community::join(&user_1.id, &community.id, &conn) |
| 157 | - let user_2 = user::create("Tahinli", &db).await.unwrap(); | ||
| 158 | - let _user_3 = user::create("Tahinli", &db).await.unwrap(); | ||
| 159 | - let community = community::create("The Community", &db).await.unwrap(); | ||
| 160 | - | ||
| 161 | - user_community::join(&user_1.id, &community.id, &db) | ||
| 162 | .await | 178 | .await |
| 163 | .unwrap(); | 179 | .unwrap(); |
| 164 | - user_community::join(&user_2.id, &community.id, &db) | 180 | + user_community::join(&user_2.id, &community.id, &conn) |
| 165 | .await | 181 | .await |
| 166 | .unwrap(); | 182 | .unwrap(); |
| 167 | 183 | ||
| 168 | - let users_in = user_community::users_in(&community.id, &db).await.unwrap(); | 184 | + let members = user_community::members(&community.id, &conn).await.unwrap(); |
| 169 | 185 | ||
| 170 | - assert_eq!(vec![user_1.id, user_2.id], users_in); | 186 | + assert_eq!(vec![user_1, user_2], members); |
| 171 | } | 187 | } |
| 172 | 188 | ||
| 173 | #[tokio::test] | 189 | #[tokio::test] |
| 174 | async fn communities_of() { | 190 | async fn communities_of() { |
| 175 | let db = test::get_database().await; | 191 | let db = test::get_database().await; |
| 192 | + let conn = database::connect(&db).await.unwrap(); | ||
| 193 | + let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 194 | + let community_1 = community::create("The Community", &owner.id, &conn) | ||
| 195 | + .await | ||
| 196 | + .unwrap(); | ||
| 197 | + let community_2 = community::create("The Community", &owner.id, &conn) | ||
| 198 | + .await | ||
| 199 | + .unwrap(); | ||
| 176 | 200 | ||
| 177 | - let user = user::create("Tahinli", &db).await.unwrap(); | 201 | + user_community::join(&owner.id, &community_1.id, &conn) |
| 178 | - let community_1 = community::create("The Community", &db).await.unwrap(); | ||
| 179 | - let community_2 = community::create("The Community", &db).await.unwrap(); | ||
| 180 | - let _community_3 = community::create("The Community", &db).await.unwrap(); | ||
| 181 | - | ||
| 182 | - user_community::join(&user.id, &community_1.id, &db) | ||
| 183 | .await | 202 | .await |
| 184 | .unwrap(); | 203 | .unwrap(); |
| 185 | - user_community::join(&user.id, &community_2.id, &db) | 204 | + user_community::join(&owner.id, &community_2.id, &conn) |
| 186 | .await | 205 | .await |
| 187 | .unwrap(); | 206 | .unwrap(); |
| 188 | 207 | ||
| 189 | - let communities_of = user_community::communities_of(&user.id, &db).await.unwrap(); | 208 | + let communities_of = community::communities_of(&owner.id, &conn).await.unwrap(); |
| 190 | 209 | ||
| 191 | - assert_eq!(vec![community_1.id, community_2.id], communities_of); | 210 | + assert_eq!(vec![community_1, community_2], communities_of); |
| 192 | } | 211 | } |
| 193 | } | 212 | } |