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.

routes.rs 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. use chrono::prelude::Local;
  2. use serde::{Deserialize, Serialize};
  3. use tera::{Context, Tera};
  4. use tide::http::mime;
  5. use tide::{Redirect, Request, Response, Result, StatusCode};
  6. use uuid::Uuid;
  7. use std::env;
  8. use crate::{fs, post::Post, State};
  9. #[derive(Debug, Serialize, Deserialize)]
  10. struct User {
  11. username: String,
  12. password: String,
  13. }
  14. pub async fn index(req: Request<State>) -> Result {
  15. let posts: Vec<Post> = fs::get_all_posts().await?;
  16. let mut context = Context::new();
  17. context.insert("posts", &posts);
  18. render_response("index.html", &context, req)
  19. }
  20. pub async fn single_post(req: Request<State>) -> Result {
  21. let mut context = Context::new();
  22. let post_id = req.param("id")?;
  23. let post = fs::get_one_post(post_id).await?;
  24. context.insert("post", &post);
  25. render_response("single.html", &context, req)
  26. }
  27. pub async fn edit_post(req: Request<State>) -> Result {
  28. let mut context = Context::new();
  29. let post_id = req.param("id")?;
  30. let mut post = fs::get_one_post(post_id).await?;
  31. post.body = post.body.replace("<br>", "\n");
  32. context.insert("post", &post);
  33. render_response("edit.html", &context, req)
  34. }
  35. pub async fn create_post(mut req: Request<State>) -> Result {
  36. let mut post: Post = req.body_form().await?;
  37. post.id = Uuid::new_v4().to_string();
  38. post.date = Local::now().date().naive_local().to_string();
  39. post.body = post.body.trim().to_owned();
  40. post.save().await?;
  41. Ok(Redirect::new("/").into())
  42. }
  43. pub async fn update_post(mut req: Request<State>) -> Result {
  44. let mut post: Post = req.body_form().await?;
  45. post.save().await?;
  46. req.session_mut().insert("flash_success", String::from("Post updated successfully"))?;
  47. redirect(&format!("/posts/{}", post.id))
  48. }
  49. pub async fn delete_post(mut req: Request<State>) -> Result {
  50. let id: String = req.param("id")?;
  51. fs::delete_post(id)?;
  52. req.session_mut().insert("flash_success", String::from("Post deleted successfully"))?;
  53. let mut res = Response::new(StatusCode::Ok);
  54. res.set_body("{\"success\": \"true\"}");
  55. res.set_content_type(mime::JSON);
  56. Ok(res)
  57. }
  58. pub async fn login_page(req: Request<State>) -> Result {
  59. render_response("login.html", &Context::new(), req)
  60. }
  61. pub async fn login(mut req: Request<State>) -> Result {
  62. let username = env::var("ADMIN_USERNAME")?;
  63. let password = env::var("ADMIN_PASSWORD")?;
  64. let user: User = req.body_form().await?;
  65. if user.username == username && user.password == password {
  66. req.session_mut().remove("logged_in");
  67. req.session_mut().insert("logged_in", true)?;
  68. redirect("/")
  69. } else {
  70. req.session_mut().remove("logged_in");
  71. req.session_mut()
  72. .insert("flash_error", "Invalid credentials")?;
  73. let login_path = req.state().login_path.clone();
  74. redirect(&login_path)
  75. }
  76. }
  77. pub async fn logout(mut req: Request<State>) -> Result {
  78. req.session_mut().remove("logged_in");
  79. req.session_mut().insert("logged_in", false)?;
  80. Ok(Redirect::new("/").into())
  81. }
  82. pub fn render_response(
  83. template: &str,
  84. context: &Context,
  85. req: Request<State>,
  86. ) -> Result<Response> {
  87. let mut context = context.clone();
  88. let logged_in: bool = req.session().get("logged_in").unwrap_or(false);
  89. let login_path = &req.state().login_path;
  90. context.insert("logged_in", &logged_in);
  91. context.insert("login_path", login_path);
  92. context.extend(prepare_flash_messages(req));
  93. let html = render_template(template, &context)?;
  94. let res = Response::builder(StatusCode::Ok)
  95. .body(html)
  96. .content_type(mime::HTML)
  97. .build();
  98. Ok(res)
  99. }
  100. pub fn render_template(template: &str, context: &Context) -> Result<String> {
  101. let tera = Tera::new("templates/**/*.html")?;
  102. let html = tera.render(template, &context)?;
  103. Ok(html)
  104. }
  105. fn redirect(path: &str) -> Result<Response> {
  106. Ok(Redirect::new(path).into())
  107. }
  108. fn prepare_flash_messages(mut req: Request<State>) -> Context {
  109. let mut context = Context::new();
  110. context.insert("flash_error", &false);
  111. context.insert("flash_success", &false);
  112. for key in vec!["flash_error", "flash_success"] {
  113. match req.session_mut().get::<String>(key) {
  114. Some(value) => {
  115. req.session_mut().remove(key);
  116. &context.insert(key, &value);
  117. }
  118. None => {}
  119. }
  120. }
  121. context
  122. }