1- use axum:: {
2- body:: Body ,
3- http:: { header:: HeaderMap , Response , StatusCode } ,
4- response:: IntoResponse ,
5- Json ,
6- } ;
1+ use axum:: http:: { header:: HeaderMap , StatusCode } ;
2+ use axum:: response:: { IntoResponse , Json } ;
73use base64:: { engine:: general_purpose, Engine as _} ;
84
5+ #[ derive( Debug ) ]
6+ pub struct AuthError {
7+ pub status : StatusCode ,
8+ pub message : & ' static str ,
9+ }
10+
11+ impl AuthError {
12+ pub fn unauthorized ( message : & ' static str ) -> Self {
13+ Self {
14+ status : StatusCode :: UNAUTHORIZED ,
15+ message,
16+ }
17+ }
18+
19+ pub fn bad_request ( message : & ' static str ) -> Self {
20+ Self {
21+ status : StatusCode :: BAD_REQUEST ,
22+ message,
23+ }
24+ }
25+ }
26+
27+ impl IntoResponse for AuthError {
28+ fn into_response ( self ) -> axum:: response:: Response {
29+ ( self . status , Json ( self . message ) ) . into_response ( )
30+ }
31+ }
32+
933pub fn check_auth (
1034 user_value : String ,
1135 pass_value : String ,
1236 headers : & HeaderMap ,
13- ) -> Result < ( ) , Response < Body > > {
14- let unauthorized = |msg| ( StatusCode :: UNAUTHORIZED , Json ( msg) ) . into_response ( ) ;
15- let bad_request = |msg| ( StatusCode :: BAD_REQUEST , Json ( msg) ) . into_response ( ) ;
16-
37+ ) -> Result < ( ) , AuthError > {
1738 let auth_header = headers
1839 . get ( "Authorization" )
19- . ok_or_else ( || unauthorized ( "No Authorization header" ) ) ?;
40+ . ok_or ( AuthError :: unauthorized ( "No Authorization header" ) ) ?;
2041 let auth_str = auth_header
2142 . to_str ( )
22- . map_err ( |_| bad_request ( "Invalid Authorization header" ) ) ?;
43+ . map_err ( |_| AuthError :: bad_request ( "Invalid Authorization header" ) ) ?;
2344 let auth = auth_str
2445 . strip_prefix ( "Basic " )
25- . ok_or_else ( || bad_request ( "Invalid Authorization header" ) ) ?;
46+ . ok_or ( AuthError :: bad_request ( "Invalid Authorization header" ) ) ?;
2647 let decoded = general_purpose:: STANDARD
2748 . decode ( auth)
28- . map_err ( |_| bad_request ( "Invalid Authorization header: couldn't decode base64" ) ) ?;
49+ . map_err ( |_| AuthError :: bad_request ( "Invalid Authorization header: couldn't decode base64" ) ) ?;
2950 let auth = String :: from_utf8 ( decoded) . map_err ( |_| {
30- bad_request ( "Invalid Authorization header: couldn't convert dec/* o */ded utf8 to string" )
51+ AuthError :: bad_request ( "Invalid Authorization header: couldn't convert decoded utf8 to string" )
3152 } ) ?;
3253
3354 let mut auth_parts = auth. splitn ( 2 , ':' ) ;
@@ -37,7 +58,7 @@ pub fn check_auth(
3758 ) ;
3859
3960 if user != user_value || pass != pass_value {
40- return Err ( unauthorized (
61+ return Err ( AuthError :: unauthorized (
4162 "Invalid Authorization header: incorrect username or password" ,
4263 ) ) ;
4364 }
0 commit comments