Validate API token for all API routes
This commit is contained in:
parent
538fc23a77
commit
2bd08a7b3f
1 changed files with 17 additions and 23 deletions
|
@ -31,7 +31,7 @@ pub fn routes(state: Arc<AppState>) -> Router<Body> {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn validate_api_token<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
|
pub async fn validate_api_token<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
|
||||||
let mut auth_header = req
|
let token = req
|
||||||
.headers()
|
.headers()
|
||||||
.get(http::header::AUTHORIZATION)
|
.get(http::header::AUTHORIZATION)
|
||||||
.and_then(|header| header.to_str().ok())
|
.and_then(|header| header.to_str().ok())
|
||||||
|
@ -40,8 +40,24 @@ pub async fn validate_api_token<B>(req: Request<B>, next: Next<B>) -> impl IntoR
|
||||||
StatusCode::BAD_REQUEST,
|
StatusCode::BAD_REQUEST,
|
||||||
"missing authorization header".to_string(),
|
"missing authorization header".to_string(),
|
||||||
)
|
)
|
||||||
|
})?
|
||||||
|
.strip_prefix("token ")
|
||||||
|
.ok_or_else(|| {
|
||||||
|
Error::Http(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"invalid authorization header".to_string(),
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
let state = req.extensions().get::<Arc<AppState>>().unwrap();
|
||||||
|
|
||||||
|
if token != state.api_token {
|
||||||
|
Err(Error::Http(
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
"invalid authorization token".to_string(),
|
||||||
|
))?
|
||||||
|
}
|
||||||
|
|
||||||
Ok::<_, Error>(next.run(req).await)
|
Ok::<_, Error>(next.run(req).await)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -163,25 +179,3 @@ async fn create_access_token(
|
||||||
encrypted_access_token,
|
encrypted_access_token,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[async_trait]
|
|
||||||
// pub trait RequestExt {
|
|
||||||
// async fn require_token(&self) -> tide::Result<()>;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// #[async_trait]
|
|
||||||
// impl RequestExt for Request {
|
|
||||||
// async fn require_token(&self) -> tide::Result<()> {
|
|
||||||
// let token = self
|
|
||||||
// .header("Authorization")
|
|
||||||
// .and_then(|header| header.get(0))
|
|
||||||
// .and_then(|header| header.as_str().strip_prefix("token "))
|
|
||||||
// .ok_or_else(|| surf::Error::from_str(403, "invalid authorization header"))?;
|
|
||||||
|
|
||||||
// if token == self.state().config.api_token {
|
|
||||||
// Ok(())
|
|
||||||
// } else {
|
|
||||||
// Err(tide::Error::from_str(403, "invalid authorization token"))
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue