Skip to content

Commit db7f5ca

Browse files
committed
Auto merge of #1599 - joshleeb:api-token-auth-header, r=carols10cents
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. Ref. #1548 (Task 4)
2 parents b2c8e18 + 8e3d345 commit db7f5ca

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

src/middleware/current_user.rs

Lines changed: 12 additions & 7 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 {
@@ -42,18 +42,23 @@ impl Middleware for CurrentUser {
4242
} else {
4343
// Otherwise, look for an `Authorization` header on the request
4444
// and try to find a user in the database with a matching API token
45-
let user = if let Some(headers) = req.headers().find("Authorization") {
46-
User::find_by_api_token(&conn, headers[0])
45+
let user_auth = if let Some(headers) = req.headers().find("Authorization") {
46+
let auth_header = headers[0].to_string();
47+
48+
User::find_by_api_token(&conn, &auth_header)
49+
.map(|user| (AuthenticationSource::ApiToken { auth_header }, user))
4750
.optional()
4851
.map_err(|e| Box::new(e) as Box<dyn Error + Send>)?
4952
} else {
5053
None
5154
};
55+
5256
drop(conn);
53-
if let Some(user) = user {
54-
// Attach the `User` model from the database to the request
57+
58+
if let Some((api_token, user)) = user_auth {
59+
// Attach the `User` model from the database and the API token to the request
5560
req.mut_extensions().insert(user);
56-
req.mut_extensions().insert(AuthenticationSource::ApiToken);
61+
req.mut_extensions().insert(api_token);
5762
}
5863
}
5964

0 commit comments

Comments
 (0)