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

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