Newer
Older
use crate::static_files::upload::*;
use crate::website::WebSite;
use actix_multipart::Multipart;
use actix_web::{
delete, get, post, web,
web::{Data, Path},
HttpResponse, Responder,
};
use futures::StreamExt;
use std::{
fs::{remove_file, File},
io::Write,
pub async fn favicon(website: web::Data<RwLock<WebSite>>) -> impl Responder {
NamedFile::open(
&website
.read()
.unwrap()
.static_files_manager
.dir
.join("default")
.join("favicon.ico"),
)
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
fn upload_data_from_multipart_field(
field: &actix_multipart::Field,
) -> Result<UploadFileData, String> {
match field.content_disposition().get_filename() {
Some(fname) => match file_ext(&fname.to_string()) {
Ok(ext) => Ok(UploadFileData {
up_type: upload_type_from_file_ext(&ext),
filename: fname.to_owned(),
}),
Err(msg) => return Err(msg),
},
None => Err("Couldn't retrieve file extension".to_string()),
}
}
async fn write_uploaded_file(
website: &WebSite,
field: &mut actix_multipart::Field,
filename: &String,
upload_type: UploadFileType,
) -> Result<String, String> {
let root = &website.static_files_manager.dir;
let sub_dir = dirname_from_type(&upload_type);
let filepath = root.join(sub_dir).join(&filename);
match File::create(&filepath) {
Err(e) => Err(format!("Error creating file {:?} : {:?}", filepath, e)),
Ok(mut f) => {
// Field in turn is stream of *Bytes* object
while let Some(chunk) = field.next().await {
match chunk {
Ok(chunk) => {
if f.write_all(&chunk).is_err() {
remove_file(&filepath).unwrap();
return Err("Error writing chunk".to_string());
}
}
Err(e) => {
return Err(format!("Error writing file {} : {:?}", filename, e));
}
}
}
Ok(filepath.into_os_string().into_string().unwrap())
}
}
}
#[post("/post-files")]
pub async fn post_files(website: Data<RwLock<WebSite>>, mut payload: Multipart) -> impl Responder {
let mut website = website
.write()
.expect("Couldn't acquire write lock for RwLock<WebSite");
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
while let Some(item) = payload.next().await {
match item {
Ok(mut field) => {
let up_data = upload_data_from_multipart_field(&field);
if let Err(msg) = up_data {
return HttpResponse::InternalServerError().body(msg);
}
let up_data = up_data.unwrap();
match write_uploaded_file(&website, &mut field, &up_data.filename, up_data.up_type)
.await
{
Err(msg) => return HttpResponse::InternalServerError().body(msg),
Ok(filepath) => uploaded_filepathes.extend(
website
.static_files_manager
.push_path(std::path::Path::new(&filepath)),
),
}
}
Err(e) => {
return HttpResponse::InternalServerError().body(format!("FIELD ERR {:?}", e))
}
}
}
HttpResponse::Ok().json(uploaded_filepathes)
}
#[get("/static-files-index")]
async fn get_static_files_index(website: Data<RwLock<WebSite>>) -> impl Responder {
HttpResponse::Ok().json(website.read().unwrap().static_files_manager.get_index())
}
#[delete("/delete-file/{category}/{filename}")]
async fn delete_static_file(
fileinfo: Path<(String, String)>,
) -> impl Responder {
let mut website = website
.write()
.expect("Couldn't acquire write lock for RwLock<WebSite");
let (cat, fname) = fileinfo.into_inner();
let fpath = std::path::PathBuf::from(cat).join(fname);
match remove_file(website.static_files_manager.dir.join(&fpath)) {
Ok(_) => {
website
.static_files_manager
.remove_path(fpath.to_string_lossy().into());
HttpResponse::Accepted().body("File was deleted")
}
Err(e) => HttpResponse::InternalServerError().body(format!("Error deleting file {:?}", e)),
}
}
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
#[cfg(test)]
mod test_static_files_services {
use super::*;
use crate::{cookie::*, website::*, AppState};
use actix_web::{
http::{Method, StatusCode},
test,
web::Bytes,
App,
};
use std::sync::RwLock;
fn create_simple_request() -> Bytes {
Bytes::from(
"--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
Content-Disposition: form-data; name=\"file\"; filename=\"test.txt\"\r\n\
Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\
test\r\n\
--abbc761f78ff4d7cb7573b5a23f96ef0\r\n\
Content-Disposition: form-data; name=\"file\"; filename=\"data.txt\"\r\n\
Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\
data\r\n\
--abbc761f78ff4d7cb7573b5a23f96ef0--\r\n",
)
}
// fn clear_testing_static(dir: &std::path::PathBuf) {
// std::fs::remove_dir_all(dir).unwrap();
// }
#[actix_web::test]
async fn post_files_unauthenticated_should_be_unauthorized() {
let static_dir = std::path::PathBuf::from("./test");
let ws = WebSiteBuilder::testing(&static_dir);
let mut app = test::init_service(
App::new()
.app_data(web::Data::new(RwLock::new(app_state.clone())))
.app_data(web::Data::new(RwLock::new(ws.clone())))
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
.service(post_files),
)
.await;
let req = test::TestRequest::with_uri("/post-files")
.method(Method::POST)
.append_header((
"Content-Type",
"multipart/form-data; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"",
))
.cookie(SecureCookie::new(
&"wrong-cookie".to_string(),
&SecureCookie::generate_token(36),
))
.set_payload(create_simple_request())
.to_request();
let resp = test::call_service(&mut app, req).await;
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
// #[actix_web::test]
// async fn test_post_files() {
// let app_state = AppState::for_test().await;
// let admin_user = Administrator::authenticated(
// &app_state,
// AdminAuthCredentials {
// username: app_state.env.default_admin_username.to_owned(),
// password: app_state.env.default_admin_password.to_owned(),
// },
// )
// .await
// .unwrap();
// let static_files_index = create_files_index(&app_state);
// let mut app = test::init_service(
// App::new()
// .app_data(Data::new(app_state.clone()))
// .app_data(Data::clone(&static_files_index))
// .app_data(Data::new(AuthenticatedAdminMiddleware::new(
// "kuadrado-admin-auth",
// )))
// .service(post_files),
// )
// .await;
// let req = test::TestRequest::with_uri("/post-files")
// .method(Method::POST)
// .header(
// "Content-Type",
// "multipart/form-data; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"",
// )
// .cookie(get_auth_cookie(
// "kuadrado-admin-auth",
// app_state
// .encryption
// .decrypt(&admin_user.auth_token.unwrap())
// .to_owned(),
// ))
// .set_payload(create_simple_request())
// .to_request();
// let resp = test::call_service(&mut app, req).await;
// let status = resp.status();
// assert_eq!(status, StatusCode::OK);
// let pathes: Vec<String> = test::read_body_json(resp).await;
// let public_dir = StaticFilesIndex::get_public_dir(&app_state.env);
// let pathes_from_public = pathes
// .iter()
// .map(|p| {
// format!(
// "/{}",
// std::path::Path::new(p)
// .strip_prefix(&public_dir)
// .unwrap()
// .to_str()
// .unwrap()
// )
// })
// .collect::<Vec<String>>();
// let index = static_files_index.lock().unwrap();
// assert_eq!(pathes_from_public, index.0);
// let mut iter_pathes = pathes.iter();
// let f = std::fs::read_to_string(iter_pathes.next().unwrap()).unwrap();
// assert_eq!(f, "test");
// let f = std::fs::read_to_string(iter_pathes.next().unwrap()).unwrap();
// assert_eq!(f, "data");
// clear_testing_static();
// }
// #[actix_web::test]
// async fn test_delete_file() {
// let app_state = AppState::for_test().await;
// let admin_user = Administrator::authenticated(
// &app_state,
// AdminAuthCredentials {
// username: app_state.env.default_admin_username.to_owned(),
// password: app_state.env.default_admin_password.to_owned(),
// },
// )
// .await
// .unwrap();
// let static_files_index = create_files_index(&app_state);
// let mut app = test::init_service(
// App::new()
// .app_data(Data::new(app_state.clone()))
// .app_data(Data::clone(&static_files_index))
// .app_data(Data::new(AuthenticatedAdminMiddleware::new(
// "kuadrado-admin-auth",
// )))
// .service(post_files)
// .service(delete_static_file),
// )
// .await;
// let auth_token = admin_user.auth_token.unwrap();
// let req = test::TestRequest::with_uri("/post-files")
// .method(Method::POST)
// .header(
// "Content-Type",
// "multipart/form-data; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"",
// )
// .cookie(get_auth_cookie(
// "kuadrado-admin-auth",
// app_state.encryption.decrypt(&auth_token).to_owned(),
// ))
// .set_payload(create_simple_request())
// .to_request();
// let resp = test::call_service(&mut app, req).await;
// let status = resp.status();
// assert_eq!(status, StatusCode::OK);
// let req = test::TestRequest::with_uri("/delete-file/uploads/docs/test.txt")
// .method(Method::DELETE)
// .cookie(get_auth_cookie(
// "kuadrado-admin-auth",
// app_state.encryption.decrypt(&auth_token).to_owned(),
// ))
// .to_request();
// let resp = test::call_service(&mut app, req).await;
// let status = resp.status();
// assert_eq!(status, StatusCode::ACCEPTED);
// clear_testing_static();
// }
}