A very performant and light (2mb in memory) link shortener and tracker. Written in Rust and React and uses Postgres/SQLite.
1use actix_web::{dev::Payload, FromRequest, HttpRequest}; 2use jsonwebtoken::{decode, DecodingKey, Validation}; 3use std::future::{ready, Ready}; 4use crate::{error::AppError, models::Claims}; 5 6pub struct AuthenticatedUser { 7 pub user_id: i32, 8} 9 10impl FromRequest for AuthenticatedUser { 11 type Error = AppError; 12 type Future = Ready<Result<Self, Self::Error>>; 13 14 fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { 15 let auth_header = req.headers() 16 .get("Authorization") 17 .and_then(|h| h.to_str().ok()); 18 19 if let Some(auth_header) = auth_header { 20 if auth_header.starts_with("Bearer ") { 21 let token = &auth_header[7..]; 22 let secret = std::env::var("JWT_SECRET").unwrap_or_else(|_| "default_secret".to_string()); 23 24 match decode::<Claims>( 25 token, 26 &DecodingKey::from_secret(secret.as_bytes()), 27 &Validation::default() 28 ) { 29 Ok(token_data) => { 30 return ready(Ok(AuthenticatedUser { 31 user_id: token_data.claims.sub, 32 })); 33 } 34 Err(_) => return ready(Err(AppError::Unauthorized)), 35 } 36 } 37 } 38 39 ready(Err(AppError::Unauthorized)) 40 } 41}