You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.rs 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. use tide::{
  2. http::mime,
  3. sessions::{CookieStore, SessionMiddleware},
  4. Next, Redirect, Request, Response, Result, StatusCode,
  5. };
  6. use std::{env, future::Future, io::ErrorKind, pin::Pin};
  7. use tera::Context;
  8. use crate::routes;
  9. pub fn session() -> SessionMiddleware<CookieStore> {
  10. SessionMiddleware::new(
  11. CookieStore::new(),
  12. env::var("TIDE_SECRET")
  13. .expect(
  14. "Please provide a TIDE_SECRET value of at \
  15. least 32 bytes in order to run this example",
  16. )
  17. .as_bytes(),
  18. )
  19. }
  20. pub fn require_auth<'a>(
  21. req: Request<()>,
  22. next: Next<'a, ()>,
  23. ) -> Pin<Box<dyn Future<Output = Result> + 'a + Send>> {
  24. Box::pin(async {
  25. let logged_in: bool = req.session().get("logged_in").unwrap_or(false);
  26. if logged_in {
  27. Ok(next.run(req).await)
  28. } else {
  29. Ok(Redirect::new("/login").into())
  30. }
  31. })
  32. }
  33. pub fn require_guest<'a>(
  34. req: Request<()>,
  35. next: Next<'a, ()>,
  36. ) -> Pin<Box<dyn Future<Output = Result> + 'a + Send>> {
  37. Box::pin(async {
  38. let logged_in: bool = req.session().get("logged_in").unwrap_or(false);
  39. if logged_in {
  40. Ok(Redirect::new("/").into())
  41. } else {
  42. Ok(next.run(req).await)
  43. }
  44. })
  45. }
  46. pub async fn errors(mut res: Response) -> Result<Response> {
  47. let mut context = Context::new();
  48. match res.downcast_error::<async_std::io::Error>() {
  49. Some(e) => {
  50. context.insert("error", &e.to_string());
  51. let status = if let ErrorKind::NotFound = e.kind() {
  52. StatusCode::NotFound
  53. } else {
  54. StatusCode::InternalServerError
  55. };
  56. let body: String = routes::render_template("error.html", &context)?;
  57. res.set_body(body);
  58. res.set_status(status);
  59. }
  60. None => match res.status() {
  61. StatusCode::NotFound => {
  62. context.insert("error", "Page not found");
  63. res.set_body(routes::render_template("error.html", &context)?);
  64. }
  65. _ => {}
  66. },
  67. };
  68. res.set_content_type(mime::HTML);
  69. Ok(res)
  70. }