-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpages-before-comment-out-prints.rs
2027 lines (1664 loc) · 93.9 KB
/
pages-before-comment-out-prints.rs
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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{thread, time};
use std::time::Instant;
use std::time::Duration;
use std::{env, str, io};
use std::io::{Cursor, Read};
use std::path::{Path, PathBuf};
use rocket_contrib::Template;
use rocket::response::{content, NamedFile, Redirect, Flash};
use rocket::{Request, Data, Outcome};
use rocket::request::{FlashMessage, Form, FromForm};
use rocket::data::FromData;
use rocket::response::content::Html;
use rocket::State;
// use rocket::request::{Form, FlashMessage};
use rocket::http::{Cookie, Cookies, RawStr};
// use auth::userpass::UserPass;
// use auth::status::{LoginStatus,LoginRedirect};
// use auth::dummy::DummyAuthenticator;
// use auth::authenticator::Authenticator;
use regex::Regex;
use titlecase::titlecase;
use chrono::prelude::*;
use chrono::{NaiveDate, NaiveDateTime};
use std::sync::atomic::{AtomicUsize, Ordering};
use rocket::http::hyper::header::{Headers, ContentDisposition, DispositionType, DispositionParam, Charset};
// use super::{BLOG_URL, ADMIN_LOGIN_URL, USER_LOGIN_URL, CREATE_FORM_URL, TEST_LOGIN_URL};
// use super::RssContent;
// use cookie_data::*;
// use cookie_data::CookieId;
// use admin_auth::*;
// use user_auth::*;
// use users::*;
// use login_form_status::*;
// use login_form_status::LoginFormRedirect;
// use templates::*;
// use authorize::*;
// use administrator::*;
// use roles::*;
use super::*;
// use counter::*;
use counter::*;
use location::*;
use referrer::*;
use collate::*;
use layout::*;
use blog::*;
use data::*;
use sanitize::*;
use rocket_auth_login::authorization::*;
use rocket_auth_login::sanitization::*;
use ral_administrator::*;
use ral_user::*;
use templates::*;
use xpress::*;
use accept::*;
// use ::templates::*;
use comrak::{markdown_to_html, ComrakOptions};
// pub const COMRAK_OPTIONS: ComrakOptions = ComrakOptions {
// hardbreaks: true, // \n => <br>\n
// width: 120usize,
// github_pre_lang: false,
// ext_strikethrough: true, // hello ~world~ person.
// ext_tagfilter: true, // filters out certain html tags
// ext_table: true, // | a | b |\n|---|---|\n| c | d |
// ext_autolink: true,
// ext_tasklist: true, // * [x] Done\n* [ ] Not Done
// ext_superscript: true, // e = mc^2^
// ext_header_ids: None, // None / Some("some-id-prefix-".to_string())
// ext_footnotes: true, // Hi[^x]\n\n[^x]: A footnote here\n
// };
// TODO: Collate: make a route that takes a number in the route (not query string)
// use this number to determine how many pages to list
// on each page say the page number as determined in the Page structure
// output\.into\(\)\.compress\(encoding\)
// let express: Express = output.into();
// express.compress(encoding)
// #[get("/login-user")]
// fn hbs_login_form_admin(start: GenTimer, conn: DbConn, user: Option<UserCookie>, flash_msg_opt: Option<FlashMessage>, encoding: AcceptCompression, referrer: Referrer) -> Express {
// let mut fields: HashMap<String, String> = HashMap::new();
// if let Referrer(Some(refer)) = referrer {
// println!("Referrer: {}", &refer);
// fields.insert("");
// }
// let express: Express = String::new().into();
// express.compress(encoding)
// }
// #[post("/login-user", data = "<form>")]
// fn hbs_login_process_admin() -> Redirect {
// }
// DOESN'T WORK
// #[get("/init")]
// pub fn initialize(admin: Option<AdministratorCookie>) {
// ContentCacheLock::cache(rock, STATIC_PAGES_DIR);
// }
fn destruct_context(ctx: ContentContext) -> (HashMap<String, PageContext>, usize) {
let reader = ctx.pages.read().unwrap().clone();
let size = ctx.size.load(Ordering::SeqCst);
(reader, size)
}
fn destruct_cache(cache: ContentCacheLock) -> (HashMap<String, ContentCached>, usize) {
let reader = cache.pages.read().unwrap().clone();
let size = cache.size.load(Ordering::SeqCst);
(reader, size)
}
#[get("/refresh_content")]
pub fn refresh_content(start: GenTimer, admin: AdministratorCookie, user: Option<UserCookie>, encoding: AcceptCompression, uhits: UniqueHits, context_state: State<ContentContext>, cache_state: State<ContentCacheLock>) -> Express {
let mut ctx_writer;
if let Ok(ctx) = context_state.pages.write() {
ctx_writer = ctx;
} else {
let template = hbs_template(TemplateBody::General(alert_danger("An error occurred attempting to access content.")), None, Some("Content not available.".to_string()), String::from("/error404"), Some(admin), user, None, Some(start.0));
let express: Express = template.into();
return express.compress(encoding);
}
let mut cache_writer;
if let Ok(cache) = cache_state.pages.write() {
cache_writer = cache;
} else {
let template = hbs_template(TemplateBody::General(alert_danger("An error occurred attempting to access content.")), None, Some("Content not available.".to_string()), String::from("/error404"), Some(admin), user, None, Some(start.0));
let express: Express = template.into();
return express.compress(encoding);
}
// let content_context: ContentContext = ContentContext::load(STATIC_PAGES_DIR);
// let content_cache: ContentCacheLock = ContentCacheLock::new();
let (ctx_pages, ctx_size) = destruct_context(ContentContext::load(STATIC_PAGES_DIR));
*ctx_writer = ctx_pages;
context_state.size.store(ctx_size, Ordering::SeqCst);
// let cache = ContentCacheLock::new();
let (cache_pages, cache_size) = destruct_cache(ContentCacheLock::new());
*cache_writer = cache_pages;
cache_state.size.store(cache_size, Ordering::SeqCst);
// // load template contexts for all content files in the pages directory
// *ctx_writer = *ctx.pages.read().unwrap();
// // ctx_writer = ctx.pages.read();
// context_state.size.store(ctx.size.load(Ordering::SeqCst), Ordering::SeqCst);
// // reset cache back to nothing
// *cache_writer = *cache.pages.read().unwrap();
// cache_state.size.store(cache.size.load(Ordering::SeqCst), Ordering::SeqCst);
let template = hbs_template(TemplateBody::General(alert_success("Content has been refreshed successfully.")), None, Some("Content refreshed.".to_string()), String::from("/error404"), Some(admin), user, None, Some(start.0));
let express: Express = template.into();
express.compress(encoding)
}
//
#[get("/content/<uri..>")]
pub fn static_pages(start: GenTimer,
uri: PathBuf,
admin: Option<AdministratorCookie>,
user: Option<UserCookie>,
encoding: AcceptCompression,
uhits: UniqueHits,
context: State<ContentContext>,
// cache_lock: State<ContentCacheLock>
) -> Result<ContentRequest, Express> {
// could also prevent hotlinking by checking the referrer
// and sending an error for referring sites other than BASE or blank
// look for the uri in the context, if it exists then make a ContextRequest
// which will be passed as the output
// before passing ContextRequest as the output, check for admin/user in the context
// if the context has user or admin set to true then make sure the admin/user var is_some()
// if it does not exist then return an Express instance with an error message
// use hbs_template's General template
// Could also move context out of the ContentReuqest and in the Responder use
// let cache = req.guard::<State<HitCount>>().unwrap();
let page = uri.to_string_lossy().into_owned();
if let Ok(ctx_reader) = context.pages.read() {
// if let Some(ctx) = context.pages.get(&page) {
if let Some(ctx) = ctx_reader.get(&page) {
// Permissions check
if (ctx.admin && admin.is_none()) || (ctx.user && user.is_none()) {
let template = hbs_template(TemplateBody::General(alert_danger("You do not have sufficient privileges to view this content.")), None, Some("Insufficient Privileges".to_string()), String::from("/error403"), admin, user, None, Some(start.0));
let express: Express = template.into();
return Err(express.compress(encoding));
}
// let test = ctx.clone();
// context request
// Build a ContentRequest with the requested files
let conreq: ContentRequest = ContentRequest {
encoding,
// cache: cache_lock.inner(),
route: page,
start,
// context: ctx.clone(),
// context: &test,
};
Ok(conreq)
} else {
// let template = hbs_template(...); // Content does not exist
let template = hbs_template(TemplateBody::General(alert_danger("The requested content could not be found.")), None, Some("Content not found.".to_string()), String::from("/error404"), admin, user, None, Some(start.0));
let express: Express = template.into();
Err(express.compress(encoding))
}
} else {
// let template = hbs_template(...); // Content does not exist
let template = hbs_template(TemplateBody::General(alert_danger("An error occurred attempting to access content.")), None, Some("Content not available.".to_string()), String::from("/error404"), admin, user, None, Some(start.0));
let express: Express = template.into();
Err(express.compress(encoding))
}
}
#[get("/download/<uri..>")]
pub fn code_download(start: GenTimer,
uri: PathBuf,
admin: Option<AdministratorCookie>,
user: Option<UserCookie>,
encoding: AcceptCompression,
uhits: UniqueHits,
context: State<ContentContext>,
// cache_lock: State<ContentCacheLock>
) -> Express {
// If the requested URI cannot be found in the static page cache
// maybe try looking in the uploads folder
let page = uri.to_string_lossy().into_owned();
if let Ok(ctx_reader) = context.pages.read() {
// if let Some(ctx) = context.pages.get(&page) {
if let Some(ctx) = ctx_reader.get(&page) {
// Permissions check
if (ctx.admin && admin.is_none()) || (ctx.user && user.is_none()) {
let template = hbs_template(TemplateBody::General(alert_danger("You do not have sufficient privileges to view this content.")), None, Some("Insufficient Privileges".to_string()), String::from("/error403"), admin, user, None, Some(start.0));
let express: Express = template.into();
return express.compress(encoding);
}
let express: Express = ctx.body.clone().into();
// let mut headers = Headers::new();
// headers.set(ContentDisposition {
// disposition: DispositionType::Attachment,
// parameters: vec![DispositionParam::Filename(
// Charset::Iso_8859_1, // The character set for the bytes of the filename
// None, // The optional language tag (see `language-tag` crate)
// b"\xa9 Copyright 1989.txt".to_vec() // the actual bytes of the filename
// )]
// });
let attachment = ContentDisposition {
disposition: DispositionType::Attachment,
parameters: vec![DispositionParam::Filename(
Charset::Iso_8859_1, // The character set for the bytes of the filename
None, // The optional language tag (see `language-tag` crate)
ctx.uri.clone().into_bytes()
// b"".to_vec() // the actual bytes of the filename
)]
};
express
// Disable cache headers; IE breaks if downloading a file over HTTPS with cache-control headers
.set_ttl(-2)
.add_header(attachment)
// express
} else {
// let template = hbs_template(...); // Content does not exist
let template = hbs_template(TemplateBody::General(alert_danger("The requested download could not be found.")), None, Some("Content not found.".to_string()), String::from("/error404"), admin, user, None, Some(start.0));
let express: Express = template.into();
express.compress(encoding)
}
} else {
// let template = hbs_template(...); // Content does not exist
let template = hbs_template(TemplateBody::General(alert_danger("An error occurred attempting to access content.")), None, Some("Content not available.".to_string()), String::from("/error404"), admin, user, None, Some(start.0));
let express: Express = template.into();
express.compress(encoding)
}
}
#[get("/admin-test")]
pub fn hbs_admin_test(start: GenTimer, user: Option<UserCookie>, admin: Option<AdministratorCookie>, encoding: AcceptCompression) -> Express {
let output: Template;
if let Some(a) = admin {
output = hbs_template(TemplateBody::General(alert_success("You are logged in.")), None, Some("Admin Test".to_string()), String::from("/admin-test"), Some(a), user, None, Some(start.0));
} else {
let mut loginmsg = String::with_capacity(300);
loginmsg.push_str("You are not logged in, please <a href=\"");
loginmsg.push_str(BLOG_URL);
loginmsg.push_str("admin");
loginmsg.push_str("\">Login</a>");
output = hbs_template(TemplateBody::General(alert_danger(&loginmsg)), None, Some("Admin Test".to_string()), String::from("/admin-test"), admin, user, None, Some(start.0));
}
let express: Express = output.into();
express.compress( encoding )
}
// #[get("/admin-test", rank = 2)]
// pub fn hbs_admin_test_unauthorized(start: GenTimer, user: Option<UserCookie>, encoding: AcceptCompression, location: Location) -> Redirect {
// // Redirect::to("/admin?referrer=")
// admin_login(location)
// }
#[get("/admin", rank = 1)]
pub fn hbs_dashboard_admin_authorized(start: GenTimer, pagination: Page<Pagination>, conn: DbConn, user: Option<UserCookie>, admin: AdministratorCookie, flash_msg_opt: Option<FlashMessage>, encoding: AcceptCompression, uhits: UniqueHits) -> Express {
// let start = Instant::now();
// let flash = if let Some(flash) = flash_msg_opt {
// Some( alert_warning(flash.msg()) )
// } else {
// None
// };
// let output: Template = hbs_template(TemplateBody::General(format!("Welcome Administrator {user}. You are viewing the administrator dashboard page.", user=admin.username), flash), Some("Dashboard".to_string()), String::from("/admin"), Some(admin), user, None, Some(start.0));
// let end = start.0.elapsed();
// println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
// let express: Express = output.into();
// express.compress(encoding)
hbs_manage_full(start, "".to_string(), "".to_string(), pagination, conn, admin, user, flash_msg_opt, encoding, uhits)
}
// No longer needed - hbs_dashboard_admin_authorized takes care of flash messages
// #[get("/admin", rank = 2)]
#[get("/admin", rank = 7)]
pub fn hbs_dashboard_admin_flash(start: GenTimer, conn: DbConn, user: Option<UserCookie>, flash_msg_opt: Option<FlashMessage>, encoding: AcceptCompression, referrer: Referrer) -> Express {
// let start = Instant::now();
let output: Template;
let mut fields: HashMap<String, String> = HashMap::new();
if let Referrer(Some(refer)) = referrer {
println!("Referrer: {}", &refer);
fields.insert("referrer".to_string(), refer);
} else {
println!("No referrer");
}
if let Some(flash_msg) = flash_msg_opt {
let flash = Some( alert_danger(flash_msg.msg()) );
output = hbs_template(TemplateBody::LoginData(ADMIN_LOGIN_URL.to_string(), None, fields), flash, Some("Administrator Login".to_string()), String::from("/admin"), None, user, Some("set_login_focus();".to_string()), Some(start.0));
} else {
output = hbs_template(TemplateBody::LoginData(ADMIN_LOGIN_URL.to_string(), None, fields), None, Some("Administrator Login".to_string()), String::from("/admin"), None, user, Some("set_login_focus();".to_string()), Some(start.0));
}
let end = start.0.elapsed();
println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
let express: Express = output.into();
express.compress(encoding)
}
// No longer needed. Was getting errors because the dashboard_admin_retry_user() route
// named the qrystr parameter user which already has a variable binding, renamed and fixed it
// #[get("/admin/<userqry>")]
// pub fn dashboard_admin_retry_route(conn: DbConn, user: Option<UserCookie>, mut userqry: String, flash_msg_opt: Option<FlashMessage>, encoding: AcceptCompression) -> Express {
// unimplemented!()
// }
// #[get("/admin?<userqry>", rank=3)]
#[get("/admin?<userqry>", rank=4)]
pub fn hbs_dashboard_admin_retry_user(start: GenTimer, conn: DbConn, user: Option<UserCookie>, mut userqry: QueryUser, flash_opt: Option<FlashMessage>, encoding: AcceptCompression) -> Express {
// let start = Instant::now();
// let userqry: QueryUser = userqry_form.get();
let flash = process_flash(flash_opt);
// let mut fields: HashMap<String, String> = HashMap::new();
// if let Referrer(Some(refer)) = referrer {
// println!("Referrer: {}", &refer);
// fields.insert("referrer".to_string(), refer);
// }
// // user = login::sanitization::sanitize(&user);
let username = if &userqry.user != "" { Some(userqry.user.clone() ) } else { None };
// let flash = if let Some(f) = flash_msg_opt { Some(alert_danger(f.msg())) } else { None };
// let output = hbs_template(TemplateBody::LoginData(ADMIN_LOGIN_URL.to_string(), username, fields), flash, Some("Administrator Login".to_string()), String::from("/admin"), None, user, Some("set_login_focus();".to_string()), Some(start.0));
let output = hbs_template(TemplateBody::Login(ADMIN_LOGIN_URL.to_string(), username), flash, Some("Administrator Login".to_string()), String::from("/admin"), None, user, Some("set_login_focus();".to_string()), Some(start.0));
let end = start.0.elapsed();
println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
let express: Express = output.into();
express.compress(encoding)
}
// #[get("/admin?<rediruser>")]
#[get("/admin?<rediruser>", rank = 2)]
pub fn hbs_dashboard_admin_retry_redir(start: GenTimer, conn: DbConn, user: Option<UserCookie>, mut rediruser: QueryUserRedir, flash_opt: Option<FlashMessage>, encoding: AcceptCompression) -> Express {
// let start = Instant::now();
// let userqry: QueryUser = userqry_form.get();
let flash = process_flash(flash_opt);
let mut fields: HashMap<String, String> = HashMap::new();
if &rediruser.referrer != "" && &rediruser.referrer != "noredirect" {
println!("Adding referrer {}", &rediruser.referrer);
fields.insert("referrer".to_string(), rediruser.referrer.clone());
} else {
println!("No referring page\n{:?}", rediruser);
}
// if let Referrer(Some(refer)) = referrer {
// println!("Referrer: {}", &refer);
// fields.insert("referrer".to_string(), refer);
// }
// // user = login::sanitization::sanitize(&user);
let username = if &rediruser.user != "" { Some(rediruser.user.clone() ) } else { None };
// let flash = if let Some(f) = flash_msg_opt { Some(alert_danger(f.msg())) } else { None };
let output = hbs_template(TemplateBody::LoginData(ADMIN_LOGIN_URL.to_string(), username, fields), flash, Some("Administrator Login".to_string()), String::from("/admin"), None, user, Some("set_login_focus();".to_string()), Some(start.0));
let end = start.0.elapsed();
println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
let express: Express = output.into();
express.compress(encoding)
}
// #[get("/admin?<rediruser>")]
#[get("/admin?<rediruser>", rank = 3)]
pub fn hbs_dashboard_admin_retry_redir_only(start: GenTimer, conn: DbConn, user: Option<UserCookie>, mut rediruser: QueryRedir, flash_opt: Option<FlashMessage>, encoding: AcceptCompression) -> Express {
// let start = Instant::now();
// let userqry: QueryUser = userqry_form.get();
let flash = process_flash(flash_opt);
let mut fields: HashMap<String, String> = HashMap::new();
if &rediruser.referrer != "" && &rediruser.referrer != "noredirect" {
println!("Adding referrer {}", &rediruser.referrer);
fields.insert("referrer".to_string(), rediruser.referrer.clone());
} else {
println!("No referring page\n{:?}", rediruser);
}
// if let Referrer(Some(refer)) = referrer {
// println!("Referrer: {}", &refer);
// fields.insert("referrer".to_string(), refer);
// }
// // user = login::sanitization::sanitize(&user);
// let username = if &rediruser.user != "" { Some(rediruser.user.clone() ) } else { None };
let username = None;
// let flash = if let Some(f) = flash_msg_opt { Some(alert_danger(f.msg())) } else { None };
let output = hbs_template(TemplateBody::LoginData(ADMIN_LOGIN_URL.to_string(), username, fields), flash, Some("Administrator Login".to_string()), String::from("/admin"), None, user, Some("set_login_focus();".to_string()), Some(start.0));
let end = start.0.elapsed();
println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
let express: Express = output.into();
express.compress(encoding)
}
#[allow(unused_mut)]
// #[post("/admin", data = "<form>")]
#[post("/admin", data = "<form>")]
// pub fn hbs_process_admin_login(start: GenTimer, form: Form<LoginCont<AdministratorForm>>, user: Option<UserCookie>, mut cookies: Cookies) -> Result<Redirect, Flash<Redirect>> {
pub fn hbs_process_admin_login(start: GenTimer, form: Form<LoginCont<AdministratorForm>>, user: Option<UserCookie>, mut cookies: Cookies) -> Result<Redirect, Flash<Redirect>> {
// let start = Instant::now();
let login: AdministratorForm = form.get().form();
// let login: AdministratorForm = form.into_inner().form;
let mut err_temp: String;
let ok_addy: &str;
let err_addy: &str;
if &login.referrer != "" && &login.referrer != "noredierct" {
println!("Processing referrer: {}", &login.referrer);
let referring = if login.referrer.starts_with(BLOG_URL) {
&login.referrer[BLOG_URL.len()-1..]
} else {
&login.referrer
};
ok_addy = &referring;
err_addy = {
err_temp = String::with_capacity(referring.len() + 20);
err_temp.push_str("/admin?redir=");
err_temp.push_str(referring);
&err_temp
};
} else {
ok_addy = "/admin";
err_addy = "/admin";
}
// let ok_addy: &str = if &login.referrer != "" {
// &login.referrer
// } else {
// "/admin"
// };
println!("Forwaring to {} or {}", ok_addy, err_addy);
// let mut output = login.flash_redirect("/admin", "/admin", &mut cookies);
let mut output = login.flash_redirect(ok_addy, err_addy, &mut cookies);
if output.is_ok() {
println!("Login success, forwarding to {}", ok_addy);
if let Some(user_cookie) = user {
if &user_cookie.username != &login.username {
if let Ok(redir) = output {
let flash_message: Flash<Redirect> = Flash::error(
redir,
&format!("The regular user {} has been logged out. You cannot log in with two separate user accounts at once.",
&user_cookie.username
)
);
// Log the regular user out
// would use UserCookie::delete_cookie(cookies) but cookies already gets sent elsewhere
cookies.remove_private( Cookie::named( UserCookie::cookie_id() ) );
// the Err will still allow the cookies to get set to log the user in but will allow a message to be passed
output = Err( flash_message );
}
}
}
}
let end = start.0.elapsed();
println!("Processed in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
output
}
// #[get("/admin_logout")]
#[get("/admin_logout")]
pub fn hbs_logout_admin(admin: Option<AdministratorCookie>, mut cookies: Cookies) -> Result<Flash<Redirect>, Redirect> {
if let Some(_) = admin {
// cookies.remove_private(Cookie::named(AdministratorCookie::cookie_id()));
AdministratorCookie::delete_cookie(&mut cookies);
Ok(Flash::success(Redirect::to("/"), "Successfully logged out."))
} else {
Err(Redirect::to("/admin"))
}
}
#[get("/user", rank = 1)]
pub fn hbs_dashboard_user_authorized(start: GenTimer, conn: DbConn, admin: Option<AdministratorCookie>, user: UserCookie, flash_msg_opt: Option<FlashMessage>, encoding: AcceptCompression) -> Express {
// let start = Instant::now();
let flash = if let Some(flash) = flash_msg_opt {
Some( alert_warning(flash.msg()) )
} else {
None
};
let output: Template = hbs_template(TemplateBody::General(format!("Welcome User {user}. You are viewing the User dashboard page.", user=user.username)), flash, Some("User Dashboard".to_string()), String::from("/user"), admin, Some(user), None, Some(start.0));
let end = start.0.elapsed();
println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
let express: Express = output.into();
express.compress(encoding)
}
// No longer needed - hbs_dhasboard_user_authorized handles flash messages
#[get("/user", rank = 2)]
pub fn hbs_dashboard_user_flash(start: GenTimer, conn: DbConn, admin: Option<AdministratorCookie>, flash_msg_opt: Option<FlashMessage>, encoding: AcceptCompression) -> Express {
// let start = Instant::now();
let output: Template;
if let Some(flash_msg) = flash_msg_opt {
let flash = Some( alert_danger(flash_msg.msg()) );
output = hbs_template(TemplateBody::Login(USER_LOGIN_URL.to_string(), None), flash, Some("User Login".to_string()), String::from("/user"), admin, None, Some("set_login_focus();".to_string()), Some(start.0));
} else {
output = hbs_template(TemplateBody::Login(USER_LOGIN_URL.to_string(), None), None, Some("User Login".to_string()), String::from("/user"), admin, None, Some("set_login_focus();".to_string()), Some(start.0));
}
let end = start.0.elapsed();
println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
let express: Express = output.into();
express.compress(encoding)
}
// #[get("/user", rank = 3)]
// pub fn dashboard_user_login(conn: DbConn, admin: Option<AdministratorCookie>, encoding: AcceptCompression) -> Express {
// hbs_template(TemplateBody::Login(URL_LOGIN_USER.to_string(), None, None), Some("User Login".to_string()), String::from("/user"), admin, None, None, None)
// }
#[get("/user?<user>")]
pub fn hbs_dashboard_user_retry_user(start: GenTimer, conn: DbConn, admin: Option<AdministratorCookie>, mut user: QueryUser, flash_msg_opt: Option<FlashMessage>, encoding: AcceptCompression) -> Express {
// let start = Instant::now();
// user = login::sanitization::sanitize(&user);
let username = if &user.user != "" { Some(user.user.clone() ) } else { None };
let flash = if let Some(f) = flash_msg_opt { Some(alert_danger(f.msg())) } else { None };
let output = hbs_template(TemplateBody::Login(USER_LOGIN_URL.to_string(), username), flash, Some("User Login".to_string()), String::from("/user"), admin, None, Some("set_login_focus();".to_string()), Some(start.0));
let end = start.0.elapsed();
println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
let express: Express = output.into();
express.compress(encoding)
}
#[allow(unused_mut)]
#[post("/user", data = "<form>")]
pub fn hbs_process_user_login(start: GenTimer, form: Form<LoginCont<UserForm>>, admin: Option<AdministratorCookie>, mut cookies: Cookies) -> Result<Redirect, Flash<Redirect>> {
// let start = Instant::now();
let login: UserForm = form.get().form();
// let login: AdministratorForm = form.into_inner().form;
let mut output = login.flash_redirect("/user", "/user", &mut cookies);
if output.is_ok() {
if let Some(admin_cookie) = admin {
if &admin_cookie.username != &login.username {
if let Ok(redir) = output {
let flash_message: Flash<Redirect> = Flash::error(
redir,
&format!("The administrator user {} has been logged out. You cannot log in with two separate user accounts at once.",
&admin_cookie.username
)
);
// Log the regular user out
// would use UserCookie::delete_cookie(cookies) but cookies already gets sent elsewhere
cookies.remove_private( Cookie::named( AdministratorCookie::cookie_id() ) );
// the Err will still allow the cookies to get set to log the user in but will allow a message to be passed
output = Err( flash_message );
}
}
}
}
let end = start.0.elapsed();
println!("Processed in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
output
}
#[get("/user_logout")]
pub fn hbs_logout_user(admin: Option<UserCookie>, mut cookies: Cookies) -> Result<Flash<Redirect>, Redirect> {
if let Some(_) = admin {
// cookies.remove_private(Cookie::named(UserCookie::cookie_id()));
UserCookie::delete_cookie(&mut cookies);
Ok(Flash::success(Redirect::to("/"), "Successfully logged out."))
} else {
Err(Redirect::to("/user"))
}
}
// #[get("/view")]
// pub fn hbs_all_articles(start: GenTimer, conn: DbConn, admin: Option<AdministratorCookie>, user: Option<UserCookie>, encoding: AcceptCompression) -> Express {
// // let start = Instant::now();
// let output: Template;
// let results = Article::retrieve_all(conn, 0, Some(300), None, None, None, None);
// if results.len() != 0 {
// output = hbs_template(TemplateBody::Articles(results, None), Some("Viewing All Articles".to_string()), String::from("/"), admin, user, None, Some(start.0));
// } else {
// if admin.is_some() {
// output = hbs_template(TemplateBody::General("There are no articles<br>\n<a href =\"/insert\">Create Article</a>".to_string(), None), Some("Viewing All Articles".to_string()), String::from("/"), admin, user, None, Some(start.0));
// } else {
// output = hbs_template(TemplateBody::General("There are no articles.".to_string(), None), Some("Viewing All Articles".to_string()), String::from("/"), admin, user, None, Some(start.0));
// }
// }
// let end = start.0.elapsed();
// println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
// let express: Express = output.into();
// express.compress(encoding)
// }
// #[get("/view?<page>")]
// pub fn hbs_articles_page(start: GenTimer, page: ViewPage, conn: DbConn, admin: Option<AdministratorCookie>, user: Option<UserCookie>, encoding: AcceptCompression) -> Express {
// // let start = Instant::now();
// let results = Article::retrieve_all(conn, 0, Some(300), None, None, None, None);
// // Todo: Change title to: Viewing Article Page x/z
// let output: Template = hbs_template(TemplateBody::General("You are viewing paginated articles.".to_string(), None), Some("Viewing Articles".to_string()), String::from("/"), admin, user, None, Some(start.0));
// let end = start.0.elapsed();
// println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
// let express: Express = output.into();
// express.compress(encoding)
// }
#[get("/all_tags")]
pub fn hbs_tags_all(start: GenTimer, conn: DbConn, admin: Option<AdministratorCookie>, user: Option<UserCookie>, encoding: AcceptCompression, uhits: UniqueHits) -> Express {
// let start = Instant::now();
let qrystr = "SELECT COUNT(*) as cnt, unnest(tag) as untag FROM articles GROUP BY untag ORDER BY cnt DESC;";
let qry = conn.query(qrystr, &[]);
let mut tags: Vec<TagCount> = Vec::new();
if let Ok(result) = qry {
// let mut sizes: Vec<u16> = Vec::new();
for row in &result {
let c: i64 = row.get(0);
let c2: u32 = c as u32;
// sizes.push(c2 as u16);
let t: String = row.get(1);
let t2: String = t.trim_matches('\'').to_string();
let tagcount = TagCount {
// tag: titlecase(t.trim_matches('\'')),
url: t2.clone(),
tag: titlecase(&t2),
count: c2,
size: 0,
};
tags.push(tagcount);
}
if tags.len() > 4 {
if tags.len() > 7 {
let mut i = 0u16;
for mut v in &mut tags[0..6] {
v.size = 6-i;
i += 1;
}
} else {
let mut i = 0u16;
for mut v in &mut tags[0..3] {
v.size = (3-i)*2;
}
}
tags.sort_by(|a, b| a.tag.cmp(&b.tag));
}
}
let output: Template = hbs_template(TemplateBody::Tags(tags), None, Some("Viewing All Tags".to_string()), String::from("/all_tags"), admin, user, None, Some(start.0));
let end = start.0.elapsed();
println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
let express: Express = output.into();
express.compress(encoding)
}
// // NOT USED ANYMORE?
// // View paginated articles - pretty much just a test route
// #[get("/view_articles")]
// pub fn hbs_view_articles(start: GenTimer, pagination: Page<Pagination>, conn: DbConn, admin: Option<AdministratorCookie>, user: Option<UserCookie>, encoding: AcceptCompression, uhits: UniqueHits) -> Express {
//
// let total_query = "SELECT COUNT(*) as count FROM articles";
// let output: Template;
// if let Ok(rst) = conn.query(total_query, &[]) {
// if !rst.is_empty() && rst.len() == 1 {
// let row = rst.get(0);
// let count: i64 = row.get(0);
// let total_items: u32 = count as u32;
// let (ipp, cur, num_pages) = pagination.page_data(total_items);
// // let sql = pagination.sql("SELECT a.aid, a.title, a.posted, a.body, a.tag, a.description, u.userid, u.display, u.username FROM articles a JOIN users u ON (a.author = u.userid)", Some("posted DESC"));
// let sql = pagination.sql(&format!("SELECT a.aid, a.title, a.posted, description({}, a.body, a.description) as body, a.tag, a.description, u.userid, u.display, u.username FROM articles a JOIN users u ON (a.author = u.userid)", DESC_LIMIT), Some("posted DESC"));
// println!("Prepared paginated query:\n{}", sql);
// if let Some(results) = conn.articles(&sql) {
// // let results: Vec<Article> = conn.articles(&sql);
// if results.len() != 0 {
// let page_information = pagination.page_info(total_items);
// output = hbs_template(TemplateBody::ArticlesPages(results, pagination, total_items, Some(page_information), None), Some(format!("Viewing All Articles - Page {} of {}", cur, num_pages)), String::from("/view_articles"), admin, user, None, Some(start.0));
// let express: Express = output.into();
// return express.compress( encoding );
// }
// }
// // if let Ok(qry) = conn.query(sql, &[]) {
// // if !qry.is_empty() && rst.len() != 0 {
//
// // }
// // }
// }
// }
//
// output = hbs_template(TemplateBody::General(alert_danger("Database query failed."), None), Some("Viewing All Articles".to_string()), String::from("/view_articles"), admin, user, None, Some(start.0));
// let express: Express = output.into();
// express.compress( encoding )
// }
#[get("/tag?<tag>")]
pub fn hbs_articles_tag_redirect(tag: Tag) -> Redirect {
Redirect::to(&format!("/tag/{}", tag.tag))
}
#[get("/tag/<tag>")]
pub fn hbs_articles_tag(start: GenTimer, tag: String, pagination: Page<Pagination>, conn: DbConn, admin: Option<AdministratorCookie>, user: Option<UserCookie>, encoding: AcceptCompression, uhits: UniqueHits) -> Express {
let output: Template;
// let tag =
// vtags - Vector of Tags - Vector<Tags>
let vtags = split_tags(tag.clone());
if vtags.len() == 0 {
output = hbs_template(TemplateBody::General(alert_danger("No tag specified.")), None, Some("No Tag Specified".to_string()), String::from("/tag"), admin, user, None, Some(start.0));
} else {
let sql: String = if vtags.len() == 1 {
format!(" WHERE '{}' = ANY(a.tag)", sanitize_tag(&vtags[0]))
} else {
let mut tmp = String::with_capacity((vtags.len()*35) + 50);
// tmp.push_str(" WHERE ");
tmp.push_str(" WHERE '");
tmp.push_str(&sanitize_tag(&vtags[0]));
tmp.push_str("' = ANY(a.tag)");
// tmp.push_str("");
for t in &vtags[1..] {
tmp.push_str(" AND '");
tmp.push_str(&sanitize_tag(t));
tmp.push_str("' = ANY(a.tag)");
// tmp.push_str("");
}
tmp
};
let mut countqrystr = String::with_capacity(sql.len() + 60);
countqrystr.push_str("SELECT COUNT(*) as count FROM articles a");
countqrystr.push_str(&sql);
let mut qrystr = String::with_capacity(sql.len() + 60);
qrystr.push_str(&format!("SELECT a.aid, a.title, a.posted, description({}, a.body, a.description) as body, a.tag, a.description, u.userid, u.display, u.username FROM articles a JOIN users u ON (a.author = u.userid)", DESC_LIMIT));
qrystr.push_str(&sql);
println!("\nTag count query: {}\nTag articles query: {}\n", countqrystr, qrystr);
if let Ok(rst) = conn.query(&countqrystr, &[]) {
if !rst.is_empty() && rst.len() == 1 {
let countrow = rst.get(0);
let count: i64 = countrow.get(0);
let total_items: u32 = count as u32;
let (ipp, cur, num_pages) = pagination.page_data(total_items);
let pagesql = pagination.sql(&qrystr, Some("posted DESC"));
println!("Tag pagination query:\n{}", pagesql);
if let Some(results) = conn.articles(&pagesql) {
if results.len() != 0 {
let page_information = pagination.page_info(total_items);
output = hbs_template(TemplateBody::ArticlesPages(results, pagination, total_items, Some(page_information)), None, Some(format!("Viewing Tag {} - Page {} of {}", tag, cur, num_pages)), String::from("/tag"), admin, user, None, Some(start.0));
} else {
output = hbs_template(TemplateBody::General(alert_danger("No articles found with the specified tag.")), None, Some("Tag".to_string()), String::from("/tag"), admin, user, None, Some(start.0));
}
} else {
output = hbs_template(TemplateBody::General(alert_danger("No articles found with the specified tag.")), None, Some("Tag".to_string()), String::from("/tag"), admin, user, None, Some(start.0));
}
} else {
output = hbs_template(TemplateBody::General(alert_danger("No articles found with the specified tag.")), None, Some("Tag".to_string()), String::from("/tag"), admin, user, None, Some(start.0));
}
} else {
output = hbs_template(TemplateBody::General(alert_danger("No articles found with the specified tag.")), None, Some("Tag".to_string()), String::from("/tag"), admin, user, None, Some(start.0));
}
}
let express: Express = output.into();
express.compress( encoding )
// let total_query = "SELECT COUNT(*) as count FROM articles";
// let output: Template;
// if let Ok(rst) = conn.query(total_query, &[]) {
// if !rst.is_empty() && rst.len() == 1 {
// let row = rst.get(0);
// let count: i64 = row.get(0);
// let total_items: u32 = count as u32;
// let (ipp, cur, num_pages) = pagination.page_data(total_items);
// // let sql = pagination.sql("SELECT a.aid, a.title, a.posted, a.body, a.tag, a.description, u.userid, u.display, u.username FROM articles a JOIN users u ON (a.author = u.userid)", Some("posted DESC"));
// let sql = pagination.sql(&format!("SELECT a.aid, a.title, a.posted, description({}, a.body, a.description) as body, a.tag, a.description, u.userid, u.display, u.username FROM articles a JOIN users u ON (a.author = u.userid)", DESC_LIMIT), Some("posted DESC"));
// println!("Prepared paginated query:\n{}", sql);
// if let Some(results) = conn.articles(&sql) {
// // let results: Vec<Article> = conn.articles(&sql);
// if results.len() != 0 {
// let page_information = pagination.page_info(total_items);
// output = hbs_template(TemplateBody::ArticlesPages(results, pagination, total_items, Some(page_information), None), Some(format!("Viewing All Articles - Page {} of {}", cur, num_pages)), String::from("/view_articles"), admin, user, None, Some(start.0));
// let express: Express = output.into();
// return express.compress( encoding );
// }
// }
// // if let Ok(qry) = conn.query(sql, &[]) {
// // if !qry.is_empty() && rst.len() != 0 {
// // }
// // }
// }
// }
// output = hbs_template(TemplateBody::General(alert_danger("Database query failed."), None), Some("Viewing All Articles".to_string()), String::from("/view_articles"), admin, user, None, Some(start.0));
// let express: Express = output.into();
// express.compress( encoding )
// let output: Template;
// let tags = Some(split_tags(medium_sanitize(tag.tag.clone())));
// // limit, # body chars, min date, max date, tags, strings
// let results = Article::retrieve_all(conn, 0, Some(-1), None, None, tags, None);
// if results.len() != 0 {
// output = hbs_template(TemplateBody::Articles(results, None), Some(format!("Viewing Articles with Tags: {}", tag.tag)), String::from("/all_tags"), admin, user, None, Some(start.0));
// } else {
// output = hbs_template(TemplateBody::General(alert_danger("Could not find any articles with the specified tag."), None), Some(format!("Could not find any articles with the tag(s): {}", medium_sanitize(tag.tag) )), String::from("/tag"), admin, user, None, Some(start.0));
// }
// let end = start.0.elapsed();
// println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
// let express: Express = output.into();
// express.compress(encoding)
}
#[get("/article/<aid>/<title>")]
pub fn hbs_article_title(start: GenTimer, aid: ArticleId, title: Option<&RawStr>, conn: DbConn, admin: Option<AdministratorCookie>, user: Option<UserCookie>, encoding: AcceptCompression, uhits: UniqueHits) -> Express {
hbs_article_view(start, aid, conn, admin, user, encoding, uhits)
}
#[get("/article/<aid>")]
pub fn hbs_article_id(start: GenTimer, aid: ArticleId, conn: DbConn, admin: Option<AdministratorCookie>, user: Option<UserCookie>, encoding: AcceptCompression, uhits: UniqueHits) -> Express {
hbs_article_view(start, aid, conn, admin, user, encoding, uhits)
}
#[get("/article?<aid>")]
pub fn hbs_article_view(start: GenTimer, aid: ArticleId, conn: DbConn, admin: Option<AdministratorCookie>, user: Option<UserCookie>, encoding: AcceptCompression, uhits: UniqueHits) -> Express {
// let start = Instant::now();
let rst = aid.retrieve_with_conn(conn); // retrieve result
let mut output: Template;
if let Some(article) = rst {
let title = article.title.clone();
output = hbs_template(TemplateBody::Article(article), None, Some(title), String::from("/article"), admin, user, Some("enable_toc(true);".to_owned()), Some(start.0));
} else {
output = hbs_template(TemplateBody::General(alert_danger(&format!("Article {} not found.", aid.aid))), None, Some("Article Not Found".to_string()), String::from("/article"), admin, user, None, Some(start.0));
}
let end = start.0.elapsed();
println!("Served in {}.{:09} seconds", end.as_secs(), end.subsec_nanos());
let express: Express = output.into();
express.compress(encoding)
}
#[get("/article")]
pub fn hbs_article_not_found(start: GenTimer, conn: DbConn, admin: Option<AdministratorCookie>, user: Option<UserCookie>, encoding: AcceptCompression, uhits: UniqueHits) -> Express {
// let start = Instant::now();
let output: Template = hbs_template(TemplateBody::General(alert_danger("Article not found")), None, Some("Article not found".to_string()), String::from("/article"), admin, user, None, Some(start.0));