-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgroups.rs
More file actions
266 lines (224 loc) · 9 KB
/
Copy pathgroups.rs
File metadata and controls
266 lines (224 loc) · 9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
use crate::dioxus_fullstack::NoContent;
use crate::routes::users::UserInfo;
#[cfg(feature = "server")]
use crate::server;
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
#[cfg(feature = "server")]
use dioxus::server::axum::Extension;
#[post("/api/groups", ext: Extension<server::AppState>, auth: Extension<server::AuthenticationState>)]
pub async fn create_group(group_name: String) -> Result<entity::group::Model, ServerFnError> {
use entity::is_in_group;
use sea_orm::{ActiveModelTrait, Set, TransactionError, TransactionTrait};
ext.database
.transaction::<_, entity::group::Model, ServerFnError>(|txn| {
Box::pin(async move {
let group = entity::group::ActiveModel {
name: Set(group_name),
..Default::default()
};
let group = group
.insert(txn)
.await
.or_internal_server_error("Error creating group")?;
let user = auth.user.as_ref().or_unauthorized("Not authenticated")?;
let pair = is_in_group::ActiveModel {
user_id: Set(user.id),
group_id: Set(group.id),
};
pair.insert(txn)
.await
.inspect_err(|error| error!("{error:?}"))
.or_internal_server_error("Error adding creator to group")?;
Ok(group)
})
})
.await
.map_err(|error| {
error!("{error}");
match error {
TransactionError::Connection(_) => ServerFnError::ServerError {
message: String::from("Error creating group"),
code: 500,
details: None,
},
TransactionError::Transaction(error) => error,
}
})
}
#[get("/api/groups", ext: Extension<server::AppState>, auth: Extension<server::AuthenticationState>)]
pub async fn list_groups() -> Result<Vec<entity::group::Model>, ServerFnError> {
use entity::group::Entity as Group;
use sea_orm::ModelTrait;
let user = auth.user.as_ref().or_unauthorized("Not authenticated")?;
let groups = user
.find_related(Group)
.all(&ext.database)
.await
.or_internal_server_error("Error loading groups")?;
Ok(groups)
}
/// Adds an user to a group
#[post("/api/groups/{group_id}/add-user", ext: Extension<server::AppState>, auth: Extension<server::AuthenticationState>)]
pub async fn add_user_to_group(group_id: i32, email: String) -> Result<NoContent, ServerFnError> {
use crate::server::events::is_user_in_group;
use entity::is_in_group;
use entity::user::Entity as User;
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter, Set};
let user = auth.user.as_ref().or_unauthorized("Not authenticated")?;
let authenticated = is_user_in_group(&ext.database, group_id, user.id).await?;
if authenticated {
let new_user = User::find()
.filter(entity::user::Column::Email.eq(email))
.one(&ext.database)
.await
.or_internal_server_error("Error loading user from database")?
.or_not_found("User not found")?;
let checker = is_user_in_group(&ext.database, group_id, new_user.id).await?;
(!checker).or_bad_request("User is already in group")?;
let pair = is_in_group::ActiveModel {
user_id: Set(new_user.id),
group_id: Set(group_id),
};
let _pair = pair
.insert(&ext.database)
.await
.or_internal_server_error("Error inserting pair into database")?;
Ok(NoContent)
} else {
Err(ServerFnError::ServerError {
message: "No permission to add a new user.".to_string(),
code: 401,
details: None,
})
}
}
///Deletes an user from a group
#[post("/api/groups/{group_id}/remove-user", ext: Extension<server::AppState>, auth: Extension<server::AuthenticationState>)]
pub async fn remove_user_from_group(
group_id: i32,
user_id: i32,
) -> Result<NoContent, ServerFnError> {
use crate::server::events::is_user_in_group;
use entity::is_in_group;
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
let user = auth.user.as_ref().or_unauthorized("Not authenticated")?;
let authenticated = is_user_in_group(&ext.database, group_id, user.id).await?;
let group = retrieve_group(group_id).await?;
let group_size = group.members.len();
if authenticated {
if group_size > 1 {
let result = is_in_group::Entity::delete_many()
.filter(is_in_group::Column::UserId.eq(user_id))
.filter(is_in_group::Column::GroupId.eq(group_id))
.exec(&ext.database)
.await
.or_internal_server_error("Error deleting relation")?;
(result.rows_affected > 0).or_not_found("Failed to remove user from group")?;
Ok(NoContent)
} else {
delete_group(group_id).await?;
Ok(NoContent)
}
} else {
Err(ServerFnError::ServerError {
message: "No permission to remove a user from this group.".to_string(),
code: 401,
details: None,
})
}
}
#[post("/api/groups/{group_id}/leave-group", auth: Extension<server::AuthenticationState>)]
pub async fn leave_group(group_id: i32) -> Result<NoContent, ServerFnError> {
let user = auth.user.as_ref().or_unauthorized("Not authenticated")?;
remove_user_from_group(group_id, user.id).await
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct GroupDetailData {
pub name: String,
pub members: Vec<UserInfo>,
pub events: Vec<entity::event::Model>,
}
///returns default struct of GroupDetailData when trying to call a group which does not exist
#[get("/api/groups/{group_id}", ext: Extension<server::AppState>)]
pub async fn retrieve_group(group_id: i32) -> Result<GroupDetailData, ServerFnError> {
use entity::event::Entity as Event;
use entity::group::Entity as Group;
use entity::user::Entity as User;
use sea_orm::EntityTrait;
use sea_orm::ModelTrait;
let group = Group::find_by_id(group_id)
.one(&ext.database)
.await
.or_internal_server_error("Error loading group from database")?
.or_not_found("Group not found")?;
let members = group
.find_related(User)
.all(&ext.database)
.await
.or_internal_server_error("Error loading members from database")?
.into_iter()
.map(UserInfo::from_user_model)
.collect();
let events = group
.find_related(Event)
.all(&ext.database)
.await
.or_internal_server_error("Error loading events from database")?;
let group_data = GroupDetailData {
name: group.name,
members,
events,
};
Ok(group_data)
}
#[put("/api/groups/{group_id}", ext: Extension<server::AppState>, auth: Extension<server::AuthenticationState>)]
pub async fn change_group_name(
group_id: i32,
group_name_new: String,
) -> Result<entity::group::Model, ServerFnError> {
use crate::server::events::is_user_in_group;
use entity::group;
use entity::group::Entity as Group;
use sea_orm::{ActiveModelTrait, EntityTrait, Set};
let user = auth.user.as_ref().or_unauthorized("Not authenticated")?;
is_user_in_group(&ext.database, group_id, user.id)
.await?
.or_forbidden("User is not part of this group")?;
let group = Group::find_by_id(group_id)
.one(&ext.database)
.await
.or_internal_server_error("Error loading Group")?
.or_not_found("Group not found")?;
let mut group: group::ActiveModel = group.into();
group.name = Set(group_name_new);
let group = group
.update(&ext.database)
.await
.or_internal_server_error("Error updating database")?;
Ok(group)
}
#[delete("/api/groups/{group_id}", ext: Extension<server::AppState>, auth: Extension<server::AuthenticationState>)]
pub async fn delete_group(group_id: i32) -> Result<NoContent, ServerFnError> {
use crate::server::events::is_user_in_group;
use crate::server::events::remove_group_events;
use entity::group::Entity as Group;
use sea_orm::EntityTrait;
let user = auth.user.as_ref().or_unauthorized("Not authenticated")?;
let authenticated = is_user_in_group(&ext.database, group_id, user.id).await?;
if authenticated {
remove_group_events(group_id, &ext.database).await?;
let delete_result = Group::delete_by_id(group_id)
.exec(&ext.database)
.await
.or_internal_server_error("Error deleting group")?;
(delete_result.rows_affected == 1).or_not_found("User not found")?;
Ok(NoContent)
} else {
Err(ServerFnError::ServerError {
message: "No permission to delte group.".to_string(),
code: 401,
details: None,
})
}
}