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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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, util, 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. post.html = post.generate_html();
  34. context.insert("post", &post);
  35. render_html_response("edit.html", &context, req)
  36. }
  37. pub async fn create_post(mut req: Request<State>) -> Result {
  38. let mut post: Post = req.body_form().await?;
  39. post.id = Uuid::new_v4().to_string();
  40. post.date = Local::now().date().naive_local().to_string();
  41. post.body = post.body.trim().to_owned();
  42. post.html = post.generate_html();
  43. post.save().await?;
  44. Ok(Redirect::new("/").into())
  45. }
  46. pub async fn update_post(mut req: Request<State>) -> Result {
  47. let mut post: Post = req.body_form().await?;
  48. post.html = post.generate_html();
  49. post.save().await?;
  50. req.session_mut()
  51. .insert("flash_success", String::from("Post updated successfully"))?;
  52. redirect(&format!("/posts/{}", post.id))
  53. }
  54. pub async fn delete_post(mut req: Request<State>) -> Result {
  55. let id: String = req.param("id")?;
  56. fs::delete_post(id)?;
  57. req.session_mut()
  58. .insert("flash_success", String::from("Post deleted successfully"))?;
  59. render_json_response(json!({ "success": "true" }))
  60. }
  61. pub async fn preview_post(mut req: Request<State>) -> Result {
  62. let body: String = req.body_string().await?;
  63. let html = util::generate_html(&body);
  64. render_json_response(json!({ "body": html }))
  65. }
  66. pub async fn login_page(req: Request<State>) -> Result {
  67. render_html_response("login.html", &Context::new(), req)
  68. }
  69. pub async fn login(mut req: Request<State>) -> Result {
  70. let username = env::var("ADMIN_USERNAME")?;
  71. let password = env::var("ADMIN_PASSWORD")?;
  72. let user: User = req.body_form().await?;
  73. if user.username == username && user.password == password {
  74. req.session_mut().insert("logged_in", true)?;
  75. redirect("/")
  76. } else {
  77. req.session_mut().remove("logged_in");
  78. req.session_mut()
  79. .insert("flash_error", "Invalid credentials")?;
  80. let login_path = req.state().login_path.clone();
  81. redirect(&login_path)
  82. }
  83. }
  84. pub async fn logout(mut req: Request<State>) -> Result {
  85. req.session_mut().insert("logged_in", false)?;
  86. Ok(Redirect::new("/").into())
  87. }
  88. pub fn render_html_response(
  89. template: &str,
  90. context: &Context,
  91. req: Request<State>,
  92. ) -> Result<Response> {
  93. let mut context = context.clone();
  94. let logged_in: bool = req.session().get("logged_in").unwrap_or(false);
  95. let login_path = &req.state().login_path;
  96. context.insert("logged_in", &logged_in);
  97. context.insert("login_path", login_path);
  98. context.extend(prepare_flash_messages(req));
  99. let html = render_template(template, &context)?;
  100. let res = Response::builder(StatusCode::Ok)
  101. .body(html)
  102. .content_type(mime::HTML)
  103. .build();
  104. Ok(res)
  105. }
  106. pub fn render_json_response(json: serde_json::Value) -> Result<Response> {
  107. let res = Response::builder(StatusCode::Ok)
  108. .body(json)
  109. .content_type(mime::JSON)
  110. .build();
  111. Ok(res)
  112. }
  113. fn redirect(path: &str) -> Result<Response> {
  114. Ok(Redirect::new(path).into())
  115. }
  116. pub fn render_template(template: &str, context: &Context) -> Result<String> {
  117. let tera = Tera::new("templates/**/*.html")?;
  118. let html = tera.render(template, &context)?;
  119. Ok(html)
  120. }
  121. fn prepare_flash_messages(mut req: Request<State>) -> Context {
  122. let mut context = Context::new();
  123. context.insert("flash_error", &false);
  124. context.insert("flash_success", &false);
  125. for key in vec!["flash_error", "flash_success"] {
  126. match req.session_mut().get::<String>(key) {
  127. Some(value) => {
  128. req.session_mut().remove(key);
  129. &context.insert(key, &value);
  130. }
  131. None => {}
  132. }
  133. }
  134. context
  135. }