From 57735ede3f65c45b08e04c65c11fbf5f67db7101 Mon Sep 17 00:00:00 2001 From: Artemy Date: Tue, 26 Jul 2022 20:33:02 +0300 Subject: [PATCH] feat: authorisation (OS-9) --- src/main.rs | 40 ++++++++++++++++++++++++++++++++++++++++ src/routes.rs | 2 ++ 2 files changed, 42 insertions(+) diff --git a/src/main.rs b/src/main.rs index 5b8f22d..7fa6433 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,6 +19,40 @@ pub struct AppState { core: core::Core, } +async fn jwt_validator( + mut req: ServiceRequest, + credentials: BearerAuth, +) -> Result { + let token = decode::( + &credentials.token(), + &DecodingKey::from_secret( + env::var("JWT_SECRET") + .expect("JWT_SECRET not found") + .as_ref(), + ), + &Validation::default(), + ); + match token { + Ok(token) => { + req.attach(vec![token.claims.role]); + req.headers_mut().insert( + HeaderName::from_lowercase(b"osma-username").unwrap(), + HeaderValue::from_str(&token.claims.name).unwrap(), + ); + + Ok(req) + } + Err(_) => { + req.attach(vec!["none".to_string()]); + req.headers_mut().insert( + HeaderName::from_lowercase(b"osma-username").unwrap(), + HeaderValue::from_str("no").unwrap(), + ); + Ok(req) + } + } +} + #[actix_rt::main] async fn main() -> std::io::Result<()> { dotenv().ok(); @@ -43,7 +77,13 @@ async fn main() -> std::io::Result<()> { core: core::Core::new(&db), })) .wrap(cors) + .service( + web::scope("/api") + .wrap(HttpAuthentication::bearer(jwt_validator)) .service(routes::apps) + ) + .service( + web::scope("/auth") .service(routes::signup) .service(routes::signin), }) diff --git a/src/routes.rs b/src/routes.rs index 1b88266..65996f6 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -1,6 +1,7 @@ use crate::types::*; use actix_web::{get, post, web, HttpRequest, HttpResponse, Responder}; use actix_web_grants::proc_macro::{has_any_permission, has_permissions}; + #[post("/signup")] pub async fn signup(app_data: web::Data, user: web::Json) -> impl Responder { response(app_data.core.signup(&user).await) @@ -15,6 +16,7 @@ pub async fn signin( } #[get("/apps")] +#[has_any_permission("user", "admin")] pub async fn apps(app_data: web::Data) -> impl Responder { HttpResponse::Ok().json(app_data.core.get_apps().await) }