From 130fd1fa60e7ebe804a2f1152fe33abbfe6d4852 Mon Sep 17 00:00:00 2001 From: Sebastian Pravda Date: Fri, 4 Nov 2022 11:48:48 +0100 Subject: [PATCH] feat: admin auth guard --- api/src/guards/request/session_auth.rs | 36 ++++++++++++++++++++++++++ api/src/lib.rs | 9 +++++-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/api/src/guards/request/session_auth.rs b/api/src/guards/request/session_auth.rs index b7a7f8f..d7a763a 100644 --- a/api/src/guards/request/session_auth.rs +++ b/api/src/guards/request/session_auth.rs @@ -36,3 +36,39 @@ impl<'r> FromRequest<'r> for CandidateAuth { } } + +pub struct AdminAuth(Candidate); + +impl Into for AdminAuth { + fn into(self) -> Candidate { + self.0 + } +} + +#[rocket::async_trait] +impl<'r> FromRequest<'r> for AdminAuth { + type Error = Option; + async fn from_request(req: &'r Request<'_>) -> Outcome { + let session_id = req.cookies().get("id").unwrap().name_value().1; + let conn = &req.rocket().state::().unwrap().conn; + + let uuid = match Uuid::parse_str(&session_id) { + Ok(uuid) => uuid, + Err(_) => return Outcome::Failure((Status::BadRequest, None)), + }; + + let session = CandidateService::auth(conn, uuid).await; + + match session { + Ok(model) => { + if model.is_admin { + Outcome::Success(AdminAuth(model)) + } else { + Outcome::Failure((Status::Forbidden, None)) + } + }, + Err(_) => Outcome::Failure((Status::Unauthorized, None)), + } + + } +} \ No newline at end of file diff --git a/api/src/lib.rs b/api/src/lib.rs index 442ee50..0e6613b 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -3,7 +3,7 @@ extern crate rocket; use std::net::SocketAddr; -use guards::request::session_auth::CandidateAuth; +use guards::request::session_auth::{CandidateAuth, AdminAuth}; use portfolio_core::services::candidate_service::CandidateService; use requests::{LoginRequest, RegisterRequest}; use rocket::http::Status; @@ -52,6 +52,11 @@ async fn validate(session: CandidateAuth) -> Result> { Ok(candidate.application.to_string()) } +#[get("/admin")] +async fn admin(session: AdminAuth) -> Result> { + Ok("Hello admin".to_string()) +} + #[post("/login", data = "")] async fn login(conn: Connection<'_, Db>, login_form: Json, ip_addr: SocketAddr) -> Result> { let db = conn.into_inner(); @@ -85,7 +90,7 @@ async fn start() -> Result<(), rocket::Error> { .attach(Db::init()) .attach(AdHoc::try_on_ignite("Migrations", run_migrations)) //.mount("/", FileServer::from(relative!("/static"))) - .mount("/", routes![create, login, hello, validate]) + .mount("/", routes![create, login, hello, validate, admin]) .register("/", catchers![]) .launch() .await