Browse Source

Rework flash system

master
Dylan Baker 3 years ago
parent
commit
366eea570c
3 changed files with 64 additions and 27 deletions
  1. 40
    19
      src/routes.rs
  2. 23
    2
      templates/layout.html
  3. 1
    6
      templates/login.html

+ 40
- 19
src/routes.rs View File

19
     let posts: Vec<Post> = fs::get_all_posts().await?;
19
     let posts: Vec<Post> = fs::get_all_posts().await?;
20
     let mut context = Context::new();
20
     let mut context = Context::new();
21
     context.insert("posts", &posts);
21
     context.insert("posts", &posts);
22
-    render_response("index.html", &context, &req)
22
+    render_response("index.html", &context, req)
23
 }
23
 }
24
 
24
 
25
 pub async fn single_post(req: Request<State>) -> Result {
25
 pub async fn single_post(req: Request<State>) -> Result {
27
     let post_id = req.param("id")?;
27
     let post_id = req.param("id")?;
28
     let post = fs::get_one_post(post_id).await?;
28
     let post = fs::get_one_post(post_id).await?;
29
     context.insert("post", &post);
29
     context.insert("post", &post);
30
-    render_response("single.html", &context, &req)
30
+    render_response("single.html", &context, req)
31
 }
31
 }
32
 
32
 
33
 pub async fn edit_post(req: Request<State>) -> Result {
33
 pub async fn edit_post(req: Request<State>) -> Result {
36
     let mut post = fs::get_one_post(post_id).await?;
36
     let mut post = fs::get_one_post(post_id).await?;
37
     post.body = post.body.replace("<br>", "\n");
37
     post.body = post.body.replace("<br>", "\n");
38
     context.insert("post", &post);
38
     context.insert("post", &post);
39
-    render_response("edit.html", &context, &req)
39
+    render_response("edit.html", &context, req)
40
 }
40
 }
41
 
41
 
42
 pub async fn create_post(mut req: Request<State>) -> Result {
42
 pub async fn create_post(mut req: Request<State>) -> Result {
51
 pub async fn update_post(mut req: Request<State>) -> Result {
51
 pub async fn update_post(mut req: Request<State>) -> Result {
52
     let mut post: Post = req.body_form().await?;
52
     let mut post: Post = req.body_form().await?;
53
     post.save().await?;
53
     post.save().await?;
54
-    Ok(Redirect::new(format!("/posts/{}", post.id)).into())
54
+    req.session_mut().insert("flash_success", String::from("Post updated successfully"))?;
55
+    redirect(&format!("/posts/{}", post.id))
55
 }
56
 }
56
 
57
 
57
-pub async fn delete_post(req: Request<State>) -> Result {
58
+pub async fn delete_post(mut req: Request<State>) -> Result {
58
     let id: String = req.param("id")?;
59
     let id: String = req.param("id")?;
59
     fs::delete_post(id)?;
60
     fs::delete_post(id)?;
61
+    req.session_mut().insert("flash_success", String::from("Post deleted successfully"))?;
60
     let mut res = Response::new(StatusCode::Ok);
62
     let mut res = Response::new(StatusCode::Ok);
61
     res.set_body("{\"success\": \"true\"}");
63
     res.set_body("{\"success\": \"true\"}");
62
     res.set_content_type(mime::JSON);
64
     res.set_content_type(mime::JSON);
63
     Ok(res)
65
     Ok(res)
64
 }
66
 }
65
 
67
 
66
-pub async fn login_page(mut req: Request<State>) -> Result {
67
-    let mut context = Context::new();
68
-    match req.session_mut().get::<String>("flash_error") {
69
-        Some(error) => {
70
-            req.session_mut().remove("flash_error");
71
-            &context.insert("error", &error);
72
-        }
73
-        None => {}
74
-    }
75
-    render_response("login.html", &context, &req)
68
+pub async fn login_page(req: Request<State>) -> Result {
69
+    render_response("login.html", &Context::new(), req)
76
 }
70
 }
77
 
71
 
78
 pub async fn login(mut req: Request<State>) -> Result {
72
 pub async fn login(mut req: Request<State>) -> Result {
82
     if user.username == username && user.password == password {
76
     if user.username == username && user.password == password {
83
         req.session_mut().remove("logged_in");
77
         req.session_mut().remove("logged_in");
84
         req.session_mut().insert("logged_in", true)?;
78
         req.session_mut().insert("logged_in", true)?;
85
-        Ok(Redirect::new("/").into())
79
+        redirect("/")
86
     } else {
80
     } else {
87
         req.session_mut().remove("logged_in");
81
         req.session_mut().remove("logged_in");
88
         req.session_mut()
82
         req.session_mut()
89
             .insert("flash_error", "Invalid credentials")?;
83
             .insert("flash_error", "Invalid credentials")?;
90
-        Ok(Redirect::new(&req.state().login_path).into())
84
+        let login_path = req.state().login_path.clone();
85
+        redirect(&login_path)
91
     }
86
     }
92
 }
87
 }
93
 
88
 
100
 pub fn render_response(
95
 pub fn render_response(
101
     template: &str,
96
     template: &str,
102
     context: &Context,
97
     context: &Context,
103
-    req: &Request<State>,
98
+    req: Request<State>,
104
 ) -> Result<Response> {
99
 ) -> Result<Response> {
105
     let mut context = context.clone();
100
     let mut context = context.clone();
106
     let logged_in: bool = req.session().get("logged_in").unwrap_or(false);
101
     let logged_in: bool = req.session().get("logged_in").unwrap_or(false);
107
-    context.insert("logged_in", &logged_in);
108
     let login_path = &req.state().login_path;
102
     let login_path = &req.state().login_path;
103
+    context.insert("logged_in", &logged_in);
109
     context.insert("login_path", login_path);
104
     context.insert("login_path", login_path);
105
+    context.extend(prepare_flash_messages(req));
106
+
110
     let html = render_template(template, &context)?;
107
     let html = render_template(template, &context)?;
108
+
111
     let mut res = Response::new(StatusCode::Ok);
109
     let mut res = Response::new(StatusCode::Ok);
112
     res.set_body(html);
110
     res.set_body(html);
113
     res.set_content_type(mime::HTML);
111
     res.set_content_type(mime::HTML);
112
+
114
     Ok(res)
113
     Ok(res)
115
 }
114
 }
116
 
115
 
119
     let html = tera.render(template, &context)?;
118
     let html = tera.render(template, &context)?;
120
     Ok(html)
119
     Ok(html)
121
 }
120
 }
121
+
122
+fn redirect(path: &str) -> Result<Response> {
123
+    Ok(Redirect::new(path).into())
124
+}
125
+
126
+fn prepare_flash_messages(mut req: Request<State>) -> Context {
127
+    let mut context = Context::new();
128
+    context.insert("flash_error", &false);
129
+    context.insert("flash_success", &false);
130
+
131
+    for key in vec!["flash_error", "flash_success"] {
132
+        match req.session_mut().get::<String>(key) {
133
+            Some(value) => {
134
+                req.session_mut().remove(key);
135
+                &context.insert(key, &value);
136
+            }
137
+            None => {}
138
+        }
139
+    }
140
+
141
+    context
142
+}

+ 23
- 2
templates/layout.html View File

136
         padding: 0.5em;
136
         padding: 0.5em;
137
       }
137
       }
138
 
138
 
139
-      .error {
140
-        color: #942626;
139
+      .message {
140
+        border: 1px solid #383e37;
141
+        color: #fff;
142
+        margin: .5em 0;
143
+        padding: .25em 1.5em;
141
         text-align: center;
144
         text-align: center;
145
+        width: 100%;
146
+      }
147
+
148
+      .message--error {
149
+        background-color: #942626;
150
+      }
151
+
152
+      .message--success {
153
+        background-color: #289426;
142
       }
154
       }
143
 
155
 
144
       .error__heading {
156
       .error__heading {
166
         </form>
178
         </form>
167
         {% endif %}
179
         {% endif %}
168
       </header>
180
       </header>
181
+      <div class="messages">
182
+        {% if flash_error %}
183
+          <p class="message message--error">{{ flash_error }}</p>
184
+        {% endif %}
185
+
186
+        {% if flash_success %}
187
+          <p class="message message--success">{{ flash_success }}</p>
188
+        {% endif %}
189
+      </div>
169
       {% block content %} {% endblock %}
190
       {% block content %} {% endblock %}
170
     </div>
191
     </div>
171
     <script>
192
     <script>

+ 1
- 6
templates/login.html View File

15
     <label for="password" class="form__label">Password</label>
15
     <label for="password" class="form__label">Password</label>
16
     <input class="form__text-field" type="password" name="password" required />
16
     <input class="form__text-field" type="password" name="password" required />
17
   </div>
17
   </div>
18
-  {% if error %}
19
-  <div class="error">
20
-    <p class="error__message">{{ error }}</p>
21
-  </div>
22
-  {% endif %}
23
   <div class="form__field">
18
   <div class="form__field">
24
-    <input class="form__button" type="submit" value="Login" />
19
+    <input class="btn" type="submit" value="Login" />
25
   </div>
20
   </div>
26
 </form>
21
 </form>
27
 {% endblock %}
22
 {% endblock %}

Loading…
Cancel
Save