Auth: Add function to get AuthInfo for Request without using an Extractor
This commit is contained in:
parent
1ac49dbb60
commit
47f8e01210
1 changed files with 39 additions and 23 deletions
|
|
@ -1,9 +1,10 @@
|
|||
use std::fmt::Debug;
|
||||
use crate::auth::token::{TokenDTO, get_roles_from_token, get_token_from_key};
|
||||
use crate::storage::DbPool;
|
||||
use axum::body::Body;
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::http::request::Parts;
|
||||
use axum::http::{header, StatusCode};
|
||||
use crate::auth::token::{get_roles_from_token, get_token_from_key, TokenDTO};
|
||||
use crate::storage::DbPool;
|
||||
use axum::http::{HeaderMap, Request, StatusCode, header};
|
||||
use std::fmt::Debug;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AuthInfo {
|
||||
|
|
@ -11,27 +12,42 @@ pub struct AuthInfo {
|
|||
roles: Vec<String>,
|
||||
}
|
||||
|
||||
impl<> FromRequestParts<DbPool> for AuthInfo
|
||||
{
|
||||
impl FromRequestParts<DbPool> for AuthInfo {
|
||||
type Rejection = StatusCode;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &DbPool) -> Result<Self, Self::Rejection> {
|
||||
let auth_header = parts
|
||||
.headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok());
|
||||
async fn from_request_parts(
|
||||
parts: &mut Parts,
|
||||
state: &DbPool,
|
||||
) -> Result<Self, Self::Rejection> {
|
||||
let header = &parts.headers;
|
||||
|
||||
match auth_header {
|
||||
Some(auth_header) => {
|
||||
let token = get_token_from_key(auth_header, state).await;
|
||||
if token.is_err() {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
let token = token.unwrap();
|
||||
let roles = get_roles_from_token(&token, state).await;
|
||||
Ok(Self {token, roles})
|
||||
}
|
||||
_ => Err(StatusCode::UNAUTHORIZED),
|
||||
}
|
||||
inspect_with_header(state, &header).await
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn inspect_req(state: &DbPool, req: &Request<Body>) -> Result<AuthInfo, StatusCode> {
|
||||
let header = req.headers();
|
||||
inspect_with_header(state, header).await
|
||||
}
|
||||
|
||||
pub async fn inspect_with_header(
|
||||
state: &DbPool,
|
||||
header: &HeaderMap,
|
||||
) -> Result<AuthInfo, StatusCode> {
|
||||
let auth_header = header
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok());
|
||||
|
||||
match auth_header {
|
||||
Some(auth_value) => {
|
||||
let token = get_token_from_key(auth_value, state).await;
|
||||
if token.is_err() {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
let token = token.unwrap();
|
||||
let roles = get_roles_from_token(&token, state).await;
|
||||
Ok(AuthInfo { token, roles })
|
||||
}
|
||||
None => Err(StatusCode::UNAUTHORIZED),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue