feat: first extractor

This commit is contained in:
Sandro Eiler 2023-10-07 22:33:50 +02:00
parent 88c4045d33
commit a38438a700
5 changed files with 54 additions and 1 deletions

18
src/ctx.rs Normal file
View file

@ -0,0 +1,18 @@
#[derive(Debug, Clone)]
pub struct Ctx {
user_id: u64,
}
// Constructor
impl Ctx {
pub fn new(user_id: u64) -> Self {
Self { user_id }
}
}
// Property Accessors.
impl Ctx {
pub fn user_id(&self) -> u64 {
self.user_id
}
}

View file

@ -16,7 +16,7 @@ use serde::Deserialize;
use tower_http::services::ServeDir;
use tower_cookies::CookieManagerLayer;
mod ctx;
mod error;
mod web;
mod model;

View file

@ -1,9 +1,14 @@
use async_trait::async_trait;
use axum::RequestPartsExt;
use axum::extract::FromRequestParts;
use axum::http::Request;
use axum::http::request::Parts;
use axum::middleware::Next;
use axum::response::Response;
use lazy_regex::regex_captures;
use tower_cookies::Cookies;
use crate::ctx::Ctx;
use crate::web::AUTH_TOKEN;
use crate::{Error, Result};
@ -25,6 +30,34 @@ pub async fn mw_require_auth<B>(
Ok(next.run(req).await)
}
// region: --- Ctx Extractor
// TODO: Find out what all this syntax means
#[async_trait]
impl<S: Send + Sync> FromRequestParts<S> for Ctx {
type Rejection = Error;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self> {
println!("->> {:<12} - Ctx", "EXTRACTOR");
// Use the cookies extractor.
let cookies = parts.extract::<Cookies>().await.unwrap();
let auth_token = cookies.get(AUTH_TOKEN).map(|c| c.value().to_string());
// Parse token.
let (user_id, exp, sign) = auth_token
.ok_or(Error::AuthFailNoAuthTokenCookie)
.and_then(parse_token)?;
// TODO: Token components validation.
Ok(Ctx::new(user_id))
}
}
// endregion: --- Ctx Extractor
/// Parse a token of format `user-[user-id].[expiration].[signature]`
/// Returns (user-id, expiration, signature)
fn parse_token(token: String) -> Result<(u64, String, String)> {