about summary refs log tree commit diff
diff options
context:
space:
mode:
authorVincent Ambo <tazjin@gmail.com>2018-04-09T07·10+0200
committerVincent Ambo <tazjin@gmail.com>2018-04-09T07·11+0200
commitef5e8ec8bd2cf06cdc48b7d77ec9a85b370b4433 (patch)
tree877010e87ee3451f588c39b5a61a2b481d3a38f3
parentd91dec28f8aa1eacbcce697f232902ad09d79523 (diff)
feat(handlers): Add RequireLogin middleware
Adds a middleware that automatically redirects users to the login page
if they don't have an active session (i.e. 'author' set).
-rw-r--r--src/handlers.rs29
-rw-r--r--src/oidc.rs2
2 files changed, 27 insertions, 4 deletions
diff --git a/src/handlers.rs b/src/handlers.rs
index 0531bb1742e7..e709fdd2023c 100644
--- a/src/handlers.rs
+++ b/src/handlers.rs
@@ -6,8 +6,9 @@
 //! project root.
 
 use actix::prelude::{Addr, Syn};
+use actix_web;
 use actix_web::*;
-use actix_web::middleware::RequestSession;
+use actix_web::middleware::{Started, Middleware, RequestSession};
 use db::*;
 use errors::{Result, ConverseError};
 use futures::Future;
@@ -120,6 +121,8 @@ pub fn login(state: State<AppState>) -> ConverseResponse {
         .responder()
 }
 
+const AUTHOR: &'static str = "author";
+
 pub fn callback(state: State<AppState>,
                 data: Form<CodeResponse>,
                 mut req: HttpRequest<AppState>) -> ConverseResponse {
@@ -128,10 +131,30 @@ pub fn callback(state: State<AppState>,
         .and_then(move |result| {
             let author = result?;
             info!("Setting cookie for {} after callback", author.name);
-            req.session().set("author_name", author.name)?;
-            req.session().set("author_email", author.email)?;
+            req.session().set(AUTHOR, author)?;
             Ok(HttpResponse::SeeOther()
                .header("Location", "/")
                .finish())})
         .responder()
 }
+
+
+/// Middleware used to enforce logins unceremonially.
+pub struct RequireLogin;
+
+impl <S> Middleware<S> for RequireLogin {
+    fn start(&self, req: &mut HttpRequest<S>) -> actix_web::Result<Started> {
+        let has_author = req.session().get::<Author>(AUTHOR)?.is_some();
+        let is_oidc_req = req.path().starts_with("/oidc");
+
+        if !is_oidc_req && !has_author {
+            Ok(Started::Response(
+                HttpResponse::SeeOther()
+                    .header("Location", "/oidc/login")
+                    .finish()
+            ))
+        } else {
+            Ok(Started::Done)
+        }
+    }
+}
diff --git a/src/oidc.rs b/src/oidc.rs
index bd2044ce5c9b..09f7f7b6e354 100644
--- a/src/oidc.rs
+++ b/src/oidc.rs
@@ -42,7 +42,7 @@ pub struct CodeResponse {
 
 /// This struct represents the data extracted from the ID token and
 /// stored in the user's session.
-#[derive(Debug)]
+#[derive(Debug, Serialize, Deserialize)]
 pub struct Author {
     pub name: String,
     pub email: String,