mirror of
https://github.com/danbulant/Portfolio
synced 2026-06-11 18:50:59 +00:00
feat: admin auth guard
This commit is contained in:
parent
82d718a7f0
commit
130fd1fa60
2 changed files with 43 additions and 2 deletions
|
|
@ -36,3 +36,39 @@ impl<'r> FromRequest<'r> for CandidateAuth {
|
|||
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AdminAuth(Candidate);
|
||||
|
||||
impl Into<Candidate> for AdminAuth {
|
||||
fn into(self) -> Candidate {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for AdminAuth {
|
||||
type Error = Option<String>;
|
||||
async fn from_request(req: &'r Request<'_>) -> Outcome<AdminAuth, (Status, Self::Error), ()> {
|
||||
let session_id = req.cookies().get("id").unwrap().name_value().1;
|
||||
let conn = &req.rocket().state::<Db>().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)),
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -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<String, Custom<String>> {
|
|||
Ok(candidate.application.to_string())
|
||||
}
|
||||
|
||||
#[get("/admin")]
|
||||
async fn admin(session: AdminAuth) -> Result<String, Custom<String>> {
|
||||
Ok("Hello admin".to_string())
|
||||
}
|
||||
|
||||
#[post("/login", data = "<login_form>")]
|
||||
async fn login(conn: Connection<'_, Db>, login_form: Json<LoginRequest>, ip_addr: SocketAddr) -> Result<String, Custom<String>> {
|
||||
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
|
||||
|
|
|
|||
Loading…
Reference in a new issue