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 { Ok(BearerToken(token.to_string())) } } impl Authorizer for Bearer where PgPool: FromRef, S: Send + Sync, { async fn authorize( credentials: Self::Credentials, state: &S, ) -> Result, 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), }