55 lines
1.2 KiB
Rust
55 lines
1.2 KiB
Rust
use axum::extract::FromRef;
|
|
use sqlx::PgPool;
|
|
|
|
use super::{AuthScheme, Authorizer, Principal};
|
|
use crate::{
|
|
crypto::hash_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 = hash_secret(&credentials.0);
|
|
let token = repository::tokens::get_by_access_token_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),
|
|
}
|