|
| 1 | +use std::time::{SystemTime, UNIX_EPOCH}; |
| 2 | + |
| 3 | +use anyhow::Result; |
| 4 | +use axum::{ |
| 5 | + extract::{Request, State}, |
| 6 | + http::StatusCode, |
| 7 | + middleware::Next, |
| 8 | + response::Response, |
| 9 | + Json, RequestExt, |
| 10 | +}; |
| 11 | +use axum_extra::{ |
| 12 | + headers::{authorization::Bearer, Authorization}, |
| 13 | + TypedHeader, |
| 14 | +}; |
| 15 | +use jsonwebtoken::{decode, encode, Header, Validation}; |
| 16 | +use serde::{Deserialize, Serialize}; |
| 17 | + |
| 18 | +use super::{super::state::RouterState, ErrorResponse}; |
| 19 | + |
| 20 | +#[derive(Deserialize)] |
| 21 | +pub(in super::super) struct AuthenticateRequest {} |
| 22 | + |
| 23 | +#[derive(Serialize)] |
| 24 | +pub(in super::super) struct AuthenticateResponse { |
| 25 | + token: String, |
| 26 | +} |
| 27 | + |
| 28 | +#[derive(Deserialize, Serialize)] |
| 29 | +struct Claim { |
| 30 | + exp: u64, |
| 31 | +} |
| 32 | + |
| 33 | +pub(in super::super) async fn authenticate( |
| 34 | + State(state): State<RouterState>, |
| 35 | + Json(request): Json<AuthenticateRequest>, |
| 36 | +) -> Result<Json<AuthenticateResponse>, (StatusCode, Json<ErrorResponse>)> { |
| 37 | + let claim = Claim { |
| 38 | + exp: SystemTime::now() |
| 39 | + .duration_since(UNIX_EPOCH) |
| 40 | + .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, Json(e.to_string().into())))? |
| 41 | + .as_secs() |
| 42 | + + state.jwt.lifetime, |
| 43 | + }; |
| 44 | + let token = encode(&Header::default(), &claim, &state.jwt.encoding_key) |
| 45 | + .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, Json(e.to_string().into())))?; |
| 46 | + Ok(Json(AuthenticateResponse { token })) |
| 47 | +} |
| 48 | + |
| 49 | +pub(in super::super) async fn authorize( |
| 50 | + State(state): State<RouterState>, |
| 51 | + mut request: Request, |
| 52 | + next: Next, |
| 53 | +) -> Result<Response, (StatusCode, Json<ErrorResponse>)> { |
| 54 | + let TypedHeader(Authorization(bearer)) = request |
| 55 | + .extract_parts::<TypedHeader<Authorization<Bearer>>>() |
| 56 | + .await |
| 57 | + .map_err(|r| (StatusCode::BAD_REQUEST, Json(r.to_string().into())))?; |
| 58 | + decode::<Claim>(bearer.token(), &state.jwt.decoding_key, &Validation::default()).map_err(|error| { |
| 59 | + ( |
| 60 | + StatusCode::UNAUTHORIZED, |
| 61 | + Json(ErrorResponse { |
| 62 | + code: Some(error.to_string()), |
| 63 | + ..Default::default() |
| 64 | + }), |
| 65 | + ) |
| 66 | + })?; |
| 67 | + let response = next.run(request).await; |
| 68 | + Ok(response) |
| 69 | +} |
0 commit comments