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.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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, State};
  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<State>,
  22. next: Next<'a, State>,
  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. let login_path = &req.state().login_path;
  30. Ok(Redirect::new(login_path).into())
  31. }
  32. })
  33. }
  34. pub fn require_guest<'a>(
  35. req: Request<State>,
  36. next: Next<'a, State>,
  37. ) -> Pin<Box<dyn Future<Output = Result> + 'a + Send>> {
  38. Box::pin(async {
  39. let logged_in: bool = req.session().get("logged_in").unwrap_or(false);
  40. if logged_in {
  41. Ok(Redirect::new("/").into())
  42. } else {
  43. Ok(next.run(req).await)
  44. }
  45. })
  46. }
  47. pub async fn errors(mut res: Response) -> Result<Response> {
  48. let mut context = Context::new();
  49. match res.downcast_error::<async_std::io::Error>() {
  50. Some(e) => {
  51. context.insert("error", &e.to_string());
  52. let status = if let ErrorKind::NotFound = e.kind() {
  53. StatusCode::NotFound
  54. } else {
  55. StatusCode::InternalServerError
  56. };
  57. let body: String = routes::render_template("error.html", &context)?;
  58. res.set_body(body);
  59. res.set_status(status);
  60. res.set_content_type(mime::HTML);
  61. }
  62. None => match res.status() {
  63. StatusCode::NotFound => {
  64. context.insert("error", "Page not found");
  65. res.set_body(routes::render_template("error.html", &context)?);
  66. res.set_content_type(mime::HTML);
  67. }
  68. _ => {}
  69. },
  70. };
  71. Ok(res)
  72. }