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 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 async fn errors(mut res: Response) -> Result<Response> {
  34. let mut context = Context::new();
  35. match res.downcast_error::<async_std::io::Error>() {
  36. Some(e) => {
  37. context.insert("error", &e.to_string());
  38. let status = if let ErrorKind::NotFound = e.kind() {
  39. StatusCode::NotFound
  40. } else {
  41. StatusCode::InternalServerError
  42. };
  43. let body: String = routes::render_template("error.html", &context)?;
  44. res.set_body(body);
  45. res.set_status(status);
  46. }
  47. None => match res.status() {
  48. StatusCode::NotFound => {
  49. context.insert("error", "Page not found");
  50. res.set_body(routes::render_template("error.html", &context)?);
  51. }
  52. _ => {}
  53. },
  54. };
  55. res.set_content_type(mime::HTML);
  56. Ok(res)
  57. }