Skip to content

Commit 66c92fd

Browse files
author
Josh Leeb-du Toit
committed
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.
1 parent 776217c commit 66c92fd

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

src/middleware/current_user.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@ use crate::schema::users;
1212
#[derive(Debug, Clone, Copy)]
1313
pub struct CurrentUser;
1414

15-
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
15+
#[derive(Debug, Clone, Eq, PartialEq)]
1616
pub enum AuthenticationSource {
1717
SessionCookie,
18-
ApiToken,
18+
ApiToken { auth_header: String },
1919
}
2020

2121
impl Middleware for CurrentUser {
@@ -41,15 +41,18 @@ impl Middleware for CurrentUser {
4141
} else {
4242
// Otherwise, look for an `Authorization` header on the request
4343
// and try to find a user in the database with a matching API token
44-
let user = if let Some(headers) = req.headers().find("Authorization") {
45-
User::find_by_api_token(&conn, headers[0]).ok()
46-
} else {
47-
None
48-
};
49-
if let Some(user) = user {
44+
let user_auth = req.headers().find("Authorization").and_then(|headers| {
45+
let auth_header = headers[0].to_string();
46+
47+
User::find_by_api_token(&conn, &auth_header)
48+
.ok()
49+
.map(|user| (AuthenticationSource::ApiToken { auth_header }, user))
50+
});
51+
52+
if let Some((api_token, user)) = user_auth {
5053
// Attach the `User` model from the database to the request
5154
req.mut_extensions().insert(user);
52-
req.mut_extensions().insert(AuthenticationSource::ApiToken);
55+
req.mut_extensions().insert(api_token);
5356
}
5457
}
5558

0 commit comments

Comments
 (0)