@@ -6,16 +6,17 @@ use diesel::prelude::*;
66use crate :: db:: RequestTransaction ;
77use crate :: util:: errors:: { std_error, CargoResult , ChainError , Unauthorized } ;
88
9+ use crate :: models:: ApiToken ;
910use crate :: models:: User ;
1011use crate :: schema:: users;
1112
1213#[ derive( Debug , Clone , Copy ) ]
1314pub struct CurrentUser ;
1415
15- #[ derive( Debug , Clone , Eq , PartialEq ) ]
16+ #[ derive( Debug , Copy , Clone , Eq , PartialEq ) ]
1617pub enum AuthenticationSource {
1718 SessionCookie ,
18- ApiToken { auth_header : String } ,
19+ ApiToken { api_token_id : i32 } ,
1920}
2021
2122impl Middleware for CurrentUser {
@@ -42,19 +43,23 @@ impl Middleware for CurrentUser {
4243 } else {
4344 // Otherwise, look for an `Authorization` header on the request
4445 // and try to find a user in the database with a matching API token
45- let user_auth = req. headers ( ) . find ( "Authorization" ) . and_then ( |headers| {
46- let auth_header = headers[ 0 ] . to_string ( ) ;
47-
48- User :: find_by_api_token ( & conn, & auth_header)
49- . ok ( )
50- . map ( |user| ( AuthenticationSource :: ApiToken { auth_header } , user) )
51- } ) ;
46+ let user_and_token_id = if let Some ( headers) = req. headers ( ) . find ( "Authorization" ) {
47+ ApiToken :: find_by_api_token_and_revoked ( & conn, headers[ 0 ] , false )
48+ . and_then ( |api_token| {
49+ User :: find ( & conn, api_token. user_id ) . map ( |user| ( user, api_token. id ) )
50+ } )
51+ . optional ( )
52+ . map_err ( |e| Box :: new ( e) as Box < dyn Error + Send > ) ?
53+ } else {
54+ None
55+ } ;
5256 drop ( conn) ;
53-
54- if let Some ( ( api_token , user ) ) = user_auth {
57+
58+ if let Some ( ( user , api_token_id ) ) = user_and_token_id {
5559 // Attach the `User` model from the database to the request
5660 req. mut_extensions ( ) . insert ( user) ;
57- req. mut_extensions ( ) . insert ( api_token) ;
61+ req. mut_extensions ( )
62+ . insert ( AuthenticationSource :: ApiToken { api_token_id } ) ;
5863 }
5964 }
6065
0 commit comments