From 66c92fd865ea5983a4595fcd2eb7cf27080e0913 Mon Sep 17 00:00:00 2001 From: Josh Leeb-du Toit Date: Sun, 20 Jan 2019 11:15:08 +1100 Subject: [PATCH 1/2] Hold onto authorization header with ApiToken source Modify the `AuthenticationSource::ApiToken` variant to hold onto the authorization header that may be used to fetch the current user. --- src/middleware/current_user.rs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/middleware/current_user.rs b/src/middleware/current_user.rs index 6ff9c05e64a..7ee24063847 100644 --- a/src/middleware/current_user.rs +++ b/src/middleware/current_user.rs @@ -12,10 +12,10 @@ use crate::schema::users; #[derive(Debug, Clone, Copy)] pub struct CurrentUser; -#[derive(Debug, Copy, Clone, Eq, PartialEq)] +#[derive(Debug, Clone, Eq, PartialEq)] pub enum AuthenticationSource { SessionCookie, - ApiToken, + ApiToken { auth_header: String }, } impl Middleware for CurrentUser { @@ -41,15 +41,18 @@ impl Middleware for CurrentUser { } else { // Otherwise, look for an `Authorization` header on the request // and try to find a user in the database with a matching API token - let user = if let Some(headers) = req.headers().find("Authorization") { - User::find_by_api_token(&conn, headers[0]).ok() - } else { - None - }; - if let Some(user) = user { + let user_auth = req.headers().find("Authorization").and_then(|headers| { + let auth_header = headers[0].to_string(); + + User::find_by_api_token(&conn, &auth_header) + .ok() + .map(|user| (AuthenticationSource::ApiToken { auth_header }, user)) + }); + + if let Some((api_token, user)) = user_auth { // Attach the `User` model from the database to the request req.mut_extensions().insert(user); - req.mut_extensions().insert(AuthenticationSource::ApiToken); + req.mut_extensions().insert(api_token); } } From 8e3d3455beaf00d4db0bdecb73608546eca67876 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Fri, 4 Oct 2019 17:27:42 -0400 Subject: [PATCH 2/2] Fix clippy errors that I introduced while resolving merge conflicts --- src/middleware/current_user.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/middleware/current_user.rs b/src/middleware/current_user.rs index 3e4c51be3f9..ad760c88857 100644 --- a/src/middleware/current_user.rs +++ b/src/middleware/current_user.rs @@ -48,7 +48,7 @@ impl Middleware for CurrentUser { User::find_by_api_token(&conn, &auth_header) .map(|user| (AuthenticationSource::ApiToken { auth_header }, user)) .optional() - .map_err(|e| return Box::new(e) as Box)? + .map_err(|e| Box::new(e) as Box)? } else { None };