A very performant and light (2mb in memory) link shortener and tracker. Written in Rust and React and uses Postgres/SQLite.
at master 1.4 kB view raw
1use crate::{error::AppError, models::Claims}; 2use actix_web::{dev::Payload, FromRequest, HttpRequest}; 3use jsonwebtoken::{decode, DecodingKey, Validation}; 4use std::future::{ready, Ready}; 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 16 .headers() 17 .get("Authorization") 18 .and_then(|h| h.to_str().ok()); 19 20 if let Some(auth_header) = auth_header { 21 if auth_header.starts_with("Bearer ") { 22 let token = &auth_header[7..]; 23 let secret = 24 std::env::var("JWT_SECRET").unwrap_or_else(|_| "default_secret".to_string()); 25 match decode::<Claims>( 26 token, 27 &DecodingKey::from_secret(secret.as_bytes()), 28 &Validation::default(), 29 ) { 30 Ok(token_data) => { 31 return ready(Ok(AuthenticatedUser { 32 user_id: token_data.claims.sub, 33 })); 34 } 35 Err(_) => return ready(Err(AppError::Unauthorized)), 36 } 37 } 38 } 39 ready(Err(AppError::Unauthorized)) 40 } 41} 42