37 lines
962 B
Rust
37 lines
962 B
Rust
use crate::state::ArcState;
|
|
use async_trait::async_trait;
|
|
use axum::{extract::FromRequestParts, http::request::Parts};
|
|
use hyper::StatusCode;
|
|
|
|
pub struct AuthState {
|
|
pub api_key: String,
|
|
pub admin: bool,
|
|
}
|
|
|
|
pub struct Auth(pub AuthState);
|
|
|
|
#[async_trait]
|
|
impl FromRequestParts<ArcState> for Auth {
|
|
type Rejection = StatusCode;
|
|
|
|
async fn from_request_parts(
|
|
parts: &mut Parts,
|
|
state: &ArcState,
|
|
) -> Result<Self, Self::Rejection> {
|
|
let header = parts
|
|
.headers
|
|
.get("Authorization")
|
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
|
let header = header.to_str().unwrap();
|
|
|
|
let row = sqlx::query!("select admin from api_keys where key = $1", header)
|
|
.fetch_one(&state.db)
|
|
.await
|
|
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
|
|
|
return Ok(Auth(AuthState {
|
|
api_key: header.to_string(),
|
|
admin: row.admin,
|
|
}));
|
|
}
|
|
}
|