Files
expenses/server/src/routes/extractors/auth/bearer.rs
T

55 lines
1.2 KiB
Rust

use axum::extract::FromRef;
use sqlx::PgPool;
use super::{AuthScheme, Authorizer, Principal};
use crate::{
domain::Secret,
repository::{self, RepositoryError},
};
#[derive(Debug)]
pub struct Bearer;
impl AuthScheme for Bearer {
const SCHEME: &'static str = "Bearer";
type Credentials = BearerToken;
type Error = BearerError;
fn credentials(token: &str) -> Result<Self::Credentials, Self::Error> {
Ok(BearerToken(token.to_string()))
}
}
impl<S> Authorizer<S> for Bearer
where
PgPool: FromRef<S>,
S: Send + Sync,
{
async fn authorize(
credentials: Self::Credentials,
state: &S,
) -> Result<Principal<Self>, Self::Error> {
let pool = PgPool::from_ref(state);
let token_hash = Secret::from(credentials.0).hash();
let token = repository::access_tokens::get_by_hash(&pool, &token_hash)
.await
.map_err(BearerError::Repository)?
.ok_or(BearerError::InvalidCredentials)?;
Ok(Principal::new(token.user_id))
}
}
pub struct BearerToken(String);
#[derive(Debug, thiserror::Error)]
pub enum BearerError {
#[error("invalid credentials")]
InvalidCredentials,
#[error(transparent)]
Repository(#[from] RepositoryError),
}